在SubmitListener中使用If-Else语句

时间:2013-07-29 14:49:32

标签: java swing user-interface

尝试开发GUI,但我遇到了障碍:

我正在使用提交按钮,它将查看txtEnter字段。如果用户输入"是"在txtEnter字段中单击“提交”,它将执行shell脚本。如果用户键入" no"没有行动。我知道运行shell脚本的命令是Runtime.getRuntime().exec(myShellScript);

如何在SubmitListner中使用if-else语句来检查用户的输入?

import javax.swing.*; import javax.swing.event.DocumentListener;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Executer private JLabel lblCommand;
private JTextField txtEnter;
private JButton btNext, btPrevious, btSubmit;
private JPanel panel;

public static void main(String[] args) {
    new Executer();
}
public  Executer() {
    JFrame frame = new JFrame("Script Executer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,300);
    frame.setVisible(true);
    myPanel();
    Text();
    Fields();
    Buttons();
    frame.add(panel); 
    frame.setVisible(true);
}
public void myPanel() {
    panel = new JPanel();
    panel.setLayout(null);
}

public void Text(){
    lblCommand = new JLabel("Enter Here");
    lblCommand.setBounds(145, 100, 150, 20);
    Font styleOne = new Font("Arial", Font.BOLD, 13);
    lblCommand.setFont(styleOne);
    panel.add(lblCommand);
}

public void Fields () {
    txtEnter = new JTextField();
    txtEnter.setBounds(230, 100, 120, 20);
    panel.add(txtEnter);
}
public void Buttons() {
    btNext = new JButton ("Next");
    btNext.setBounds(300,215,100,20);
    panel.add(btNext);

    btPrevious = new JButton ("Previous");
    btPrevious.setBounds(190,215,100,20);
    panel.add(btPrevious);

    btSubmit = new JButton("Submit");
    btSubmit.setBounds(80,215,100,20);
    panel.add(btSubmit);
}

class SubmitListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {


        }}}

1 个答案:

答案 0 :(得分:2)

您必须将Actionlistener指定给按钮:

btSubmit = new JButton();

    btSubmit.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // here the click happend so you can check your Textfield

            String userEntered = txtEnter.getText();

            if(userEntered.equalsIgnoreCase("yes"))
            {
                //run your script
            }
        }
    });