许多人可能知道,当你调用输入法时有一个while循环(或任何循环),程序会停止并等待输入。
e.g。
while {
String input = in.readLine();
int x = 55; //This will not execute until input has been given a value
System.out.println (x + x);
}
现在我使用按钮进行输入。有没有办法可以使用JButton,JPanel,JFrame等做同样的事情(在循环中停止程序)?
注意:如果需要,我也可以使用Runnable()接口。
更新: 我正在使用按钮的按钮。这是确切的问题。
public void actionPerformed (ActionEvent x){ string = x.getActionCommand}
public void someOtherMethod ()
{
while (true){
start ();
if (string.equals ("exit") break; // This line will never execute because start()
//is always repeating itself.
}
}
修改 我找到了一个解决方案(最终!)
这就是所有需要做的事情......
string = "";
while (true){
if (string.equals ("");
start ();
if (string.equals ("exit") break; // I guess I didn't explain the problem too well...
}
感谢大家的帮助!
答案 0 :(得分:2)
我认为您遇到的问题是如何根据输入到GUI中的内容更改按钮的功能。请记住,使用GUI,用户可以随时以任何顺序与任何已启用的GUI组件进行交互。关键是检查按钮的ActionListener中的GUI状态,然后根据此GUI的状态更改此方法的行为。例如,如果您的GUI有三个JTextFields,field1,field2和sumField以及一个JButton addButton:
private JTextField field1 = new JTextField(5);
private JTextField field2 = new JTextField(5);
private JTextField sumField = new JTextField(5);
private JButton addButton = new JButton("Add");
你想让addButton将field1和field2中的数字加在一起并将结果放入sumField中,如果任何一个字段留空,你显然不想做任何添加,所以你要测试它在JButton的ActionListener中:
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text1 = field1.getText().trim();
String text2 = field2.getText().trim();
if (text1.isEmpty() || text2.isEmpty()) {
// data not entered... so return the method and do nothing
return;
}
// if we've reached this point, the user has entered in text and so we handle it
以下是整个事情:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class WaitForInput extends JPanel {
private JTextField field1 = new JTextField(5);
private JTextField field2 = new JTextField(5);
private JTextField sumField = new JTextField(5);
private JButton addButton = new JButton("Add");
public WaitForInput() {
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text1 = field1.getText().trim();
String text2 = field2.getText().trim();
if (text1.isEmpty() || text2.isEmpty()) {
// data not entered... so return the method and do nothing
return;
}
try {
int number1 = Integer.parseInt(field1.getText());
int number2 = Integer.parseInt(field2.getText());
int sum = number1 + number2;
sumField.setText("" + sum);
} catch (NumberFormatException e1) {
// TODO: use JOptionPane to send error message
// clear the fields
field1.setText("");
field2.setText("");
}
}
});
add(field1);
add(new JLabel("+"));
add(field2);
add(new JLabel("="));
add(sumField);
add(addButton);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("WaitForInput");
frame.getContentPane().add(new WaitForInput());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
编辑1
否则,如果您必须使用循环,那么是,在Runnable中执行此操作并在后台线程中执行此操作。记得在循环内调用Thread.sleep(...),即使是一小段,所以它不会占用CPU。例如
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class HaltingProblem extends JPanel {
private static final int PANEL_HEIGHT = 400;
private static final int PANEL_WIDTH = 600;
private static final long SLEEP_DELAY = 100;
private Color[] colors = {Color.red, Color.orange, Color.yellow,
Color.green, Color.blue, Color.cyan};
private boolean halt = false;
private JButton haltButton = new JButton("Halt");
private int colorIndex = 0;
public HaltingProblem() {
setBackground(colors[colorIndex]);
haltButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
halt = !halt; // toggle it!
}
});
add(haltButton);
new Thread(new Runnable() {
public void run() {
while (true) {
keepDoingThis();
}
}
}).start();
}
private void keepDoingThis() {
try {
Thread.sleep(SLEEP_DELAY);
} catch (InterruptedException e) {}
if (halt) {
return;
}
colorIndex++;
colorIndex %= colors.length;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setBackground(colors[colorIndex]);
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(PANEL_WIDTH, PANEL_HEIGHT);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("HaltingProblem");
frame.getContentPane().add(new HaltingProblem());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
答案 1 :(得分:1)
当您使用GUI时,编程范例会有所不同。
通过在按钮上注册监听器,当出现问题时会收到通知 - 如果没有任何反应,则Swing事件循环(EDT)已经“无所事事”。
也许我误解了这个问题。
答案 2 :(得分:1)
如果你有一个GUI,你通常没有一个无限期执行的中央主循环。响应事件的规范方法是使用event listeners:
mybutton.addListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { System.out.println("Clicked"); }
});
答案 3 :(得分:1)
制作JFrame
工具ActionListener
并致电button.addActionListener(this)
。然后,当单击按钮时,actionPerformed(ActionEvent event)
方法内的代码将执行:)
或者您可以使用
匿名ActionListener
button.addActionListener(new ActionListener() {
void actionPerformed(ActionEvent event) {
// Insert code to execute when button is clicked
}
}