Lennotoecom
Lennotoecom

Reputation: 31

JButton from different class


please help me with this issue.
How to create a JButton from a different class, is it even possible?
The first button is here the second is not:

import javax.swing.JButton;
import javax.swing.JFrame;

public class Source {

    public static void main(String[] args){
        JFrame jf = new JFrame();
        jf.setLayout(null);
        jf.setSize(640, 360);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton jb = new JButton("first button");
        jb.setBounds(50, 50, 110, 20);

        jf.add(jb);
        jf.add(new Button());
    }

}

class Button extends JButton {
    public Button(){
        JButton jb = new JButton("second button");
        jb.setBounds(0, 0, 110, 20);
    }
}

Thank you in advance. Best regards.

Upvotes: 1

Views: 298

Answers (1)

NESPowerGlove
NESPowerGlove

Reputation: 5496

Code executing within a non static class method operate with an implicit this reference referring to the instance that you created and called those methods with (or in the case of a constructor, a reference to what you are creating), so you would do the following to fix your code, where the method calls refer to here that "new Button()" you created on the line of "jf.add(new Button());":

Change

    JButton jb = new JButton("second button");
    jb.setBounds(0, 0, 110, 20);

to

    setText("second button");
    setBounds(0, 0, 110, 20);

Upvotes: 4

Related Questions