如何在JFrame中创建JPanel填充整个窗口?

在下面的示例中,如何让JPanel占用所有JFrame? 我将首选大小设置为800×420,但它实际上只填充792×391。

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(); } } 

如果你只有一个框架而没有别的,那么试试这个:

  • 在框架中设置BorderLayout。
  • 使用BorderLayout.CENTER在框架中添加面板

可能是因为JPanel中的while循环而发生这种情况。(不知道为什么?找到实际原因。找到它时会更新。)如果用paintComponent(g)方法替换它,一切正常:

 public BSTest() { //--- your code as it is add(panel, BorderLayout.CENTER); //-- removed panel.drawStuff(); } public class DrawPanel extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.BLACK); System.out.println("W:" + getSize().width + ", H:" + getSize().height); g2d.fillRect(0, 0, getSize().width, getSize().height); } } //your code as it is. 

这是使用pack的替代方案。

 import java.awt.Color; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JPanel; public class PackExample extends JFrame { public PackExample(){ JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(800,600)); panel.setBackground(Color.green); add(panel); pack(); setVisible(true); } public static void main(String[] args){ new PackExample(); } } 

如果你想用整个JPanel填充JFrame,你需要将setUndecorated设置为true,即frame.setUndecorated(true); 。 但现在你必须担心你的MAXIMIZE

这让我永远想出来,但它实际上是最简单的代码。 只需创建父面板并传递GridLayout,然后像这样添加子面板。

 JPanel parentPanel= new JPanel(new GridLyout()); JPanel childPanel= new JPanel(); parentPanel.add(childPanel);