Search code examples
javauser-interfaceactionlistenerjoptionpane

user input for JLabel


I have a problem with a piece of code. When I click on it in my GUI, it reopens once I've inputted text. Can anyone explain to me what is wrong with the code. I'm using this to set a name in a JLabel in my GUI

setNameButton.addActionListener((ActionEvent e) -> {

    String usernameinput;
    String defaultUsername = "dom" + "baker";

    usernameinput = JOptionPane.showInputDialog(
        setNameButton, "Enter a username", 
        "Set username", JOptionPane.OK_CANCEL_OPTION);
    {
        username.setText(String.valueOf(usernameinput));    
    }
});

Solution

  • I've created a simple GUI to test your code and the dialog opens just once. I have cleaned up a bit your listener, but basically it's the same code. Your problem may be in another part of your code.

      import java.awt.Component;
      import java.awt.Dimension;
      import java.awt.event.ActionEvent;
    
      import javax.swing.Box;
      import javax.swing.BoxLayout;
      import javax.swing.JButton;
      import javax.swing.JFrame;
      import javax.swing.JLabel;
      import javax.swing.JOptionPane;
      import javax.swing.JPanel;
      import javax.swing.SwingUtilities;
    
      public class SimpleFrameTest extends JFrame {
    
      JLabel username = new JLabel("Press button to enter your name here");
    
       public SimpleFrameTest() {
    
            setSize(300, 300);
            setTitle("Test");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLocationRelativeTo(null);
            setResizable(true);
    
            initComponents();
    
            setVisible(true);
    
        }
    
        private void initComponents() {
    
            JPanel panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    
            username.setAlignmentX(Component.CENTER_ALIGNMENT);
    
            JButton setNameButton = new JButton("Set name");
            setNameButton.setAlignmentX(Component.CENTER_ALIGNMENT);
    
            setNameButton.addActionListener((ActionEvent e) -> {
                 String usernameinput = JOptionPane.showInputDialog(setNameButton, "Enter a username", "Set username", JOptionPane.OK_CANCEL_OPTION);
    
                 if (usernameinput != null) {
                     username.setText(String.valueOf(usernameinput));
                 }
            });
    
            panel.add(Box.createRigidArea(new Dimension(5,10)));
            panel.add(username);
            panel.add(Box.createRigidArea(new Dimension(5,10)));
            panel.add(setNameButton);
            add(panel);
    
        }
    
    
        public static void main(String args[]){
    
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new SimpleFrameTest();
    
            }
        });   
    
       }  
    
     }