Reputation: 61
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.
Upvotes: 0
Views: 90
Reputation: 324108
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:
Upvotes: 2
Reputation: 1776
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);
}
Upvotes: 0