Ok I'm just looking for a cleaner way to achieve my goal here, if there is one and if this is not much of a satisfactory method. The goal is to accept an integer from a user using JOptionPane.showInputDialog.

A brief example of what I'm currently doing

            check = true;
            num = Integer.parseInt(JOptionPane.showInputDialog("How many items do you need to list?"));
        catch(NumberFormatException nfe)
            check = false;

Just curious for better methods, faster, cleaner etc. Thanks in advance

Recommended Answers

All 6 Replies

mKorbel: Hi. What's the easiest way you know to use a JFormattedTextField for the input in a JOptionPane InputDialog?

@JamesCherrill great minds thinks alike ---> I see that good point, there is only String for showInputDialog

OK. I hoped you found a new idea there. :(

So the best answer we have is "you can't change the text field in a JOptionPane.showInputDialog, so you will have to create a custom dialog and use a JFornattedTextField". For examples just Google "custom JDialog"

Yep, thank you guys for the help. I am in a beginners data structures class that is requiring we use JOptionPane. I've been coding Java for a couple years, so I was just trying to see if I could improve upon anything that seemed like it could be cut down.


  • this is valid for JOptionPane.showInputDialog, rest ise customizable

  • you can to add any JComponent to JOptionPane.showInputDialog but return value is from built_in JTextField

  • is possible to derive, to the pieces, but then is better to use custom showMessageDialog

  • but see one of ways, without hacks :-),


import java.awt.EventQueue;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class MyOptionPane {

    public MyOptionPane() {
        Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
        Object[] possibilities = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
        Integer i = (Integer) JOptionPane.showInputDialog(null,
                "Select number:\n\from JComboBox", "ShowInputDialog",
                JOptionPane.PLAIN_MESSAGE, errorIcon, possibilities, "Numbers");
        if ((i != null) && (i > 0)) {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                MyOptionPane mOP = new MyOptionPane();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.