Handle JButton click event in another class

后端 未结 3 1752
[愿得一人]
[愿得一人] 2021-01-12 10:47

I\'m new to java coming from C# so I\'m not familiar with java best practices.

I have a main class that opens a JFrame to get several input strings from a user. When

3条回答
  •  广开言路
    2021-01-12 11:09

    Yes, that is the right idea. You must do two things in order to be able to do that, though:

    1. Put this at the beginning of the FInput class:

      Main m = new Main(this);
      
    2. Then, put these lines somewhere in the Main class...

      FInput gui;
      
      public Main(FInput in) { gui = in; }
      

    Now you can refer to any component in the FInput class from the Main class by doing something like this.

    gui.someComponent ...
    

    To set up listeners just write someComponent.addItemListener(m); or something of the sort.

    Hope this helps!


    @Yoav In response to your latest comment...

    You don't have to separate the listening class from the GUI class; you can combine the two into one class...

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class Main extends JFrame implements ActionListener {
    
        private JTextField txtSourceDirectory;
        private JTextField txtTargetDirectory;
        private JTextField txtDefectNumber;
        private JTextField txtSliceTokens;
        private JButton btnStart;
    
        public Main() {
            txtSourceDirectory = new JTextField(40); //change this to the amount of characters you need
            txtTargetDirectory = new JTextField(40);
            txtDefectNumber = new JTextField(40);
            txtSliceTokens = new JTextField(40);
            btnStart = new JButton("Start");
            add(txtSourceDirectory);
            add(txtTargetDirectory);
            add(txtDefectNumber);
            add(txtSliceTokens);
            add(btnStart);
            btnStart.addActionListener(this);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
    
        public void actionPerformed(ActionEvent event) {
            //do stuff
        }
    
        static void startProcess(String[] ARGS) {
            //do stuff
        }
    
        public static void main(String[] args) {
            if (args.length == 0) {
                Main frame = new Main();
            } else {
                startProcess(args);
            }
        }
    }
    

提交回复
热议问题