我需要通过gui向用户显示一些相关信息(如介绍,是/否问题和其他问题),然后gui将他们的响应输入控制台。但是,我不能为我的生活想到或找到办法做到这一点。如何运行GUI但仍允许输入控制台?这里有一些减少的代码,显示了我正在尝试做的事情。我是从一个处理容器内容的pps框架类做的。我只需要添加按钮,文本字段以及稍后的动作事件。
public class gui extends XFrame
{
private JTextField[] textFieldsUneditable;
public gui()
{
super();
textFieldsUneditable = new JTextField[10];
for(int i=0; i<textFieldsUneditable.length; i++)
{
textFieldsUneditable[i] = new JTextField(42);
textFieldsUneditable[i].setEditable(false);
add(textFieldsUneditable[i]);
}
revalidate();
repaint();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// code code code
}
但我所拥有的是其他方法,我想运行它,然后在用户在控制台中响应后使用GUI中的setText输出到这些不可编辑的JTextFields。我希望这是有道理的!
答案 0 :(得分:1)
我会做这样的事情(下面的例子):
Scanner
。SwingUtilities.invokeAndWait
或invokeLater
public static void main(String[] args) throws Exception {
// create a new frame
JFrame frame = new JFrame("Test");
frame.setLayout(new GridLayout(0, 1));
// create some fields that you can update from the console
JTextField[] fields = new JTextField[10];
for (int i = 0; i < fields.length; i++)
frame.add(fields[i] = new JTextField("" + i)); // add them to the frame
// show the frame (it will pop up and you can interact with in - spawns a thread)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
// Create a scanner so that you can get some input from the console (the easy way)
Scanner s = new Scanner(System.in);
for (int i = 0; i < fields.length; i++) {
// get the field you want to update
final JTextField field = fields[i];
// get the input from the console
final String line = s.nextLine();
// update the field (must be done thread-safe, therefore this construct)
SwingUtilities.invokeAndWait(new Runnable() {
@Override public void run() { field.setText(line); }
});
}
}