So I've been looking for examples on the internet for a while now and this seems the most common way everyone is suggesting, but now I ask is there a better way to make a new jframe pop up on click than this.

The code :

JLabel prevention = new JLabel("<html><U><font color='red'>Prevencija</font><U></html>");
    prevention.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 100));
    prevention.addMouseListener(new MouseAdapter() {

        public void mouseClicked(MouseEvent e) {
            JFrame jf = new JFrame("Prevencija");
            jf.setContentPane(new PreventionPanel());
            jf.setSize(new Dimension(400, 400));
  • \$\begingroup\$ do you create more than one such clickable label? \$\endgroup\$ – I'll add comments tomorrow Feb 13 '16 at 21:29

In general the code is quite okay, here are a few remarks.

  • Maybe extract the body of the mouseClicked() method into a separate method, in case you have more code that would perform the same action, like when listening to keystrokes as well.
  • Consider using a JButton instead of a JLabel and use an ActionListener or even an Action instead of a MouseListener. Using a MouseListener for reacting on mouseClicked on the entire area of a JLabel seems like replicating something on a physical level for which Swing already provides something on a logical level.
  • I'd use WindowConstants.EXIT_ON_CLOSE instead of JFrame.EXIT_ON_CLOSE, as that's the original definition.
  • I'd use DISPOSE_ON_CLOSE instead of EXIT_ON_CLOSE and dispose all frames. Applications which use EXIT_ON_CLOSE become more difficult to test. When DISPOSE_ON_CLOSE doesn't work it usually means that you have a bad application design or bugs regarding threading.
  • Depending on what you want to achieve, you might be more interested in using JDialog or JOptionPane instead of JFrame for this use case. Maybe JOptionPane.showMessageDialog(). I can only recommend to look into those, not tell whether those are better for your use case, as your code and description don't give enough information for more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.