简体   繁体   English

来自不同类的JButton

[英]JButton from different class


please help me with this issue. 请帮助我解决这个问题。
How to create a JButton from a different class, is it even possible? 如何从不同的类创建JButton,甚至有可能吗?
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. 最好的祝福。

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());": 在非静态类方法中执行的代码使用隐式this引用进行操作,该引用引用您创建并实例化的实例(如果是构造函数,则引用所创建的对象),因此您可以执行以下操作修复您的代码,方法调用在这里指的是您在“ jf.add(new Button());”行上创建的“ new Button()”:

Change 更改

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM