Java Swing,有一个JComponent和一个JPanel



我正在尝试将JComponent添加到JPanel中,然后在窗口中显示它。我很确定我做对了,但只有面板上的按钮出现了。

//Component class
JFrame window=new JFrame("This is a window");
RcComponent component=new RcComponent();
JButton button= new Button("This is a  button");
JPanel panel=new JPanel();
panel.add(component);
panel.add(button);
window.add(panel);
window.setVisible(true);

只有按钮显示在创建的窗口中。我不太确定我做错了什么。

默认情况下,JPanel使用FlowLayout,FlowLayout尊重添加到其中的所有组件的首选大小。

如果RcComponent是自定义组件,则需要重写getPreferredSize()方法以返回组件的维度。

@Override
public Dimension getPreferredSize()
{
    return new Dimension(...);
}

如果不覆盖此方法,则首选大小为0,因此没有任何内容可显示:

我相信您已经错过了布局管理器。

https://www.google.com/#q=java%20layout

public static void main(String[] args) {
    JFrame window=new JFrame("This is a window");
    JButton button= new JButton("This is a  button");
    JLabel lbl= new JLabel("This is a  label");
    JPanel panel=new JPanel();
    panel.setLayout(new GridLayout());
    panel.add(button);
    panel.add(lbl);
    window.add(panel);
    window.setSize(new Dimension(200, 200));
    window.setLocationRelativeTo(null);
    window.addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
        }
    });
    window.setVisible(true);
}

最新更新