在下面的例子中,我如何让JPanel占用所有的JFrame?我将首选大小设置为800x420,但实际上只填充了792x391。如何使一个JFrame内的JPanel填充整个窗口?
import java.awt.Color;
import java.awt.Dimension;
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);
setLayout(new BorderLayout()); // edited line
setVisible(true);
setSize(800,420);
setLocationRelativeTo(null);
setIgnoreRepaint(true);
createBufferStrategy(2);
bs = getBufferStrategy();
panel.setIgnoreRepaint(true);
panel.setPreferredSize(new Dimension(800,420));
add(panel, BorderLayout.CENTER); // edited line
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();
}
}
Swing引擎有它自己的paint循环,你不需要while(true)。在你的面板类中重写'JComponent.paint(Graphics g)' – 2012-02-25 05:19:30
Hi @Joe,我试着在这里使用'BufferStrategy',为此你不使用'paint()',这就是为什么'while()'循环和'setIgnoreRepaint(true);'是什么。任何关于我如何能够填满整个窗户的想法? – 2012-02-25 05:23:00
是的,尝试将你的JPanel传递给'JFrame.setContentPane()' – 2012-02-29 00:43:55