首页 > 解决方案 > 无法自动选择 JOption 窗格 showInputDialog

问题描述

所以我JOptionPane在我的主要方法的一开始就有这样的:

JFrame frame = new JFrame("Input");
String progName = JOptionPane.showInputDialog(frame, "Name?");

但是,在我开始输入之前,我需要手动点击弹出窗口。有什么方法可以让我运行程序时,它会自动“选择”弹出窗口,这样当我开始输入时它就会出现在文本框中。如果这不能用 a 来完成JOptionPane,我可以使用其他替代方案,我只需要考虑到上述约束来获取用户输入的字符串。

标签: javaswingjoptionpane

解决方案


我创建了一个简单的示例,其中询问用户姓名的逻辑集中在一个方法中。此方法在应用程序的最开始以及每次单击按钮时调用。

这样,用户在应用程序启动时以及每次他/她希望更改输入的值时都被迫输入数据。

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();
    }

}

推荐阅读