繁体   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