在下面的例子中,我如何讓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