Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a popup window with just a textfield?

I want to create a popup window when the user clicks a "Load from file" button. I want that popup box to have a text box and an "OK" "Cancel" option.

I have read through a lot of Java Documentation and I see no simple solution, it feels like I am missing something because if there is a JOptionPane that allows me to display a textbox to the user why would there be no way to retrieve that text?

Unless I wanted to create a "type text into text boxes and click ok" program, but that's now what I am doing.

like image 604
OKGimmeMoney Avatar asked Jun 18 '13 22:06

OKGimmeMoney


1 Answers

You can indeed retrieve the text entered by the user with a JOptionPane:

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

There is a great page about JOptionPane in the Java Tutorials: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html

But if you really need the user to select a path/a file, I think you rather want to display a JFileChooser:

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

Otherwise you can go the hard way and create your own dialog with everything you want inside by using a JDialog.

Edit

Here is a short example to help you create your main window. With Swing, windows are created using 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);

I still recommend you to follow the Java Swing GUI tutorial since it contains everything you need to get started.

like image 183
Raphaël Avatar answered Oct 21 '22 03:10

Raphaël