java - 无法自动选择 JOption 窗格 showInputDialog
问题描述
所以我JOptionPane
在我的主要方法的一开始就有这样的:
JFrame frame = new JFrame("Input");
String progName = JOptionPane.showInputDialog(frame, "Name?");
但是,在我开始输入之前,我需要手动点击弹出窗口。有什么方法可以让我运行程序时,它会自动“选择”弹出窗口,这样当我开始输入时它就会出现在文本框中。如果这不能用 a 来完成JOptionPane
,我可以使用其他替代方案,我只需要考虑到上述约束来获取用户输入的字符串。
解决方案
我创建了一个简单的示例,其中询问用户姓名的逻辑集中在一个方法中。此方法在应用程序的最开始以及每次单击按钮时调用。
这样,用户在应用程序启动时以及每次他/她希望更改输入的值时都被迫输入数据。
public class Jf53136132 extends JFrame {
private static final long serialVersionUID = -3336501835025139522L;
private JPanel contentPane;
public Jf53136132() {
setTitle("Jf53136132");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
JButton btnInvokeJoptionpane = new JButton("set some text on label");
panel.add(btnInvokeJoptionpane);
JLabel lblx = new JLabel("-x-");
panel.add(lblx);
getNewTextForLabel(lblx);
btnInvokeJoptionpane.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
getNewTextForLabel(lblx);
}
});
}
private void getNewTextForLabel(JLabel label) {
String inputText = JOptionPane.showInputDialog("Enter the text for the label");
System.out.println("you entered <" + inputText + ">");
if (inputText != null && !inputText.trim().isEmpty()) {
label.setText(inputText);
}
}
}
请注意方法 getNewTextForLabel(...) 在标签添加到内容窗格后以及每次单击按钮时如何被调用。
此外,正如 VGR 正确指出的那样,最好不要在主应用程序线程内运行任何 Swing 代码。您可以查看 swing 的 java 教程(这是一个经典示例)。
以下是在单独线程上运行框架的一些示例代码。
public class Main {
private static void createAndShowGUI() {
Jf53136132 f = new Jf53136132();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(640, 480));
f.setLocationRelativeTo(null);
f.setVisible(true);
}
void execute() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void main(String[] args) {
new Main().execute();
}
}
推荐阅读
- python - Flask CGI htaccess 404 未找到
- git - 我可以为我网站的一个部分使用单独的分支吗?
- templates - Handlebars:使用键中的空格访问嵌套对象
- r - 同一列的不同字符类型转换为日期格式
- r - 通过考虑 r (2) 中的分组 Q 矩阵来操作字符向量
- amazon-web-services - 在没有线程的情况下,将大文件从 S3 下载到 Lambda 更快
- javascript - 如何使用反引号在 node.js 中编写多行 MySQL 查询?
- java - apache commons FTPSClient.listFiles() 触发 java.net.ConnectException:连接被拒绝:连接
- python - 如何使用 groupby 和 lamda 表达式为 .loc 指定日期范围?
- python - 将结果作为单独的实体而不是列表返回