Reputation: 6253
I tried to create a class which extends JComponents, but when i add it to a Box, i can see only an empty window. Can you help me? What i Expect to get, is a window with 3 horizontal boxes containing a label and a button next to it.
public class MyWindowComp{
public MyWindowComp(){
JFrame frame = new JFrame("myFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel wp = new JPanel(new BorderLayout());
Box vBox = new Box(BoxLayout.Y_AXIS);
MyComponent one = new MyComponent();
MyComponent two = new MyComponent();
MyComponent three = new MyComponent();
vBox.add(one);
vBox.add(two);
vBox.add(three);
wp.add(vBox);
frame.add(wp);
frame.setVisible(true);
}}
public class MyComponent extends JComponent {
private Box box;
private JButton b;
private JLabel l;
public MyComponent(){
this.box = new Box(BoxLayout.X_AXIS);
this.l = new JLabel ("label");
this.l.setVisible(true);
this.b = new JButton("button");
this.b.setVisible(true);
box.add(l);
box.add(b);
}}
Obtained:
Expected:
Upvotes: 0
Views: 219
Reputation: 324197
You create instances of MyComponent component, but you never add any components to your component so there is nothing to paint.
In the constructor of your MyComponent classe you create a Box and then you add two components to the Box, but you don't add the Box to your component.
The solution is to get rid of the Box and add the button and label directly to your component:
public MyComponent()
{
setLayout( new BoxLayout(this, BoxLayout.X_AXIS) );
l = new JLabel ("label");
b = new JButton("button");
add(l);
add(b);
}
Also:
JPanel
, since the purpose of a panel is to contain other components.Upvotes: 3
Reputation: 7273
Seem like a homework, I will try answer as a teacher
you forgot the method to load your MyWindowComp() method
if it loaded, and it show only menu bar, then you forget to set it size with frame.setSize(x,y);
Upvotes: 0