如何从keyevent方法调用textfield变量?

时间:2016-01-09 10:34:58

标签: java swing user-interface methods key-events

好的,所以我正在做一个GUI程序,我无法检索用户将输入的信息,并从另一个类调用它,以便可以在那里访问它。这是我的GUI类的主要部分,它从创建第一个文本字段开始:

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

}

这是第二堂课:

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

我确信这是一个愚蠢而愚蠢的错误,但任何帮助都会很棒。一旦我能够使这两个类工作,其余的应该以相同的方式工作:)

3 个答案:

答案 0 :(得分:1)

尝试类似以下代码的内容。

<强> Test.java

  for (int col = row; col < array[row].length;col++) {

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

我将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!"); } } } 更改为KeyAdapter,因为事件会在文档更改后的更好时间触发。在您的版本中,Document Listener在将信件放入KeyAdapter之前触发了事件。

修改

如果你想在最后检查它。移除textfield1,只需在Document Listener

中包含以下代码即可

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

Test.java

答案 1 :(得分:1)

好的,基于此......

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

您似乎希望在用户与您的表单进行互动后获得softwareName

在此,你有三个选择,你可以使用某种Observer Pattern GUI_project,当某种行为发生时,null会向任何感兴趣的一方发送某种事件(例如,用户)按“确定”按钮)

或者你可以使用modal dialog,它会在对话框可见之前暂停代码的执行,直到它关闭为止,此时你可以访问所需的信息。

或者您应该直接传递第二课所需的信息

第二种方法是更常见的方法和更“线性”的方法,这似乎适合您的代码。

但是,在我们兴奋之前,一些家务活动......

  • 避免使用KeyListener布局,像素完美布局是现代ui设计中的错觉。影响组件个体大小的因素太多,您无法控制。 Swing旨在与布局管理器一起工作,放弃这些将导致问题和问题的结束,您将花费越来越多的时间来纠正
  • 避免ActionListener作为一般规则,但特别是对于文本组件,它们非常不合适,事实上,在您的情况下,DocumentListener会更好。有关详细信息,请参阅How to Use Text FieldsHow to Write an Action Listeners
  • 如果您需要在文字输入字段时提供特殊处理,则应使用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; } } } } } ,有关详细信息,请参阅Listening for Changes on a Document。如果您想在该字段上提供实时验证,那么您应该使用`DocumentFilter,有关详细信息,请参阅Implementing a Document FilterDocumentFilter Examples

作为一个概念性的想法......

el.addClass('ec-circle-hover2');

答案 2 :(得分:0)

您可以使用列表界面来改进第二类的代码

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
}