为什么在构造的JPanel中表示组件的某些属性,但不表达其他属性?

问题描述 投票:0回答:1

我正在开始一个程序,在其中构造一个JFrame并使用我创建的另一个名为StartPanel的类向其添加JPanel。在构造JPanel时,它将添加StartPanel类中定义的JLabel。然后将该面板添加到JFrame。标签的某些属性在GUI中表示(它会自动添加到面板中,可以在面板上添加红色边框,可以更改文本),而有些则不是。例如,我不能更改标签的位置或大小。

[到目前为止,我所读到的所有内容(我认为)都同意我的方法或未作太多澄清。此外,我在StartPanel和标签上都添加了边框,以可视化问题并确认标签没有改变其大小。我无法调整标签的大小或位置属性。如何解决此问题并控制标签的属性?

另外,我知道我可以通过不通过单独的类构造面板并在同一函数中声明标签来规避整个问题。但是,该项目将相当大,因此我希望有一个可以在需要时构造面板的类系统。

代码时间:

我使用类构造框架和面板的地方:

public class StartFrame {

    public StartFrame() {
        JFrame frame = new JFrame("Constuctor tests");
        frame.setSize(800, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        JPanel startPanel = new StartPanel();  //This is where I construct the panel
        startPanel.setVisible(true);
        startPanel.setBorder(BorderFactory.createLineBorder(Color.blue)); //Visualize the panel
        frame.add(startPanel);

    }

}

StartPanel类:

public class StartPanel extends JPanel {

    public StartPanel() {
        JLabel label = new JLabel("This is a label");
        label.setLocation(100, 100); //It is not at 100,100
        label.setSize(200, 100); //It is not a box this large
        label.setBorder(BorderFactory.createLineBorder(Color.red)); //Done as to visualize it
        label.setVisible(true);
        add(label);

    }
}

最后是产品图片:The final product

非常感谢您的帮助!

java swing jframe jpanel
1个回答
1
投票

您可以通过布局管理器控制元素的大小和布局。您可以阅读all about it here

为了让您入门,让我们看一下为什么您的屏幕看起来像这样。

JFrame的默认布局是BorderLayout。 BorderLayout接收它的第一个子对象(在此例中为JPanel),将其放置在中心并拉伸以占据容器的全部宽度(在本例中为JFrame)。这就是为什么您的StartPanel占用JFrame的全部大小的原因。 Here you can read more about how to use the border layout.

JPanel的默认布局是FlowLayout。在流程布局中,每个子元素(在本例中为JLabel)都添加到中间顶部。添加更多子级后,它们会在一行中彼此相邻添加。 FlowLayout允许其子代占用所需的大小。在这种情况下,JLable仅需要一个小矩形来显示文本,因此这就是JLabel的大小。 Go here to learn more about the FlowLayout.

© www.soinside.com 2019 - 2024. All rights reserved.