如何在JFrame中创建JPanel填充整个窗口? [英] How to make a JPanel inside a JFrame fill the whole window?

查看:667
本文介绍了如何在JFrame中创建JPanel填充整个窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the below example, how can I get the JPanel to take up all of the JFrame? I set the preferred size to 800x420 but it only actually fills 792x391.

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


推荐答案

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

If you are having only one panel in frame and nothing else then try this:


  • 在框架中设置BorderLayout。

  • 使用BorderLayout.CENTER添加面板框架

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

May be this is happening because of while loop in JPanel.(Not sure why? finding actual reason. Will update when find it.) If you replace it with paintComponent(g) method all works fine:

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.

这篇关于如何在JFrame中创建JPanel填充整个窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆