簡體   English   中英

獲取Java Swing Component的內容

[英]Get contents of Java Swing Component

我需要獲取JPanel組件(選項卡之一)的內容,這是JTabbedPane的一部分。 從定義了JTabbedPane的類中,有一個事件偵聽器,它獲取當前選定的選項卡(在狀態更改時)。

這是示例代碼:

...
Component tab = jTabbedPane1.getSelectedComponent();
...

我需要在該選項卡中獲取所有組件。 例如:

Component[] comps = tab.getComponents(); // obviously it didn't work

我需要這個,因為我必須根據用戶權限禁用/啟用某些按鈕。

最好使用你自己的類,按鈕作為字段,然后能夠直接獲得組件所持按鈕的引用,或者更好的是,能夠與公共mutator方法交互,可以為你改變按鈕狀態(你想要的)盡可能向外界公開最少量的信息 - 封裝你的信息,例如:

// assuming the JButtons are in an array
public void setButtonEnabled(int buttonIndex, boolean enabled) {
   buttonArray[buttonIndex].setEnabled(enabled);
}

或者,如果按鈕位於使用按鈕文本String作為鍵的HashMap中的相同示例:

// assuming the JButtons are in an hashmap
public void setButtonEnabled(String buttonMapKey, boolean enabled) {
   JButton button = buttonMap.get(buttonMapKey);
   if (button != null) {
      button.setEnabled(enabled);
   }

}

此外,您的代碼表明您正在使用NetBeans來創建Swing代碼。 我建議您在完全理解Swing之前避免這樣做,而是使用教程來幫助您學習手動創建Swing,因為這將使您更好地理解Swing的基礎。 然后,當你理解它時,確定,使用代碼生成軟件來加快你的開發時間,只有現在你才能知道它在表面下做了什么,你將能夠更好地控制它。

運氣!

我會在面板中封裝這個邏輯。

如何擴展JPanel以創建包含按鈕的RoleAwareButtonPanel 然后,您可以傳入某種Role對象,並根據需要啟用面板啟用/禁用按鈕。

class Role {
  private boolean canCreate;
  private boolean canEdit;
  //etc...

  //getters and setters
}

class RoleAwareButtonPanel extends JPanel {

  private JButton createButton;
  private JButton editButton;

  //other stuff you need for your panel

  public void enableButtonsForRole(Role role) {
    createButton.setEnabled(role.canCreate());
    editButton.setEnabled(role.canEdit());
  }

}

暫無
暫無

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

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