簡體   English   中英

一個 class 調用另一個的方法

[英]One class calling another's method

為了整理我的(非常基本的)UI 代碼,我將按鈕和文本字段拆分為兩個單獨的類,其中一個主要用於創建框架並運行。 該按鈕需要在單擊時影響文本字段的內容,所以我使用了mouseEvent 但是,我不能調用我的文本字段的方法,因為文本字段 object 存儲在 main 中,所以沒有 object 可以使用方法。 所有方法都是公共的,所有屬性都是私有的。 所有的幫助都是apprciated,謝謝。

我嘗試將 object 設為public statiic無濟於事,我不確定我是否在這里遺漏了一些明顯的東西。

Fpor上下文, mouseEvent需要從文本字段object調用rename(String)方法,稱為tf,在class gui1中

編輯:
(主要的)

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

textfieldobj

buttonObject

你為什么要重新發明所有這些輪子? JTextFieldJButton是表示文本字段和按鈕的類,您不需要圍繞這些進行無操作包裝。

按鈕單擊時需要影響文本字段的內容

那是糟糕的設計; 您不希望您的按鈕需要了解文本字段; 如果是這樣,除了修改該確切的文本字段外,無法使用所述按鈕進行任何操作。

所以我使用了mouseEvent。

是的,這就是要使用的東西。 但是,只需.. 在知道按鈕和字段的地方添加偵聽器。 這可能是主要的,但這讓我們想到了另一點:

public static void main(...

這不是寫代碼的地方。 制作一個 object,在上面調用一些 '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!");
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM