简体   繁体   中英

Get contents of Java Swing Component

I need to get contents of JPanel component (one of tabs), which a part of JTabbedPane. From class where JTabbedPane is defined there is an event listener which gets current selected tab (on state change).

Here is sample code:

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

I need to get all components in that tab. For example:

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

I need this, because I have to disable/enable some buttons depending user rights.

Better to use your own class with the buttons as fields and then be able to directly obtain references to the buttons held by the components, or better still, be able to interact with public mutator methods that can change the button state for you (you want to expose the least amount of information to the outside world as possible -- to encapsulate your information), something like:

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

Or same example for if the buttons are in a HashMap that uses the button text String as the key:

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

}

Also, your code suggests that you're using NetBeans to create your Swing code. I suggest that you avoid doing this until you fully understand Swing, that instead you use the tutorials to help you to learn to create Swing by hand as this will give you a much better understanding of the underpinnings of Swing. Then later when you understand it well, sure, use code-generation software to speed up your development time, only now you'll know what it's doing under the surface and you will be able to control it better.

Luck!

I would encapsulate this logic in the panel.

How about extending JPanel to create a RoleAwareButtonPanel that contains your buttons. You could then pass in some kind of Role object and have your panel enable/disable buttons as appropriate.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM