簡體   English   中英

NetBeans Matisse-從另一個類訪問jframe組件

[英]NetBeans Matisse - Access jframe component from another class

Netbeans的Matisse代碼被阻止。 我的問題是我必須將另一個包中的另一個類的setBackground設置為JLabel ,但是我不能這樣做,因為由於其私有和受阻止的代碼,我無法訪問JLabel

有什么解決辦法嗎?

“ Netbeans的Matisse代碼被阻止”

您可以按此處所示對其進行編輯

“因為我的JLabel由於其私有代碼和已阻止的代碼而無法訪問”

只需為另一個類中的標簽編寫一個getter方法

public class OtherClass .. {
    private JLabel jLabel1;

    public JLabel getLabel() {
        return jLabel1;
    }
}

import otherpackage.OtherClass;

public class MainFrame extends JFrame {
    private OtherClass otherClass;
    ...
    private void jButtonActionPerformed(ActionEvent e) {
         JLabel label = otherClass.getLabel();
         label.setBackground(...)
    }
}

“從另一個類訪問jframe組件”

聽起來您正在使用多個幀。 請參閱使用多個JFrame,良好/不良做法?


更新

“我有一個由馬蒂斯制成的主框架,但是由於某些原因,當另一個類別中發生X驗證時,我必須設置另一個類別的馬蒂斯內部的textField背景”

然后,您可以做的是將Main框架的引用傳遞給另一個類,並在Main框架中有一個setter 類似於(我將提供訪問界面)

public interface Gettable {
    public void setLabelBackground(Color color);
}

public class Main extends JFrame implements Gettable {
    private JLabel jLabel1;
    private OtherPanel otherPanel;

    public void initComponents() {
        otherPanel = new OtherPanel(Main.this); // see link above to edit this area
    }

    @Override
    public void setLabelBackground(Color color) {
        jLabel1.setBackground(color);
    }
}

public class OtherPanel extends JPanel {
    private Gettable gettable;

    public OtherPanel(Gettable gettable) {
        this.gettable = gettable;
    }

    private void jButtonActionPerformed(ActionEvent e) {
        gettable.setLabelBackground(Color.RED);
    }
}
  • 使用JLabel創建類的偵聽器,並帶有更改標簽背景的方法
  • 在使用JLabel的類中實現它
  • 使用JLabel將其他類(您要從中更改BG)的偵聽器設置為類的偵聽器
  • 在您需要任何功能之后更改背景。

暫無
暫無

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

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