将 JPanel 添加到 CENTER 以外的区域

Adding JPanels to regions other than CENTER

我目前正在阅读《深入浅出》的第 12 章 Java 关于制作 GUI 的内容。他们刚刚提到 JFrames 分为中心、北、南、东和西。然后本书使用 2 参数 add() 方法将指定的组件添加到具有该 JFrame 的指定区域。

我可以很好地向五个区域中的每一个添加一个 JButton。我还可以将我自己的 JPanel 添加到中心区域,周围环绕着 JButton。但是当我尝试将 JPanel 添加到中心以外的任何区域时,JPanel 没有出现。

在过去的一个小时里,我确实在整个网络和 Stack Overflow 上进行了搜索,但我没有遇到任何提及将 JPanel 添加到 JFrame 中心以外的任何区域的内容。所以我的问题是:是否可以将 JPanel 添加到 JFrame 的北、南、东或西区域?

提前感谢任何可以帮助我的人。

这是我在北部地区尝试使用我的 JPanel 运行 的代码:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BorderLayout;

public class StackQ {

    JFrame frame;

    public static void main(String [] args) {

        StackQ gui = new StackQ();
        gui.go();

    }

    public void go() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button = new JButton("location test");
        JButton button2 = new JButton("location test");
        JButton button3 = new JButton("location test");
        JButton button4 = new JButton("location test");

        myDrawPanel custom = new myDrawPanel();

        frame.getContentPane().add(button, BorderLayout.CENTER);
        frame.getContentPane().add(button2, BorderLayout.EAST);
        frame.getContentPane().add(button3, BorderLayout.WEST);
        frame.getContentPane().add(button4, BorderLayout.SOUTH);

        frame.getContentPane().add(custom, BorderLayout.NORTH);

        frame.setSize(300,300);
        frame.setVisible(true);
    }

}

class myDrawPanel extends JPanel {

    public void paintComponent(Graphics g) {

        int red = (int) (Math.random() * 255);
        int green = (int) (Math.random() * 255);
        int blue = (int) (Math.random() * 255);

        Color random = new Color(red, green, blue);
        g.setColor(random);
        g.fillOval(20,20,100,100);

    }
}

它可能更清楚,但这在 BorderLayout 文档中有描述:

The components are laid out according to their preferred sizes and the constraints of the container's size.... the CENTER component may stretch both horizontally and vertically to fill any space left over.

换句话说,CENTER 组件将被拉伸(如果需要)以填充应用程序,任何其他组件都需要指定 preferred-size 以便从CENTER.

JButton 根据按钮的内容默认指定首选大小。 JPanel 另一方面没有 - 它的首选大小取决于它的内容,而你的 JPanel 没有任何内容,因此它的首选大小为零。

简而言之,为您的 JPanel 指定首选尺寸,BorderLayout 将尝试为面板分配至少 space 的尺寸。

为了让这个 post 的任何潜在的未来观众得到想要的结果,我首先在我的 StackQ class 的最顶部导入了 Dimension class(这是需要,因为稍后在 go() 方法中使用的 setPreferredSize() 方法接受 Dimension 类型的参数):

import java.awt.Dimension;

然后我在 myDrawPanel 实例化后立即将此代码添加到 go() 方法 class:

Dimension dims = new Dimension(1366, 200);
custom.setPreferredSize(dims);

我选择 1366 作为宽度,因为我的屏幕就是这么大。

感谢大家的帮助!