有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用一个文本字段创建一个弹出窗口?

我想在用户单击“从文件加载”按钮时创建一个弹出窗口。我希望弹出框有一个文本框和一个“确定”“取消”选项

我已经阅读了很多Java文档,我没有看到简单的解决方案,感觉好像我遗漏了什么,因为如果有一个JOptionPane允许我向用户显示文本框,为什么没有办法检索该文本

除非我想创建一个“在文本框中键入文本并单击ok”程序,但我现在就是这么做的


共 (1) 个答案

  1. # 1 楼答案

    您确实可以使用JOptionPane检索用户输入的文本:

    String path = JOptionPane.showInputDialog("Enter a path");
    

    Java教程中有一个关于JOptionPane的精彩页面: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html

    但如果您确实需要用户选择路径/文件,我认为您更希望显示JFileChooser:

    JFileChooser chooser = new JFileChooser();
    if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File selectedFile = chooser.getSelectedFile();
    }
    

    否则,您可以通过使用JDialog艰难地创建自己的对话框,其中包含您想要的所有内容

    编辑

    下面是一个帮助您创建主窗口的简短示例。 使用Swing,窗口是使用JFrame创建的

    // Creating the main window of our application
    final JFrame frame = new JFrame();
    
    // Release the window and quit the application when it has been closed
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    
    // Creating a button and setting its action
    final JButton clickMeButton = new JButton("Click Me!");
    clickMeButton.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent e) {
            // Ask for the user name and say hello
            String name = JOptionPane.showInputDialog("What is your name?");
            JOptionPane.showMessageDialog(frame, "Hello " + name + '!');
        }
    });
    
    // Add the button to the window and resize it to fit the button
    frame.getContentPane().add(clickMeButton);
    frame.pack();
    
    // Displaying the window
    frame.setVisible(true);
    

    我仍然建议您遵循JavaSwingGUI教程,因为它包含了入门所需的所有内容