I am designing the graphics for a game i am programming, i wanted to know if there is an easy way of opening a frame when a JLabel is cliked?
Is there easy code for this?
I am designing the graphics for a game i am programming, i wanted to know if there is an easy way of opening a frame when a JLabel is cliked?
Is there easy code for this?
Implement MouseListener
interface and use it mouseClicked
method to handle the clicks on the JLabel.
label.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
// you can open a new frame here as
// i have assumed you have declared "frame" as instance variable
frame = new JFrame("new frame");
frame.setVisible(true);
}
});
create a label and add click event in it .
Something like this :
JLabel click=new JLabel("Click me");
click.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JFrame jf=new JFrame("new one");
jf.setBackground(Color.BLACK);
jf.setSize(new Dimension(200,70));
jf.setVisible(true);
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
});
don't to create a new JFrame, never bunch of JFrames, have to calculating with OutOfMemoryException
, because this Object
never will be GC'ed,
for multiple of views to use CardLayout
see answer The Use of Multiple JFrames, Good/Bad Practice? by @Andrew Thompson
You could do that like this:
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e)
{
JPanel j = new JPanel();
frame.setContentPane(j);
}
});
1:- Implement your class containing the JLabel with MouseListener interface
2:- add MouseListener to your JLabel
3:-Override mouseClicked Event in your class
4:- In mouseClicked Even't body add your code to open a new JFrame/Frame .