简体   繁体   中英

Java Swing, having a JComponent and a JPanel

I'm trying to add a JComponent to a JPanel and then display it in a window. I'm pretty sure I've got it right, but only the button in the panel shows ups.

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

Only the button shows up in the created window. I'm not quite sure what I'm doing wrong.

By default a JPanel uses a FlowLayout and a FlowLayout respects the preferred size of all components added to it.

If RcComponent is a custom component then you need to override the getPreferredSize() method to return the Dimension of the component.

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

If you don't override this method, then the preferred size is 0, so there is nothing to display:

I believe you have missed the layout manager.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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