15

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?

enter image description here

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1992697
  • 315
  • 1
  • 5
  • 11
  • you can use `MouseListener` interface and in `mouseClicked(MouseEvent e)` check the source of click using `e.getSource() ==your label` and create new frame there. – kaysush Feb 06 '13 at 17:27
  • They are actually buttons without background and borders. Labels are not designed for that use case, and will be harder to adapt to your game's future needs. Labels don't even have focus. And their accessibility support is inappropriate for your use case, if you care about that. Finally, as a side note, I wouldn't draw text over a drawing, especially if part of it is the same color of the text. I think that developing a custom look and feel will be less of a pain rather than reusing the label trick in many parts of the game. – ignis Feb 06 '13 at 17:45
  • ...as suggested card layout should be considered here – ΦXocę 웃 Пepeúpa ツ Jul 24 '16 at 07:25

5 Answers5

37

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);

    }  
}); 
Robin Chander
  • 7,225
  • 3
  • 28
  • 42
3

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);
        }
    });
Arpit
  • 12,767
  • 3
  • 27
  • 40
2
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

You could do that like this:

label.addMouseListener(new MouseAdapter()   {   

        public void mouseClicked(MouseEvent e)   
        {   
              JPanel j = new JPanel();
              frame.setContentPane(j);
        }   
});
Vuk Vasić
  • 1,398
  • 10
  • 27
0
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 .
c.pramod
  • 606
  • 1
  • 8
  • 22