This is my first attempt at using BufferStrategy , and I really appreciate some tips.
1) Why do getSize() in the code below return 0 sizes until you resize the window? How can I immediately determine the size of the window?
2) Why, when getSize() returns something, is it not all window sizes? IE why is there a black bar at the bottom and right?
3) Is there a way to get rid of flicker when resizing a window?
import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferStrategy; import javax.swing.JFrame; import javax.swing.JPanel; public class BSTest extends JFrame { BufferStrategy bs; DrawPanel panel = new DrawPanel(); public BSTest() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(800,420); setLocationRelativeTo(null); setIgnoreRepaint(true); setVisible(true); createBufferStrategy(2); bs = getBufferStrategy(); panel.setIgnoreRepaint(true); add(panel); panel.drawStuff(); } public class DrawPanel extends JPanel { public void drawStuff() { while(true) { try { Graphics2D g = (Graphics2D)bs.getDrawGraphics(); g.setColor(Color.BLACK); System.out.println("W:"+getSize().width+", H:"+getSize().height); g.fillRect(0,0,getSize().width,getSize().height); bs.show(); g.dispose(); Thread.sleep(20); } catch (Exception e) { System.exit(0); } } } } public static void main(String[] args) { BSTest bst = new BSTest(); } }
source share