ユーザー入力 (0/1 文字のシーケンスの後に "Done" が続く) を取得するための小さなスイング プログラムを作成し、文字列をメイン クラスに返します - 以下にコードを添付します。問題は、通常モードで実行するとハングすることですが、「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();
}
}