【问题标题】:One class calling another's method一个类调用另一种方法
【发布时间】:2021-01-11 21:06:41
【问题描述】:

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

我已尝试将对象 public statiic 设为无济于事,我不确定我在这里是否缺少明显的东西。

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

编辑:
(主要)

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

        textfieldobj tf = new textfieldobj("You should press button 1",100,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,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);
    }

【问题讨论】:

  • 请提供一些代码示例。
  • 是的对不起我忘了
  • 也许向buttonObject 添加一个参数,并传递您希望它为其设置文本的文本字段?然后将其称为buttonObject b = new buttonObject("new button!", tf)
  • 运行,但按钮和文本字段没有对话并且非常小。我开始认为这从一开始就是徒劳的努力,我应该像理智的人一样把它放在一个班级里吗?
  • 只是对标准改进的建议 - 类和接口名称 - 以及构造函数 - 应该以大写字母开头(“class ButtonObject”,“TextFieldObj”),而方法和变量以小写字母开头("setText", "字符串文本")

标签: java user-interface methods method-call


【解决方案1】:

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!");
        });
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多