Why does getSize () not work for me here and why does it flicker when resizing?

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(); } } 
+4
source share
1 answer
  • The size of the JPanel not valid until validate() is called, usually as a result of calling pack() on the containing Window .

  • The final size is the result of a combination of factors, including the preferred dimensions of the enclosed components and the delegate UI panels for a particular Look and Feel.

  • JPanel default double buffering; no extra effort required. AnimationTest is an example.

+5
source

Source: https://habr.com/ru/post/1398339/


All Articles