我编写了一个小摇摆程序来获取用户输入(一系列 0/1 字符,后跟“完成”)将字符串返回给主类 - 代码附在下面。问题是它在正常模式下运行时挂起,但在“return new String(str)”行(在函数 getData() 中)放置断点时工作正常,之后单步运行。我认为这是一个时间问题,并在 while 循环之前放入了一个“Thread.sleep(400)”(参见注释行) - 现在它工作正常。
但是这段代码看起来很愚蠢。有没有更好的方法来编写这段代码——接受用户输入并将用户给定的字符串返回给调用类?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class DataEntryPanel extends JPanel implements ActionListener {
private JButton Button0, Button1, ButtonDone;
private JLabel DataEntered;
public char[] str = "________".toCharArray();
int posn = 0;
public boolean dataDone = false;
public DataEntryPanel() {
this.setLayout(new FlowLayout(FlowLayout.CENTER));
Button0 = new JButton("0"); Button0.addActionListener(this); this.add(Button0);
Button1 = new JButton("1"); Button1.addActionListener(this); this.add(Button1);
ButtonDone = new JButton("Done"); ButtonDone.addActionListener(this); this.add(ButtonDone);
DataEntered = new JLabel("xxxxxxxx"); this.add(DataEntered);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source==Button0) DataEntered.setText(setData('0'));
else if(source==Button1) DataEntered.setText(setData('1'));
else if(source==ButtonDone) dataDone=true;
}
public String setData(char c) {
if(posn<8) str[posn++] = c;
return new String(str);
}
}
class DataEntryFrame extends JFrame {
public JPanel panel;
private void centerWindow (Window w) {
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
}
public DataEntryFrame() {
setTitle("Data Entry");
setSize(267, 200);
centerWindow(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new DataEntryPanel();
this.add(panel);
}
public String getData() {
DataEntryPanel p = (DataEntryPanel) panel;
System.out.printf("waiting for data......\n");
// try {
while(!p.dataDone)
// Thread.sleep(400)
; // looping on data completion
// } catch (InterruptedException e) { e.printStackTrace(); }
return new String(p.str);
}
}
public class FRead {
public FRead() {
JFrame frame = new DataEntryFrame();
frame.setVisible(true);
DataEntryFrame f = (DataEntryFrame) frame;
String s = f.getData();
System.out.printf("string obtained=%s\n", s);
System.exit(0);
}
public static void main(String[] args) throws Exception {
new FRead();
}
}