简体   繁体   中英

How do I make the the variables in my GUI Driver class to be transferred to the ActionListener class after a button is pressed?

So this is my entire code, just look at my "btnClick" button and its ActionListener class called ButtonHandler. I am trying to transfer the two ListModel sortedlist and modelist onto the ActionListener class, so I can actually code to sort the numbers and output them. How do I do this?

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

One quick and easy way to solve this (though not necessarily the best way) is to pass an instance of the GUI_Driver class into the Handler class via a constructor parameter, and then call public methods of GUI_Driver to get the state of its lists when the actionPerformed method is called. For this to work well, again the fields in the GUI_Driver class should be private instance (not static) fields.

A better solution though is to separate your logic from your GUI via something akin to the model-view-control design pattern, but this may be over-kill at this stage or your program.

For example, in the code below, I've created a SortHandler class that extends AbstractAction (kind of like a super-duper ActionListener), and pass into its constructor a reference to the GUI class itself. I've also given the GUI class public methods to extract the information that the handler needs, such as the getOriginalNumberModel() and getSelectedAlgorithm() methods, and then within the actionPerformed method, I have called this information to extract the needed information. Note that the ButtonGroup will return the ButtonModel for the selected JRadioButton. If you set the radiobutton's actionCommand, then this information can be useful as my code below shows:

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

   }
}

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