有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

contentPanel内的Java Swing调整大小面板

我的框架结构如下:

框架->;内容窗格面板->;topPanel面板->;桌子

代码如下:

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

我想实现的是,当我调整框架的大小使窗口变大时,topPanel和它所包含的表也会调整大小,并且不会保持与调整框架大小之前相同的大小。我读过关于布局的书,但我不能让它工作。有什么建议吗


共 (1) 个答案

  1. # 1 楼答案

    使用布局管理器来控制框架内组件的大小和位置。避免将面板的布局管理器设置为null

    我建议你看看这个链接:"A Visual Guide to Layout Managers"来了解更多关于你可以使用的不同类型的布局

    例如,在您的代码中,我将使用BorderLayout:

    contentPane.setLayout(new BorderLayout());
    

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

    topPanel.add(table, BorderLayout.Center);
    

    顺便说一句,我想你的类ShowList扩展了JFrame,因为setDefaultCloseOperation之类的方法会给你一个错误,如果不是这样的话,对吗

    我希望有帮助