junior_developer181
junior_developer181

Reputation: 105

How can I separate my swing components to different classes in java?

Just started to learn GUI, I've made a window with 2 buttons and 1 label and it worked.

After that I tried to separate the buttons to a different class and that worked too.

Then I wanted to separate my label to a different class (with the same strategy I used for buttons) but the text didn't show up.

My gui code:

public class guiMain extends JFrame {
 public guiMain(){
        super("app");

        setLayout(new BorderLayout());

        Buttons buttons = new Buttons(); //I can see the buttons
        add(buttons, BorderLayout.CENTER);

        Labels label = new Labels();
        add(label, BorderLayout.SOUTH);
      //  JLabel label = new JLabel("test");
      //  add(label, BorderLayout.SOUTH);

        setSize(400,200);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
 }
}

Labels class:

public class Labels extends JPanel {
    public void Labels(){
        setLayout(new FlowLayout(FlowLayout.LEFT));
        JLabel label = new JLabel("bottom left label ");
        add(label);
    }
}

Sorry if this question is too simple, I didn't find any solution.

Any suggestions for "good practice" would be appreciated also!

Upvotes: 0

Views: 281

Answers (1)

JavaMan
JavaMan

Reputation: 1217

You've created a method

public void Labels() {

But what you want is a constructor

public Labels() {

Upvotes: 1

Related Questions