gpt4 book ai didi

java - 在 SubmitListener 中使用 If-Else 语句

转载 作者:行者123 更新时间:2023-12-02 06:51:58 24 4
gpt4 key购买 nike

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

我正在使用提交按钮,它将查看 txtEnter 字段。如果用户在 txtEnter 字段中输入“yes”并单击“提交”,则会执行 shell 脚本。如果用户输入“否”,则不会执行任何操作。我知道运行 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) {


}}}

最佳答案

您必须将 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
}
}
});

关于java - 在 SubmitListener 中使用 If-Else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17927138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com