I'm developing graphics for a game I'm programming, I wanted to know if there is an easy way to open a frame when JLabel clicks?
Is there any simple code for this?
MouseListener interface and use its mouseClicked to handle clicks on JLabel.
MouseListener
mouseClicked
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); } });
You can do it like this:
label.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { JPanel j = new JPanel(); frame.setContentPane(j); } });
create a shortcut and add a click event to it.
Something like that:
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); } });
never create a new JFrame , never bind JFrames, you have to calculate it with OutOfMemoryException , because this Object will never be GC'ed,
OutOfMemoryException
Object
for several species to use CardLayout
see answer Using multiple JFrames, Good / Bad Practice? @Andrew Thompson
@Andrew Thompson
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 .