在Instanced JPanel中编辑实例化JList

时间:2015-07-12 02:15:56

标签: java swing jpanel jlist jtabbedpane

我有一个具有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 - 完整的类,名为clusterEndusersGui

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

代码

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" };
}

1 个答案:

答案 0 :(得分:3)

这个问题与“如何从多个对象中引用一个对象”这个更一般的问题没什么不同,一个好的解决方案是把你的对象,这里的JPanel“视图”放到一个集合中,比如作为ArrayList,如果希望通过索引检索项目,或者如果希望通过非数字对象键(如String)检索项目,则可以使用HashMap。他们所说的魔鬼就是细节。与大多数GUI工作一样,您应该努力将程序的逻辑(模型)与GUI显示或视图分开,这也可以帮助您获取和操作核心数据。

至于你的具体情况,有点难以分辨,因为你在链接中发布了一长串代码。我请你避免使用链接,因为很多人都无法访问它们,而且由于你要求志愿者提供帮助,你应该让其他人尽可能地帮助你。如果您仍然遇到困难,请考虑在此处创建并在此处发布您的问题,这是一个小得多的程序版本,除了试图证明您要执行的操作之外没有任何功能,minimal example program。< / p>

修改
我已经回顾了你的一些代码,并且看到你的clusterTab,一个应该重命名为ClusterTab的类,在init()方法中将其大部分Swing组件及其模型声明为局部变量,使得这些变量在其余部分中不可见班上的。不要对关键变量执行此操作,尤其是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" 
   };
}