首页 文章

如何在JFrame中放置一个表和3个按钮

提问于
浏览
1

嗨朋友,我想在一帧中布局4个实体

  • 一个JTable

  • 3个按钮

为此,我创建了一个JFrame,并在该JFrame中放置了2个JPanel . 一个JPanel包含一个包含JTable的scrollablePanel . 另一个JPanel包含3个JButtons .

我期望输出如下:

enter image description here

但我的 table 不再可见,只有按钮可见 . 以下是我的代码

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class displayGui extends JFrame{
    private JPanel topPanel;
    private JPanel btnPanel;
    private JScrollPane scrollPane;

    public displayGui(JTable tbl){
        setTitle("Company Record Application");
        setSize(300,200);
        setBackground(Color.gray);


        topPanel = new JPanel();
        btnPanel = new JPanel();

        topPanel.setLayout(new BorderLayout());
        getContentPane().add(topPanel);
        getContentPane().add(btnPanel);
        scrollPane = new JScrollPane(tbl);
        topPanel.add(scrollPane,BorderLayout.CENTER);
        JButton addButton = new JButton("ADD");
        JButton delButton = new JButton("DELETE");
        JButton saveButton = new JButton("SAVE");

        btnPanel.add(addButton);
        btnPanel.add(delButton);

    }
}

我的主要方法中的代码:

displayGui dg = new displayGui(table);
dg.setVisible(true);

1 回答

  • 4

    您需要为框架上的每个面板指定一个位置...

    代替...

    getContentPane().add(topPanel);
    getContentPane().add(btnPanel);
    

    尝试...

    getContentPane().add(topPanel, BorderLayout.CENTER);
    getContentPane().add(btnPanel, BorderLayout.SOUTH);
    

    Side Note

    JFrame 的add方法会自动将对它的调用重定向到 contentPane ,所以从技术上讲,你只需要...

    add(topPanel, BorderLayout.CENTER);
    add(btnPanel, BorderLayout.SOUTH);
    

    Updated

    我还应该指出 JFrame 的默认布局管理器是 BorderLayout . 你可以通过简单地调用 JFrame#setLayout 来改变它,但是你所追求的结果最好与 BorderLayout ... FYI相遇

相关问题