\$\begingroup\$
\$\endgroup\$
1
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);
-
\$\begingroup\$ do you create more than one such clickable label? \$\endgroup\$I'll add comments tomorrow– I'll add comments tomorrow2016年02月13日 21:29:42 +00:00Commented Feb 13, 2016 at 21:29
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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 aJLabel
and use anActionListener
or even anAction
instead of aMouseListener
. Using aMouseListener
for reacting onmouseClicked
on the entire area of aJLabel
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 ofJFrame.EXIT_ON_CLOSE
, as that's the original definition. - I'd use
DISPOSE_ON_CLOSE
instead ofEXIT_ON_CLOSE
and dispose all frames. Applications which useEXIT_ON_CLOSE
become more difficult to test. WhenDISPOSE_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
orJOptionPane
instead ofJFrame
for this use case. MaybeJOptionPane.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
lang-java