Search code examples
javaswingdocumentjtextfieldjoptionpane

not showing message diologe with JOptione pane


i have written a code to create a sms form and i want to add the ability to show error message when the text area is empty. i put JOptionpane in my code but diologe dose not appear when i run the program! here is my code

private void initialize() {
    frame = new JFrame("?????? ? ????? ?????");
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JOptionPane optionPane = new JOptionPane();


    JPanel middlePanel = new JPanel();

    txtPath = new JTextField();
    txtPath.setBounds(150, 10, 200, 21);
    frame.getContentPane().add(txtPath);
    txtPath.setColumns(10);

    txtPath2 = new JTextField();
    txtPath2.setBounds(150, 65, 200, 21);
    frame.getContentPane().add(txtPath2);
    txtPath2.setColumns(20);

    JButton btnBrowse = new JButton("?????");
    btnBrowse.setBounds(5, 10, 87, 23);
    frame.getContentPane().add(btnBrowse);

    final JButton ok = new JButton("?????");
    ok.setBounds(250, 230, 87, 23);
    frame.getContentPane().add(ok);

    JButton cancel = new JButton("???");
    cancel.setBounds(110, 230, 87, 23);
    frame.getContentPane().add(cancel);


    final JTextArea textarea = new JTextArea();
    textarea.setBounds(50, 100, 300, 100);
    frame.getContentPane().add(textarea);
    textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);




    JProgressBar progressBar = new JProgressBar(0, 100);
    progressBar.setSize(10, 1);
    progressBar.setForeground(Color.blue);
    frame.getContentPane().add(progressBar);





    btnBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();

            // For Directory
            fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

            // For File
            //fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

            fileChooser.setAcceptAllFileFilterUsed(false);

            int rVal = fileChooser.showOpenDialog(null);
            if (rVal == JFileChooser.APPROVE_OPTION) {
                txtPath.setText(fileChooser.getSelectedFile().toString());
                fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt", "rtf"));

            }
        }
    });



   ok.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(textarea.getLineCount()>=1)
            {


          test t=new test();
            ReadTextFile readTextFile=new ReadTextFile();
            t.testMethode(txtPath2.getText(), textarea.getText(),readTextFile.readFile(txtPath.getText()) );
        }
            else
                JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
        }
    });




        cancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }
        });


    }
    }

Solution

  • GUI's are event driven environments. Something happens, you respond to it.

    You if-else statement will never be false because the time it is executed, the textarea will be blank (have no text).

    You need to respond to some event (ie send for example) at which time you would make your check to valid the form.

    Take a look at Creating a GUI with Swing for more details

    Updated with example

    enter image description here

    public class Example {
    
        public static void main(String[] args) {
            new Example();
        }
    
        public Example() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            private final JTextArea msg;
    
            public TestPane() {
    
                msg = new JTextArea(10, 20);
                JButton send = new JButton("Send");
    
                setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;
    
                add(new JScrollPane(msg), gbc);
                add(send, gbc);
    
                send.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (msg.getText().trim().length() > 0) {
                            // Send msg
                        } else {
                            JOptionPane.showMessageDialog(TestPane.this, "Please write something (nice)", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                });
    
            }
    
        }
    }
    

    Updated based on changes to the answer by the OP

    if(textarea.getLineCount()>=1) will always return true. Try using msg.getText().trim().length() > 0 instead to determine the JTextArea contains text or not...

    Updated

    mKobel has made an excellent point. You really should avoid using null layouts. You don't control what font size or screen DPI/resolution your application might need to work on. Layout managers take out the guess work.

    You should try checking out A visual guide to layout managers and Using layout managers for more details