按下按钮后,如何将GUI Driver类中的变量传送到ActionListener类?

时间:2015-04-18 01:01:05

标签: java swing variables actionlistener jlist

所以这是我的整个代码,只需看看我的" btnClick"按钮及其ActionListener类名为ButtonHandler。我试图将两个ListModel sortedlist和modelist转移到ActionListener类,所以我实际上可以编码来对数字进行排序并输出它们。我该怎么做?

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;

import java.awt.*;
import java.awt.event.*;

public class GUI_Driver 
{
    static int intTotal;

    static JLabel userPrompt;
    static JLabel numTitle;
    static JLabel sortTitle;
    static JLabel radsortTitle;
    static JLabel radasdsTitle;
    static JButton btnClick;

    static JRadioButton radAscending;
    static JRadioButton radDescending;
    static JRadioButton radSelection;   
    static JRadioButton radBubble;  
    static JRadioButton radInsertion;   
    static JRadioButton radQuick;
    static JList<Integer> ListofNum;
    static JList<Integer> ListofSortNum;

    //Blank labels
    static JLabel blank1;
    static JLabel blank2;
    static JLabel blank3;
    static JLabel blank4;
    static JLabel blank5;
    static JLabel blank6;
    static JLabel blank7;
    static JLabel blank8;
    static JLabel blank9;
    static JLabel blank10;
    static JLabel blank11;
    static JLabel blank12;
    static JLabel blank13;
    static JLabel blank14;
    static JLabel blank15;
    static JLabel blank16;
    static JLabel blank17;
    static JLabel blank18;
    static JLabel blank19;
    static JLabel blank20;
    static JLabel blank21;
    static JLabel blank22;
    static JLabel blank23;
    static JLabel blank24;
    static JLabel blank25;
    static JLabel blank26;
    static JLabel blank27;
    static JLabel blank28;


    private static void guiApp()
    {


        //Frame
        JFrame frame = new JFrame("Sorting Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        //Where the GUI is created:
        JMenuBar menuBar;
        JMenu menu, submenu;
        JMenuItem menuItem;

        //Create the menu bar.
        menuBar = new JMenuBar();

        //Build the first menu.
        menu = new JMenu("Options");
        menu.setMnemonic(KeyEvent.VK_A);
        menu.getAccessibleContext().setAccessibleDescription(
                "The only menu in this program that has menu items");
        menuBar.add(menu);

        //a group of JMenuItems
        menuItem = new JMenuItem("Help", KeyEvent.VK_T);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
        menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
        menu.add(menuItem);

        menuItem = new JMenuItem("RESTART");
        menuItem.setMnemonic(KeyEvent.VK_B);
        menu.add(menuItem);

        menuItem = new JMenuItem("EXIT");
        menuItem.setMnemonic(KeyEvent.VK_D);
        menu.add(menuItem);



        //a submenu
        menu.addSeparator();
        submenu = new JMenu("A submenu");
        submenu.setMnemonic(KeyEvent.VK_S);

        menuItem = new JMenuItem("An item in the submenu");
        menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_2, ActionEvent.ALT_MASK));
        submenu.add(menuItem);

        menuItem = new JMenuItem("Another item");
        submenu.add(menuItem);
        menu.add(submenu);

        frame.setJMenuBar(menuBar);





        //do stuff to control objects

        ListModel<Integer> modelist = new DefaultListModel<Integer>();
        ListModel<Integer> sortedlist = new DefaultListModel<Integer>();


        ((DefaultListModel<Integer>) sortedlist).addElement(1);
        ((DefaultListModel<Integer>) sortedlist).addElement(2);
        ((DefaultListModel<Integer>) sortedlist).addElement(3);
        ((DefaultListModel<Integer>) sortedlist).addElement(4);
        ((DefaultListModel<Integer>) sortedlist).addElement(20);
        ((DefaultListModel<Integer>) sortedlist).addElement(9);
        ((DefaultListModel<Integer>) sortedlist).addElement(120);
        ((DefaultListModel<Integer>) sortedlist).addElement(21);
        ((DefaultListModel<Integer>) sortedlist).addElement(64);
        ((DefaultListModel<Integer>) sortedlist).addElement(64);
        ((DefaultListModel<Integer>) sortedlist).addElement(886);
        ((DefaultListModel<Integer>) sortedlist).addElement(87);
        ((DefaultListModel<Integer>) sortedlist).addElement(78);
        ((DefaultListModel<Integer>) sortedlist).addElement(987);
        ((DefaultListModel<Integer>) sortedlist).addElement(90);
        ((DefaultListModel<Integer>) sortedlist).addElement(13);
        ((DefaultListModel<Integer>) sortedlist).addElement(23);

        ((DefaultListModel<Integer>) modelist).addElement(1);
        ((DefaultListModel<Integer>) modelist).addElement(2);
        ((DefaultListModel<Integer>) modelist).addElement(3);
        ((DefaultListModel<Integer>) modelist).addElement(4);
        ((DefaultListModel<Integer>) modelist).addElement(6);
        ((DefaultListModel<Integer>) modelist).addElement(9);
        ((DefaultListModel<Integer>) modelist).addElement(120);
        ((DefaultListModel<Integer>) modelist).addElement(21);
        ((DefaultListModel<Integer>) modelist).addElement(64);
        ((DefaultListModel<Integer>) modelist).addElement(64);
        ((DefaultListModel<Integer>) modelist).addElement(886);
        ((DefaultListModel<Integer>) modelist).addElement(87);
        ((DefaultListModel<Integer>) modelist).addElement(78);
        ((DefaultListModel<Integer>) modelist).addElement(987);
        ((DefaultListModel<Integer>) modelist).addElement(90);
        ((DefaultListModel<Integer>) modelist).addElement(13);
        ((DefaultListModel<Integer>) modelist).addElement(23);


        ListofNum = new JList<Integer>(modelist);
        ListofNum.setVisibleRowCount(3);
        ListofNum.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        ListofSortNum = new JList<Integer>(sortedlist);
        ListofSortNum.setVisibleRowCount(3);
        ListofSortNum.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


        JScrollPane listScroll = new JScrollPane(ListofNum);
        JScrollPane sortScroll = new JScrollPane(ListofSortNum);

        JButton btnSearch = new JButton("Search for a number");
        ButtonGroup SortingTypes = new ButtonGroup();
        ButtonGroup Directions = new ButtonGroup();
        btnClick = new JButton("Sort the Input");
        radAscending = new JRadioButton("Ascending  ", false);
        radAscending.setForeground(Color.black);
        radAscending.setBackground(Color.lightGray);
        radDescending = new JRadioButton("Descending", false);
        radDescending.setForeground(Color.black);
        radDescending.setBackground(Color.lightGray);

        radSelection = new JRadioButton("Selection ", false);
        radSelection.setBackground(Color.lightGray);
        radQuick = new JRadioButton("Quick       ", false);
        radQuick.setBackground(Color.lightGray);
        radBubble = new JRadioButton("Bubble     ", false);
        radBubble.setBackground(Color.lightGray);
        radInsertion = new JRadioButton("Insertion  ", false);
        radInsertion.setBackground(Color.lightGray);
        userPrompt = new JLabel("                 How many numbers do you wish to generate?");
        blank1 = new JLabel(" ");
        blank2 = new JLabel(" ");
        blank3 = new JLabel(" ");
        blank4 = new JLabel(" ");
        blank5 = new JLabel(" ");
        blank6 = new JLabel(" ");
        blank7 = new JLabel(" ");
        blank8 = new JLabel(" ");
        blank9 = new JLabel(" ");
        blank10 = new JLabel(" ");
        blank11 = new JLabel(" ");
        blank12 = new JLabel(" ");
        blank13 = new JLabel(" ");
        blank14 = new JLabel(" ");
        blank15 = new JLabel(" ");
        blank16 = new JLabel(" ");
        blank17 = new JLabel(" ");
        blank18 = new JLabel(" ");
        blank19 = new JLabel(" ");
        blank20 = new JLabel(" ");
        blank21 = new JLabel(" ");
        blank22 = new JLabel(" ");
        blank23 = new JLabel(" ");
        blank24 = new JLabel(" ");
        blank25 = new JLabel(" ");
        blank26 = new JLabel(" ");
        blank27 = new JLabel(" ");
        blank28 = new JLabel(" ");
        numTitle = new JLabel("Original Numbers");
        numTitle.setForeground(Color.red);
        sortTitle = new JLabel("Sorted Numbers  ");
        sortTitle.setForeground(Color.red);
        radsortTitle = new JLabel("Choose a Sorting Algorithms:");
        radsortTitle.setForeground(Color.blue);
        radasdsTitle = new JLabel("Choose an order:");
        radasdsTitle.setForeground(Color.blue);


        JTextField txtInput = new JTextField("Enter value here..");


        SortingTypes.add(radSelection);
        SortingTypes.add(radQuick);
        SortingTypes.add(radBubble);
        SortingTypes.add(radInsertion);

        Directions.add(radAscending);
        Directions.add(radDescending);


        //Panel
        JPanel leftpanel = new JPanel();
        JPanel rightpanel = new JPanel();
        JPanel textpanel = new JPanel();


        leftpanel.setLayout(new BoxLayout(leftpanel, BoxLayout.Y_AXIS));
        rightpanel.setLayout(new BoxLayout(rightpanel, BoxLayout.Y_AXIS));
        textpanel.setLayout(new BoxLayout(textpanel, BoxLayout.Y_AXIS));
        textpanel.setPreferredSize(new Dimension(50,50));

        //add label to panel
        leftpanel.add(radsortTitle, BorderLayout.WEST);
        leftpanel.add(Box.createRigidArea(new Dimension(10,10)));
        leftpanel.add(radSelection, BorderLayout.WEST);
        leftpanel.add(radQuick, BorderLayout.WEST);
        leftpanel.add(radBubble, BorderLayout.WEST);
        leftpanel.add(radInsertion, BorderLayout.WEST);
        leftpanel.add(Box.createRigidArea(new Dimension(10,10)));
        leftpanel.add(btnClick, BorderLayout.WEST);
        leftpanel.add(Box.createRigidArea(new Dimension(10,10)));
        leftpanel.add(Box.createRigidArea(new Dimension(10,10)));
        leftpanel.add(userPrompt, BorderLayout.WEST);
        leftpanel.add(Box.createRigidArea(new Dimension(10,10)));
        leftpanel.add(Box.createRigidArea(new Dimension(10,10)));
        leftpanel.add(Box.createRigidArea(new Dimension(10,10)));
        leftpanel.add(Box.createRigidArea(new Dimension(10,10)));
        leftpanel.add(numTitle, BorderLayout.WEST);
        leftpanel.add(listScroll, BorderLayout.WEST);

        textpanel.add(blank27, BorderLayout.CENTER);
        textpanel.add(blank28, BorderLayout.CENTER);
        textpanel.add(blank1, BorderLayout.CENTER);
        textpanel.add(blank2, BorderLayout.CENTER);
        textpanel.add(blank3, BorderLayout.CENTER);
        textpanel.add(blank4, BorderLayout.CENTER);
        textpanel.add(blank5, BorderLayout.CENTER);
        textpanel.add(blank6, BorderLayout.CENTER);
        textpanel.add(blank7, BorderLayout.CENTER);
        textpanel.add(blank8, BorderLayout.CENTER);
        textpanel.add(Box.createRigidArea(new Dimension(10,10)));
        textpanel.add(Box.createRigidArea(new Dimension(10,10)));
        textpanel.add(txtInput, BorderLayout.CENTER);
        textpanel.add(blank9, BorderLayout.CENTER);
        textpanel.add(blank10, BorderLayout.CENTER);
        textpanel.add(blank11, BorderLayout.CENTER);
        textpanel.add(blank12, BorderLayout.CENTER);
        textpanel.add(blank13, BorderLayout.CENTER);
        textpanel.add(blank14, BorderLayout.CENTER);
        textpanel.add(blank15, BorderLayout.CENTER);
        textpanel.add(blank16, BorderLayout.CENTER);
        textpanel.add(blank17, BorderLayout.CENTER);
        textpanel.add(blank18, BorderLayout.CENTER);
        textpanel.add(blank19, BorderLayout.CENTER);
        textpanel.add(blank20, BorderLayout.CENTER);
        textpanel.add(blank21, BorderLayout.CENTER);
        textpanel.add(blank22, BorderLayout.CENTER);
        textpanel.add(blank23, BorderLayout.CENTER);
        textpanel.add(blank24, BorderLayout.CENTER);
        textpanel.add(blank25, BorderLayout.CENTER);
        textpanel.add(blank26, BorderLayout.CENTER);

        rightpanel.add(radasdsTitle, BorderLayout.EAST);
        rightpanel.add(Box.createRigidArea(new Dimension(30,30)));
        rightpanel.add(radAscending, BorderLayout.EAST);
        rightpanel.add(radDescending, BorderLayout.EAST);
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(btnSearch);
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(Box.createRigidArea(new Dimension(10,10)));
        rightpanel.add(sortTitle, BorderLayout.EAST);
        rightpanel.add(sortScroll, BorderLayout.EAST);


        Container contentPane = frame.getContentPane();
        contentPane.add(leftpanel, BorderLayout.WEST);
        contentPane.add(rightpanel, BorderLayout.EAST);
        contentPane.add(textpanel, BorderLayout.CENTER);
        //The text to prompt user into inputting the numbers



        btnClick.addActionListener(new ButtonHandler());

        //set size
        frame.setSize(700,500);

        //set to visible
        frame.setVisible(true);

    }

            public static class ButtonHandler implements ActionListener
            {
                ListModel<Integer> modelist = new DefaultListModel<Integer>();
                ListModel<Integer> sortedlist = new DefaultListModel<Integer>();

                public  void Variablepass(ListModel<Integer> original, ListModel<Integer> sorted)
                {
                    this.modelist = original;
                    this.sortedlist = sorted;

                }

                public void actionPerformed(ActionEvent e)
                {

                    JFrame frame2 = new JFrame("Clickd");
                    frame2.setVisible(true);
                    frame2.setSize(200, 200);
                    JLabel labelcheck = new JLabel("u clicked");
                    JPanel checkpanel = new JPanel();
                    frame2.add(checkpanel);
                    checkpanel.add(labelcheck);
                    ((DefaultListModel<Integer>) sortedlist).addElement(69);

                }

            }
            public static void main(String[] args)
            {   
                javax.swing.SwingUtilities.invokeLater(new Runnable(){
                    public void run(){
                        guiApp();
                    }
                });
            }
}

1 个答案:

答案 0 :(得分:1)

解决这个问题的一种快捷方法(尽管不一定是最好的方法)是通过构造函数参数将GUI_Driver类的实例传递给Handler类,然后调用GUI_Driver的公共方法来获取其状态调用actionPerformed方法时列出。为了使其正常工作,GUI_Driver类中的字段应该是私有实例(非静态)字段。

更好的解决方案是通过类似于模型 - 视图 - 控制设计模式的东西将您的逻辑与GUI分离,但这可能会在此阶段或您的程序中过度杀死。

例如,在下面的代码中,我创建了一个扩展AbstractAction的SortHandler类(有点像超级duper ActionListener),并将一个对GUI类本身的引用传递给它的构造函数。我还给了GUI类公共方法来提取处理程序所需的信息,例如getOriginalNumberModel()getSelectedAlgorithm()方法,然后在actionPerformed方法中,我将这些信息调用到提取所需的信息。请注意,ButtonGroup将返回所选JRadioButton的ButtonModel。如果你设置了radiobutton的actionCommand,那么这些信息会很有用,如下面的代码所示:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.*;

@SuppressWarnings("serial")
public class GuiDriver2 extends JPanel {
   public static final String[] SortingAlgorithms = {"Selection", "Quick", "Bubble", "Insertion"};
   private static final int MAX_ELEMENT = 200;
   private DefaultListModel<Integer> originalNumberModel = new DefaultListModel<>();
   private JList<Integer> originalNumberList = new JList<>(originalNumberModel);
   private JButton sortButton = new JButton(new SortHandler(this, "Sort", KeyEvent.VK_S));
   private ButtonGroup sortAlgorithmGroup = new ButtonGroup(); 

   public GuiDriver2() {
      Random random = new Random();
      for (int i = 0; i < 20; i++) {
         originalNumberModel.addElement(random.nextInt(MAX_ELEMENT));
      }
      originalNumberList.setVisibleRowCount(7);
      originalNumberList.setPrototypeCellValue(1000000);

      JPanel sortingAlgorithmPanel = new JPanel(new GridLayout(0, 1));
      for (String sortAlgorithm : SortingAlgorithms) {
         JRadioButton rButton = new JRadioButton(sortAlgorithm);
         rButton.setActionCommand(sortAlgorithm);
         sortingAlgorithmPanel.add(rButton);
         sortAlgorithmGroup.add(rButton);
      }
      sortingAlgorithmPanel.setBorder(BorderFactory.createTitledBorder("Algorithm"));

      add(sortingAlgorithmPanel);
      add(new JScrollPane(originalNumberList));
      add(sortButton);
   }

   public DefaultListModel<Integer> getOriginalNumberModel() {
      return originalNumberModel;
   }

   public ButtonModel getSelectedAlgorithm() {
      return sortAlgorithmGroup.getSelection();
   }

   private static void createAndShowGui() {
      GuiDriver2 mainPanel = new GuiDriver2();

      JFrame frame = new JFrame("GuiDriver");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

// enum SortingAlgorithm {
//    SELECTION, QUICK, BUBBLE, INSERTION;
// }



@SuppressWarnings("serial")
class SortHandler extends AbstractAction {
   private GuiDriver2 guiDriver2;

   public SortHandler(GuiDriver2 guiDriver2, String name, int mnemonic) {
      super(name);
      putValue(MNEMONIC_KEY, mnemonic);
      this.guiDriver2 = guiDriver2;
   }

   @Override
   public void actionPerformed(ActionEvent e) {
      ButtonModel selectedRadioButton = guiDriver2.getSelectedAlgorithm();
      if (selectedRadioButton != null) {
         System.out.println("Sorting algorith selected is: " + selectedRadioButton.getActionCommand());
      }

      List<Integer> list = new ArrayList<>();
      DefaultListModel<Integer> originalModel = guiDriver2.getOriginalNumberModel();
      for (int i = 0; i < originalModel.getSize(); i++) {
         list.add(originalModel.get(i));
      }

      System.out.println("List: " + list);

   }
}