一个类调用另一个类的方法

问题描述

为了整理我的(非常基本的)UI 代码,我将按钮和文本字段拆分为两个单独的类,其中一个主要用于创建框架并运行。该按钮需要在点击时影响文本字段的内容,所以我使用了 mouseEvent。但是,我无法调用我的文本字段的方法,因为文本字段对象存储在 main 中,因此没有可使用方法的对象。所有方法都是公共的,所有属性都是私有的。感谢所有帮助,谢谢。

我曾尝试使对象 public statiic 无济于事,我不确定这里是否有明显遗漏的东西。

在上下文中,mouseEvent 需要从类 gui1 中的文本字段对象(称为 tf)调用方法 rename(String)

编辑:
(主要)

public interface gui1{
    public static void main(String[] args) {

        textfieldobj tf = new textfieldobj("You should press button 1",100,150,20);   
        buttonObject b = new buttonObject("new button!");

(在 buttonObject 类中)

public class buttonObject extends JButton implements{
    JButton b;
    
    public buttonObject(String text){
        JButton b=new JButton(text); 
        b.setBounds(100,60,60);
        b.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {
                tf.setText("You Did It");//problem area
                b.setEnabled(false);

(在文本字段类中)

    public void setText(String newtext) {
        text = newtext;
        super.setText(newtext);
    }

解决方法

textfieldobj

buttonObject

你为什么要重新发明所有这些轮子? JTextFieldJButton 是表示文本字段和按钮的类,您无需对它们进行无用包装。

按钮需要在点击时影响文本框的内容

那是糟糕的设计;您不希望您的按钮需要了解文本字段;如果是这样,除了修改那个确切的文本字段之外,没有办法将所述按钮用于任何事情。

所以我使用了一个 mouseEvent。

是的,这就是使用。但是,只需.. 在知道按钮和字段的地方添加侦听器。这可能是主要的,但这让我们进入另一个点:

public static void main(...

这里不是写代码的地方。创建一个对象,在它上面调用一些 'go' 方法,这就是你的 main 应该有的一行。你想尽快摆脱static,你就是这样做的。

所以,例如:

public class MainApp {
    // frames,layout managers,whatever you need as well
    private final JButton switchTextButton;
    private final JTextField textField;

    public MainApp() {
        this.switchTextButton = new JButton("Switch it up!");
        this.textField = new JTextField();
        // add a panel,add these gui elements to it,etc.

        setupListeners();
    }

    private void setupListeners() {
        // hey,we have both the button and the textfield in scope here.
        switchTextButton.addActionListener(evt -> {
            textField.setText("Hello!");
        });
    }
}