简体   繁体   English

contentPanel中的Java Swing调整大小面板

[英]Java Swing resize panel inside contentPanel

I have the following structure in a frame: 我在框架中具有以下结构:

Frame->contentPane panel->topPanel panel->table 框架-> contentPane面板-> topPanel面板-> table

This is the code: 这是代码:

private JPanel contentPane;
private JTable table;
private JPanel topPanel;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ShowList frame = new ShowList();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public ShowList() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 675, 433);

    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    topPanel = new JPanel();
    topPanel.setBounds(76, 76, 491, 245);
    contentPane.add(topPanel);
    topPanel.setLayout(null);

    table = new JTable();
    table.setBounds(0, 0, 491, 245);
    topPanel.add(table);
}

What I want to achieve is that when I resize the frame making the window bigger, the topPanel and the table that it is contained by this one resize also and do not stay the same size as they were before resizing the frame. 我要实现的是,当我调整框架的大小以使窗口更大时,该窗口所包含的topPanel和表格也将重新调整大小,并且不会保持与调整框架大小之前的大小相同。 I have read about Layouts but I can not make it work. 我已阅读过有关布局的信息,但无法使其正常运行。 Any suggestion? 有什么建议吗?

Use a LayoutManager to control the size and position of the components inside of your frame. 使用LayoutManager来控制框架内部组件的大小和位置。 Avoid setting the layout manager of your panels as null . 避免将面板的布局管理器设置为null

I recommend you to take a look at this link: "A Visual Guide to Layout Managers" to learn more about the different kinds of layouts you can use. 我建议您看一下以下链接: “布局管理器的可视指南”,以了解有关可以使用的各种布局的更多信息。

In your code, for example, I would use a BorderLayout: 例如,在您的代码中,我将使用BorderLayout:

contentPane.setLayout(new BorderLayout());

... ...

contentPane.add(topPanel, BorderLayout.CENTER);
topPanel.setLayout(new BorderLayout());

... ...

topPanel.add(table, BorderLayout.Center);

By the way, I suppose your class ShowList extends JFrame because methods like setDefaultCloseOperation gives you an error if not, right? 顺便说一句,我想您的类ShowList扩展了JFrame,因为像setDefaultCloseOperation这样的方法会给您一个错误,对吧?

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM