Robdll
Robdll

Reputation: 6253

Java Swing - how do i paint this class which extends JComponent

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: enter image description here

Expected: enter image description here

Upvotes: 0

Views: 219

Answers (2)

camickr
camickr

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:

  1. there is no need to use setVisible(true) on each components since components are visible by default (except for top level containers like JFrame).
  2. Usually you would extend JPanel, since the purpose of a panel is to contain other components.

Upvotes: 3

Sruit A.Suk
Sruit A.Suk

Reputation: 7273

Seem like a homework, I will try answer as a teacher

  1. you forgot the method to load your MyWindowComp() method

  2. if it loaded, and it show only menu bar, then you forget to set it size with frame.setSize(x,y);

Upvotes: 0

Related Questions