简体   繁体   中英

How to call on a textfield variable from a keyevent method?

Okay, so I am doing a GUI program and I have trouble retrieving the information that the user will input and call on it from another class so it can be accessed there. Here is the main part of my GUI class, and it starts from the creating of the first textfield:

/**
*Text genereted by Simple GUI Extension for BlueJ
*/
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.border.Border;
import javax.swing.*;


public class GUI_project extends JFrame {

private JMenuBar menuBar;
private JButton button1;
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JLabel label4;
private JTextField textfield1;
private JTextField textfield2;
private JTextField textfield3;
public String SoftName;
public String ReportName;
public String Devices;
public int InDevices;

//Constructor 
public GUI_project(){

    setTitle("Software Calculator");
    setSize(500,400);
    //menu generate method
    generateMenu();
    setJMenuBar(menuBar);

    //pane with null layout
    JPanel contentPane = new JPanel(null);
    contentPane.setPreferredSize(new Dimension(500,400));
    contentPane.setBackground(new Color(51,153,0));


    button1 = new JButton();
    button1.setBounds(180,325,150,35);
    button1.setBackground(new Color(214,217,223));
    button1.setForeground(new Color(0,0,0));
    button1.setEnabled(true);
    button1.setFont(new Font("sansserif",0,12));
    button1.setText("Calculate and Save");
    button1.setVisible(true);
    //Set action for key events
    //Call defined method
    button1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            startApp(evt);
        }
    });


    label1 = new JLabel();
    label1.setBounds(95,12,300,35);
    label1.setBackground(new Color(214,217,223));
    label1.setForeground(new Color(0,0,0));
    label1.setEnabled(true);
    label1.setFont(new Font("SansSerif",0,20));
    label1.setText("Software Agreement Calcuator");
    label1.setVisible(true);

    label2 = new JLabel();
    label2.setBounds(18,102,150,35);
    label2.setBackground(new Color(214,217,223));
    label2.setForeground(new Color(0,0,0));
    label2.setEnabled(true);
    label2.setFont(new Font("SansSerif",0,16));
    label2.setText("Name of Software:");
    label2.setVisible(true);

    label3 = new JLabel();
    label3.setBounds(15,174,300,35);
    label3.setBackground(new Color(214,217,223));
    label3.setForeground(new Color(0,0,0));
    label3.setEnabled(true);
    label3.setFont(new Font("SansSerif",0,16));
    label3.setText("Number of Devices the Software is on:");
    label3.setVisible(true);

    label4 = new JLabel();
    label4.setBounds(17,244,250,35);
    label4.setBackground(new Color(214,217,223));
    label4.setForeground(new Color(0,0,0));
    label4.setEnabled(true);
    label4.setFont(new Font("SansSerif",0,15));
    label4.setText("Name of Report to Save Under:");
    label4.setVisible(true);

    textfield1 = new JTextField();
    textfield1.setBounds(335,102,90,35);
    textfield1.setBackground(new Color(255,255,255));
    textfield1.setForeground(new Color(0,0,0));
    textfield1.setEnabled(true);
    textfield1.setFont(new Font("sansserif",0,12));
    textfield1.setText("");
    textfield1.setVisible(true);
    //Set action for key events
    //Call defined method
    textfield1.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent evt) {
            getSoftwareName(evt);
        }
    });


    textfield2 = new JTextField();
    textfield2.setBounds(335,173,90,35);
    textfield2.setBackground(new Color(255,255,255));
    textfield2.setForeground(new Color(0,0,0));
    textfield2.setEnabled(true);
    textfield2.setFont(new Font("sansserif",0,12));
    textfield2.setText("");
    textfield2.setVisible(true);
    //Set action for key events
    //Call defined method
    textfield2.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent evt) {
            number(evt);
        }
    });


    textfield3 = new JTextField();
    textfield3.setBounds(336,240,90,35);
    textfield3.setBackground(new Color(255,255,255));
    textfield3.setForeground(new Color(0,0,0));
    textfield3.setEnabled(true);
    textfield3.setFont(new Font("sansserif",0,12));
    textfield3.setText("");
    textfield3.setVisible(true);
    //Set action for key events
    //Call defined method
    textfield3.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent evt) {
            FileName(evt);
        }
    });


    //adding components to contentPane panel
    contentPane.add(button1);
    contentPane.add(label1);
    contentPane.add(label2);
    contentPane.add(label3);
    contentPane.add(label4);
    contentPane.add(textfield1);
    contentPane.add(textfield2);
    contentPane.add(textfield3);

    //adding panel to JFrame and seting of window position and close operation
    getContentPane().add(contentPane);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    pack();
    setVisible(true);
}

//Method keyPressed for button1
public void startApp (ActionEvent evt) {
        Print.Start();
}

//Method actionPerformed for textfield1
public String getSoftwareName (KeyEvent evt) {
        SoftName = textfield1.getText();
        return SoftName;
}

//Method actionPerformed for textfield2

  public int number (KeyEvent evt) {
        char c=evt.getKeyChar();
        if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||c==KeyEvent.VK_DELETE)){
            evt.consume();
  }
        this.Devices= this.textfield2.getText();
        InDevices= Integer.parseInt(Devices);
        return InDevices;
 }
  //Method actionPerformed for textfield3
public String FileName (KeyEvent evt) {
        this.ReportName= this.textfield3.getText();
        return ReportName;
}

//method for generate menu
public void generateMenu(){
    menuBar = new JMenuBar();

    JMenu file = new JMenu("File");

    JMenuItem open = new JMenuItem("Open   ");
    open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,Event.CTRL_MASK));

    JMenuItem exit = new JMenuItem("Exit   ");
    exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,Event.CTRL_MASK));


    //Setings action for menu item
    //Call defined method
    open.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            openFile(evt);
        }
    });

    //Setings action for menu item
    //Call defined method
    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            Quit(evt);
        }
    });


    file.add(open);
    file.add(exit);

    menuBar.add(file);
}
//Method for Open from menuFile 
private void openFile (ActionEvent evt) {
        PopUp Pop= new PopUp();
        Pop.Frame();
}

//Method for Exit from menuFile 
private void Quit (ActionEvent evt) {
        System.exit(0);
}




 public static void main(String[] args){
    System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new GUI_project();
        }
    });
}

}

And here's the second class:

public static int software;
public static String name;
public static void Company(){
GUI_project main= new GUI_project();
name=main.getSoftwareName();
if(name.equals("Microsoft")||name.equals("Norton")||name.equals("Oracle")||name.equals("CRM")){
    if(name.equals("Microsoft")){
        Name.software = 1200000;
    }else if(name.equals("Norton")){
        Name.software = 3000000;
    }else if(name.equals("Oracle")){
        Name.software = 1700000;
    }else if(name.equals("CRM")){
        Name.software = 2300000;
    }
  }else{
    System.out.println("Not a company, GOOD BYE!");
    System.exit(0);
}
}

I'm sure that its a silly and stupid mistake, but any help would be great. Once I am able to have these two classes work, the rest should work the same way :)

Try something like the following code.

Test.java

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

public class Test
{
    JFrame myMainWindow = new JFrame("This is my title");
    JPanel  firstPanel = new JPanel(null);
    JTextField textfield1 = new JTextField();

    public void runGUI() {
        myMainWindow.setBounds(10, 10, 500, 500);
        myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myMainWindow.setLayout(new GridLayout(1,1));
        createFirstPanel();
        myMainWindow.getContentPane().add(firstPanel);
        myMainWindow.setVisible(true);
    }

    public void createFirstPanel() {
        textfield1.setBounds(335,102,90,35);
        textfield1.setBackground(new Color(255,255,255));
        textfield1.setForeground(new Color(0,0,0));
        textfield1.setEnabled(true);
        textfield1.setFont(new Font("sansserif",0,12));
        textfield1.setVisible(true);
        textfield1.getDocument().addDocumentListener(new MyDocumentListener());
        firstPanel.add(textfield1);
    }

    private class MyDocumentListener implements DocumentListener {
        public void insertUpdate(DocumentEvent e) {
            new Class2(textfield1.getText());
        }

        public void removeUpdate(DocumentEvent e) {
            new Class2(textfield1.getText());
        }

        public void changedUpdate(DocumentEvent e) {}
    }

    public static void main(String[] args)
    {
        Test t = new Test();
        t.runGUI();
    }
}

Class2.java

public class Class2 {
    int software;

    public Class2(String s) {
        Company(s);
        System.out.println(s);
        System.out.println(software);
    }

    public void Company(String s) {
        if(s.equals("Microsoft")||s.equals("Norton")||s.equals("Oracle")||s.equals("CRM")){
            if(s.equals("Microsoft")) {
                software = 1200000;
                System.out.println("Matches Microsoft");
            } else if(s.equals("Norton")) {
                software = 3000000;
                System.out.println("Matches Norton");
            } else if(s.equals("Oracle")) {
                software = 1700000;
                System.out.println("Matches Oracle");
            } else if(s.equals("CRM")) {
                software = 2300000;
                System.out.println("Matches CRM");
            }
        } else {
            System.out.println("Not a company, GOOD BYE!");
        }
    }
}

I changed the KeyAdapter to a Document Listener because the event fires at a better time, which is after the document has changed. Whereas in your version the KeyAdapter was firing events before a letter had been placed in textfield1 .

Edit

If you want it to check at the end. Remove the Document Listener and just have the following code in Test.java

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

public class Test
{
    JFrame myMainWindow = new JFrame("This is my title");
    JPanel  firstPanel = new JPanel(null);
    JTextField textfield1 = new JTextField();
    JButton button1 = new JButton("Check Company");

    public void runGUI() {
        myMainWindow.setBounds(10, 10, 500, 500);
        myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myMainWindow.setLayout(new GridLayout(1,1));
        createFirstPanel();
        myMainWindow.getContentPane().add(firstPanel);
        myMainWindow.setVisible(true);
    }

    public void createFirstPanel() {
        textfield1.setBounds(335,102,90,35);
        textfield1.setBackground(new Color(255,255,255));
        textfield1.setForeground(new Color(0,0,0));
        textfield1.setEnabled(true);
        textfield1.setFont(new Font("sansserif",0,12));
        textfield1.setVisible(true);
        firstPanel.add(textfield1);

        button1.setBounds(335,150,150,35);
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                new Class2(textfield1.getText());
            }
        });
        firstPanel.add(button1);
    }

    public static void main(String[] args)
    {
        Test t = new Test();
        t.runGUI();
    }
}

Okay, so based on this...

GUI_project main= new GUI_project();
name=main.getSoftwareName();

you seem to be wanting to get the softwareName after the user has interacted with your form.

In this, you have three choices, you can use some kind of Observer Pattern by which the GUI_project will send any interested party some kind of event when some kind of action occurs (like, the user presses the "Ok" button)

Or you can use a modal dialog which will halt the execution of the code at the point the dialog is made visible until it is closed, at which time you can gain access to the information you need.

Or you should pass the information that the second class needs to it directly

The second approach is the more common approach and the more "linear" approach, which would seem to fit your code.

But, before we get to excited, some house keeping...

  • Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
  • Avoid KeyListener as general rule, but especially with text components, they are woefully inappropriate, in fact, in your case, an ActionListener would be so much better. See How to Use Text Fields and How to Write an Action Listeners for more details
  • If you need to provide special processing while text is been entered into a field, you should use a DocumentListener , see Listening for Changes on a Document for more details. If you want to provide real time validation on the field, then you should use a `DocumentFilter, see Implementing a Document Filter and DocumentFilter Examples for more details

As a conceptual idea...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                GUI_project project = new GUI_project();

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setJMenuBar(project.generateMenu());
                frame.add(project);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class GUI_project extends JPanel {

        private JButton button1;
        private JLabel label1;
        private JLabel label2;
        private JLabel label3;
        private JLabel label4;
        private JTextField textfield1;
        private JTextField textfield2;
        private JTextField textfield3;
        public String SoftName;
        public String ReportName;
        public String Devices;
        public int InDevices;

        public GUI_project() {

            generateMenu();

            //pane with null layout
            setBackground(new Color(51, 153, 0));

            button1 = new JButton();
            button1.setBackground(new Color(214, 217, 223));
            button1.setForeground(new Color(0, 0, 0));
            button1.setEnabled(true);
            button1.setFont(new Font("sansserif", 0, 12));
            button1.setText("Calculate and Save");
            button1.setVisible(true);
            //Set action for key events
            //Call defined method
            button1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    startApp(evt);
                }
            });

            label1 = new JLabel();
            label1.setBackground(new Color(214, 217, 223));
            label1.setForeground(new Color(0, 0, 0));
            label1.setEnabled(true);
            label1.setFont(new Font("SansSerif", 0, 20));
            label1.setText("Software Agreement Calcuator");
            label1.setVisible(true);

            label2 = new JLabel();
            label2.setBackground(new Color(214, 217, 223));
            label2.setForeground(new Color(0, 0, 0));
            label2.setEnabled(true);
            label2.setFont(new Font("SansSerif", 0, 16));
            label2.setText("Name of Software:");
            label2.setVisible(true);

            label3 = new JLabel();
            label3.setBackground(new Color(214, 217, 223));
            label3.setForeground(new Color(0, 0, 0));
            label3.setEnabled(true);
            label3.setFont(new Font("SansSerif", 0, 16));
            label3.setText("Number of Devices the Software is on:");
            label3.setVisible(true);

            label4 = new JLabel();
            label4.setBackground(new Color(214, 217, 223));
            label4.setForeground(new Color(0, 0, 0));
            label4.setEnabled(true);
            label4.setFont(new Font("SansSerif", 0, 15));
            label4.setText("Name of Report to Save Under:");
            label4.setVisible(true);

            textfield1 = new JTextField(10);
            textfield1.setBackground(new Color(255, 255, 255));
            textfield1.setForeground(new Color(0, 0, 0));
            textfield1.setEnabled(true);
            textfield1.setFont(new Font("sansserif", 0, 12));
            textfield1.setText("");
            textfield1.setVisible(true);

            textfield2 = new JTextField(10);
            textfield2.setBackground(new Color(255, 255, 255));
            textfield2.setForeground(new Color(0, 0, 0));
            textfield2.setEnabled(true);
            textfield2.setFont(new Font("sansserif", 0, 12));
            textfield2.setText("");
            textfield2.setVisible(true);
            //Set action for key events
            //Call defined method

            textfield3 = new JTextField(10);
            textfield3.setBackground(new Color(255, 255, 255));
            textfield3.setForeground(new Color(0, 0, 0));
            textfield3.setEnabled(true);
            textfield3.setFont(new Font("sansserif", 0, 12));
            textfield3.setText("");
            textfield3.setVisible(true);
            //Set action for key events
            //Call defined method

            //adding components to contentPane panel
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.gridx = 0;
            gbc.gridy = 0;
            add(label1, gbc);
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridy++;
            gbc.gridwidth = 1;
            add(label2, gbc);
            gbc.gridy++;
            add(label3, gbc);
            gbc.gridy++;
            add(label4, gbc);

            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridy = 1;
            gbc.gridx++;
            add(textfield1, gbc);
            gbc.gridy++;
            add(textfield2, gbc);
            gbc.gridy++;
            add(textfield3, gbc);
            gbc.gridy++;

            gbc.gridx = 0;
            gbc.anchor = gbc.EAST;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            add(button1, gbc);

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(500, 400);
        }

        public JMenuBar generateMenu() {
            JMenuBar menuBar = new JMenuBar();

            JMenu file = new JMenu("File");

            JMenuItem open = new JMenuItem("Open   ");
            open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK));

            JMenuItem exit = new JMenuItem("Exit   ");
            exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK));

            //Setings action for menu item
            //Call defined method
            open.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    openFile(evt);
                }
            });

            //Setings action for menu item
            //Call defined method
            exit.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    Quit(evt);
                }
            });

            file.add(open);
            file.add(exit);

            menuBar.add(file);

            return menuBar;
        }

        public void startApp(ActionEvent evt) {
            Popup pop = new Popup(textfield1.getText());
            // And what ever you need to do
        }

        private void openFile(ActionEvent evt) {
        }

        private void Quit(ActionEvent evt) {
            SwingUtilities.windowForComponent(this).dispose();
        }
    }

    public class Popup {

        private int type;

        public Popup(String softwareName) {
            if (softwareName.equals("Microsoft") || softwareName.equals("Norton") || softwareName.equals("Oracle") || softwareName.equals("CRM")) {
                if (softwareName.equals("Microsoft")) {
                    type = 1200000;
                } else if (softwareName.equals("Norton")) {
                    type = 3000000;
                } else if (softwareName.equals("Oracle")) {
                    type = 1700000;
                } else if (softwareName.equals("CRM")) {
                    type = 2300000;
                }
            }
        }

    }
}

You can use the list interface to improve the code of your second class

List <String> companyList = new ArrayList<String>();

companyList.add("Microsoft");
companyList.add("Norton");
companyList.add("Oracle");
companyList.add("CRM");

int index=companyList.indexOf(name);

switch(index){
    case 0: Name.software = 1200000;break;
    case 1: Name.software = 3000000;break;
    case 2: Name.software = 1700000;break;
    case 3: Name.software = 2300000;break;
    case -1: //-1 Signifies it did not match the company names
}

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