-1

我创建了一个ActionListener和按钮,但按钮不起作用。

动作监听器应该与提交按钮集成,请帮忙?

代码:

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);
    btSubmit.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            String userEntered = txtEnter.getText();
            if(userEntered.equalsIgnoreCase("yes"))
            {
                //run your script
            }
        }
    });
}
}
4

1 回答 1

2

您的代码看起来不错。输入打印语句,您可以看到它正在工作。

btSubmit.addActionListener(new ActionListener() {

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

        String userEntered = txtEnter.getText();
        System.out.println("User enterd: " + userEntered);

        if(userEntered.equalsIgnoreCase("yes"))
        {
            System.out.println("Entered Yes");
        }
    }
});
于 2013-07-29T15:15:16.780 回答