在实例化 JPanel 中编辑实例化 JList

Edit Instanced JList in an Instanced JPanel

我有一个包含 JTabbedPane 组件的 JFrame。 JTabbedPane 中的选项卡数量取决于先前确定的用户数据。 TabbedPane 中的每个选项卡都是由 JPanel 扩展的实例。每个 JPanel 都有一个 JList 和几个按钮。如何编辑特定的 JList? 我如何创建选项卡:

for (String s : variables.focusedHostnames) {
            clusterTab cluster = new clusterTab();
            tabbedPaneClusters.addTab(s, cluster);
        }

http://justpaste.it/maxv - 完整的 class,称为 clusterEndusersGui

http://justpaste.it/maxw - 这是用于创建选项卡的 clusterTab class


代码

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

// !! import assets.variables;

@SuppressWarnings("serial")
public class clusterEndusersGui extends JFrame {

   // !! I (hovercraft) added this so that the code runs
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            clusterEndusersGui gui = new clusterEndusersGui();
            gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            gui.pack();
            gui.setLocationRelativeTo(null);
            gui.setVisible(true);
         }
      });
   }

   public clusterEndusersGui() {
      initComponents();
   }

   private void initComponents() {
      panelQuery = new JPanel();
      labelWhere = new JLabel();
      comboBoxDataType = new JComboBox<>();
      comboBoxDataParameter = new JComboBox<>();
      fieldQueryData = new JTextField();
      btnFindUsers = new JButton();
      tabbedPaneClusters = new JTabbedPane();
      panel4 = new JPanel();
      listScrollPane = new JScrollPane();
      list1 = new JList();
      btnRemoveAll = new JButton();
      btnAddAll = new JButton();
      btnRemoveFromAll = new JButton();
      panel5 = new JPanel();
      btnApplyUpdates = new JButton();
      btnBackToConn = new JButton();
      // ======== this ========
      Container contentPane = getContentPane();
      // ======== panelQuery ========
      {
         panelQuery.setBorder(new TitledBorder("Find Users Query"));
         // ---- labelWhere ----
         labelWhere.setText("Where");
         // ---- comboBoxDataType ----
         comboBoxDataType.setModel(new DefaultComboBoxModel<>(
               new String[] { "User ID" }));
         // ---- comboBoxDataParameter ----
         comboBoxDataParameter.setModel(new DefaultComboBoxModel<>(
               new String[] { "Equals" }));
         // ---- btnFindUsers ----
         btnFindUsers.setText("Find Users");
         GroupLayout panelQueryLayout = new GroupLayout(panelQuery);
         panelQuery.setLayout(panelQueryLayout);
         panelQueryLayout.setHorizontalGroup(panelQueryLayout
               .createParallelGroup().addGroup(
                     panelQueryLayout
                           .createSequentialGroup()
                           .addContainerGap()
                           .addComponent(labelWhere)
                           .addGap(18, 18, 18)
                           .addComponent(comboBoxDataType,
                                 GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.DEFAULT_SIZE,
                                 GroupLayout.PREFERRED_SIZE)
                           .addGap(18, 18, 18)
                           .addComponent(comboBoxDataParameter,
                                 GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.DEFAULT_SIZE,
                                 GroupLayout.PREFERRED_SIZE)
                           .addGap(18, 18, 18)
                           .addComponent(fieldQueryData,
                                 GroupLayout.PREFERRED_SIZE, 200,
                                 GroupLayout.PREFERRED_SIZE)
                           .addPreferredGap(
                                 LayoutStyle.ComponentPlacement.RELATED,
                                 GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                           .addComponent(btnFindUsers).addContainerGap()));
         panelQueryLayout.setVerticalGroup(panelQueryLayout
               .createParallelGroup().addGroup(
                     panelQueryLayout
                           .createParallelGroup(GroupLayout.Alignment.BASELINE)
                           .addComponent(labelWhere)
                           .addComponent(comboBoxDataType,
                                 GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.DEFAULT_SIZE,
                                 GroupLayout.PREFERRED_SIZE)
                           .addComponent(comboBoxDataParameter,
                                 GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.DEFAULT_SIZE,
                                 GroupLayout.PREFERRED_SIZE)
                           .addComponent(fieldQueryData,
                                 GroupLayout.PREFERRED_SIZE,
                                 GroupLayout.DEFAULT_SIZE,
                                 GroupLayout.PREFERRED_SIZE)
                           .addComponent(btnFindUsers)));
      }
      // ======== tabbedPaneClusters ========
      {
         // ======== panel4 ========
         for (String s : variables.focusedHostnames) {
            clusterTab cluster = new clusterTab();
            tabbedPaneClusters.addTab(s, cluster);
         }
      }
      // ---- btnApplyUpdates ----
      btnApplyUpdates.setText("Apply all End User Updates");
      // ---- btnBackToConn ----
      btnBackToConn.setText("<< Go back to Cluster Connections");
      GroupLayout contentPaneLayout = new GroupLayout(contentPane);
      contentPane.setLayout(contentPaneLayout);
      contentPaneLayout
            .setHorizontalGroup(contentPaneLayout
                  .createParallelGroup()
                  .addGroup(
                        contentPaneLayout
                              .createSequentialGroup()
                              .addContainerGap()
                              .addGroup(
                                    contentPaneLayout
                                          .createParallelGroup()
                                          .addGroup(
                                                contentPaneLayout
                                                      .createSequentialGroup()
                                                      .addComponent(
                                                            tabbedPaneClusters)
                                                      .addContainerGap())
                                          .addGroup(
                                                GroupLayout.Alignment.TRAILING,
                                                contentPaneLayout
                                                      .createSequentialGroup()
                                                      .addGap(0, 0,
                                                            Short.MAX_VALUE)
                                                      .addComponent(
                                                            panelQuery,
                                                            GroupLayout.PREFERRED_SIZE,
                                                            GroupLayout.DEFAULT_SIZE,
                                                            GroupLayout.PREFERRED_SIZE)
                                                      .addGap(98, 98, 98))
                                          .addGroup(
                                                GroupLayout.Alignment.TRAILING,
                                                contentPaneLayout
                                                      .createSequentialGroup()
                                                      .addComponent(
                                                            btnBackToConn)
                                                      .addPreferredGap(
                                                            LayoutStyle.ComponentPlacement.RELATED,
                                                            GroupLayout.DEFAULT_SIZE,
                                                            Short.MAX_VALUE)
                                                      .addComponent(
                                                            btnApplyUpdates)
                                                      .addContainerGap()))));
      contentPaneLayout
            .setVerticalGroup(contentPaneLayout.createParallelGroup()
                  .addGroup(
                        contentPaneLayout
                              .createSequentialGroup()
                              .addGap(11, 11, 11)
                              .addComponent(panelQuery,
                                    GroupLayout.PREFERRED_SIZE, 51,
                                    GroupLayout.PREFERRED_SIZE)
                              .addPreferredGap(
                                    LayoutStyle.ComponentPlacement.RELATED)
                              .addComponent(tabbedPaneClusters,
                                    GroupLayout.PREFERRED_SIZE, 390,
                                    GroupLayout.PREFERRED_SIZE)
                              .addPreferredGap(
                                    LayoutStyle.ComponentPlacement.RELATED)
                              .addGroup(
                                    contentPaneLayout
                                          .createParallelGroup(
                                                GroupLayout.Alignment.BASELINE)
                                          .addComponent(btnApplyUpdates)
                                          .addComponent(btnBackToConn))
                              .addContainerGap(15, Short.MAX_VALUE)));
      pack();
      setLocationRelativeTo(getOwner());
   }

   public static void printTabNames() {
      System.out.println("Tab Name: " + tabbedPaneClusters.getTitleAt(0));
   }

   private JPanel panelQuery;
   private JLabel labelWhere;
   private JComboBox<String> comboBoxDataType;
   private JComboBox<String> comboBoxDataParameter;
   private JTextField fieldQueryData;
   private JButton btnFindUsers;
   private static JTabbedPane tabbedPaneClusters;
   private JPanel panel4;
   private JScrollPane listScrollPane;
   private JList list1;
   private JButton btnRemoveAll;
   private JButton btnAddAll;
   private JButton btnRemoveFromAll;
   private JPanel panel5;
   private JButton btnApplyUpdates;
   private JButton btnBackToConn;
}

class clusterTab extends JPanel {
   public clusterTab() {
      initComponents();
   }

   public void getUsers(ActionEvent e) {
      clusterEndusersGui.printTabNames();
   }

   private void initComponents() {
      final JScrollPane listScrollPane;
      final JList list1;
      final JButton btnRemoveAll;
      final JButton btnAddAll;
      final JButton btnRemoveFromAll;
      final DefaultListModel listItems;
      listScrollPane = new JScrollPane();
      list1 = new JList();
      btnRemoveAll = new JButton();
      btnAddAll = new JButton();
      btnRemoveFromAll = new JButton();
      listItems = new DefaultListModel();
      listItems.addElement("Test");
      // ======== panel4 ========
      {
         // List
         {
            list1.setModel(listItems);
         }
         // ======== listScrollPane ========
         {
            listScrollPane.setViewportView(list1);
         }
         // ---- btnRemoveAll ----
         btnRemoveAll.setText("Remove all from Cluster");
         btnRemoveAll
               .setToolTipText("Remove all selected End Users from this Cluster");
         // ---- btnAddAll ----
         btnAddAll.setText("Add all to Cluster");
         btnAddAll
               .setToolTipText("Update All End Users, set their Home Cluster to this one");
         btnAddAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
               getUsers(e);
            }
         });
         // ---- btnRemoveFromAll ----
         btnRemoveFromAll.setText("Remove from All Clusters");
         btnRemoveFromAll
               .setToolTipText("Remove selected user from all Clusters except this one");
         GroupLayout panel4Layout = new GroupLayout(this);
         this.setLayout(panel4Layout);
         panel4Layout.setHorizontalGroup(panel4Layout.createParallelGroup()
               .addGroup(
                     panel4Layout
                           .createSequentialGroup()
                           .addContainerGap()
                           .addComponent(listScrollPane,
                                 GroupLayout.PREFERRED_SIZE, 378,
                                 GroupLayout.PREFERRED_SIZE)
                           .addGap(18, 18, 18)
                           .addGroup(
                                 panel4Layout
                                       .createParallelGroup(
                                             GroupLayout.Alignment.LEADING,
                                             false)
                                       .addComponent(btnRemoveAll,
                                             GroupLayout.DEFAULT_SIZE,
                                             GroupLayout.DEFAULT_SIZE,
                                             Short.MAX_VALUE)
                                       .addComponent(btnAddAll,
                                             GroupLayout.DEFAULT_SIZE,
                                             GroupLayout.DEFAULT_SIZE,
                                             Short.MAX_VALUE)
                                       .addComponent(btnRemoveFromAll,
                                             GroupLayout.DEFAULT_SIZE,
                                             GroupLayout.DEFAULT_SIZE,
                                             Short.MAX_VALUE))
                           .addContainerGap(187, Short.MAX_VALUE)));
         panel4Layout.setVerticalGroup(panel4Layout.createParallelGroup()
               .addGroup(
                     panel4Layout
                           .createSequentialGroup()
                           .addContainerGap()
                           .addGroup(
                                 panel4Layout
                                       .createParallelGroup()
                                       .addGroup(
                                             panel4Layout
                                                   .createSequentialGroup()
                                                   .addComponent(btnRemoveAll)
                                                   .addGap(18, 18, 18)
                                                   .addComponent(btnAddAll)
                                                   .addGap(18, 18, 18)
                                                   .addComponent(
                                                         btnRemoveFromAll)
                                                   .addGap(0, 0,
                                                         Short.MAX_VALUE))
                                       .addComponent(listScrollPane,
                                             GroupLayout.DEFAULT_SIZE, 304,
                                             Short.MAX_VALUE))
                           .addContainerGap()));
      }
   }
}

// !! A dummy class that I (hovercraft) created just so I could get your code to work
class variables {
   public static String[] focusedHostnames = { "1", "2", "3", "4", "5", "6",
         "7" };
}

这个问题与更一般的问题 "how do I get a reference to one object out of several" 没有什么不同,一个好的解决方案是将您的对象,这里是您的 JPanel "views" 放入一个集合,例如 ArrayList,如果你希望你的项目可以通过索引检索,或者如果你希望你的项目可以通过非数字对象键(如字符串)检索,则可能是 HashMap。正如他们所说,细节决定成败。与大多数 GUI 工作一样,您应该努力将程序的逻辑、模型与其 GUI 显示或视图分开,这也应该有助于您获取和操作核心数据。

至于你的具体情况,有点难说,因为你已经在链接中发布了很长一段代码。我要求您避免使用链接,因为这里的许多人无法访问它们,并且由于您是在寻求志愿者的帮助,因此您应该让其他人尽可能容易地帮助您。如果您仍然遇到困难,请考虑在这里创建并发布您的程序的一个更小版本的问题,一个除了尝试演示您正在尝试做的事情之外没有任何功能的 minimal example program.


编辑
我查看了您的一些代码,发现您的 clusterTab,一个应重命名为 ClusterTab 的 class,将其大部分 Swing 组件及其模型声明为 init() 方法中的局部变量,从而生成这些变量在 class 的其余部分不可见。不要对关键变量执行此操作,尤其是 listItems 变量,而是将它们设为私有字段,以便它们具有实例级可见性。


此外,不要将 JTabbedPane 变量设为静态,因为这表明您的设计已损坏,需要修复。 printTabNames() 方法也不应该是静态的。


编辑 2
有些人在玩弄您的代码——如果您试图获取对当前选定选项卡的引用,您可能根本不需要 ArrayList,因为 JTabbedPane 可以为您完成这项工作。例如:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


@SuppressWarnings("serial")
public class ClusterEndusersGui2 extends JPanel {
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            ClusterEndusersGui2 mainPanel = new ClusterEndusersGui2();
            JFrame gui = new JFrame("GUI");
            gui.add(mainPanel);
            gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            gui.pack();
            gui.setLocationRelativeTo(null);
            gui.setVisible(true);
         }
      });
   }

   public ClusterEndusersGui2() {
      initComponents();
   }

   private void initComponents() {
      someButton = new JButton("Selected Tabbed Pane");
      tabbedPaneClusters = new JTabbedPane();
      for (String s : Variables2.focusedHostnames) {
         ClusterTab2 cluster = new ClusterTab2(s);
         tabbedPaneClusters.addTab(s, cluster);
      }

      add(tabbedPaneClusters);
      add(someButton);

      someButton.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            ClusterTab2 tabbedPane = (ClusterTab2) tabbedPaneClusters.getSelectedComponent();
            if (tabbedPane != null) {
               System.out.println("Selected Tab: " + tabbedPane.getName());
            }
         }
      });
   }

   public void printTabNames() {
      System.out.println("Tab Name: " + tabbedPaneClusters.getTitleAt(0));
   }

   private JTabbedPane tabbedPaneClusters;
   private JButton someButton;
}

@SuppressWarnings("serial")
class ClusterTab2 extends JPanel {
   private DefaultListModel<String> listItems;

   public ClusterTab2(String name) {
      setName(name);
      initComponents();
   }

   public void getUsers(ActionEvent e) {
      //!! ClusterEndusersGui2.printTabNames();
   }

   private void initComponents() {
      final JScrollPane listScrollPane;
      final JList<String> list1;
      final JButton btnRemoveAll;
      final JButton btnAddAll;
      final JButton btnRemoveFromAll;
      listScrollPane = new JScrollPane();
      list1 = new JList<>();
      list1.setPrototypeCellValue("                            ");
      btnRemoveAll = new JButton();
      btnAddAll = new JButton();
      btnRemoveFromAll = new JButton();
      listItems = new DefaultListModel<>();
      listItems.addElement("Test");
      list1.setModel(listItems);
      listScrollPane.setViewportView(list1);

      // ---- btnRemoveAll ----
      btnRemoveAll.setText("Remove all from Cluster");
      btnAddAll.setText("Add all to Cluster");
      btnAddAll.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            getUsers(e);
         }
      });
      btnRemoveFromAll.setText("Remove from All Clusters");

      JPanel btnPanel = new JPanel(new GridLayout(0, 1, 4, 4));
      btnPanel.add(btnRemoveAll);
      btnPanel.add(btnAddAll);
      btnPanel.add(btnRemoveFromAll);

      btnRemoveAll.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            listItems.removeAllElements();
         }
      });
      btnAddAll.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            listItems.addElement("Fubar!");
         }
      });

      JPanel btnWrapPanel = new JPanel(new GridBagLayout());
      btnWrapPanel.add(btnPanel);

      add(listScrollPane);
      add(btnWrapPanel);
   }
}

class Variables2 {
   public static String[] focusedHostnames = { 
      "1", "2", "3", "4", "5", "6", "7" 
   };
}