1
\$\begingroup\$

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() {
 @Override
 public void mouseClicked(MouseEvent e) {
 JFrame jf = new JFrame("Prevencija");
 jf.setContentPane(new PreventionPanel());
 jf.setSize(new Dimension(400, 400));
 jf.setVisible(true);
 jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 });
 bottom.add(prevention);
asked Feb 13, 2016 at 19:42
\$\endgroup\$
1
  • \$\begingroup\$ do you create more than one such clickable label? \$\endgroup\$ Commented Feb 13, 2016 at 21:29

1 Answer 1

2
\$\begingroup\$

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.
answered Feb 13, 2016 at 20:40
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.