0

I want to open a new window when I click the label. By implementing a key pressed listener. But it is not working. Even nothing is happening.

JLabel lblNewLabel_2 = new JLabel("Create New Account!!!!");
lblNewLabel_2.setForeground(Color.GREEN);
lblNewLabel_2.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        
        Dosomething();
    }
});
private void Dosomething() {
    hide();
    Account account=new Account();
    account.visible();
    
}
protected static void hide() {
    frame.hide();
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mr.Roy
  • 35
  • 1
  • 2
  • 8
  • 3
    1) Post a proper [mre] demonstrating the problem. You have been aske for an MRE in previous questions: https://stackoverflow.com/questions/66823638/how-to-move-the-position-text-and-image-in-jlabel-jpanel. All questions should have an MRE. 2) method names should NOT start with an upper case character. Learn from the examples in your text book or tutorials. 3) Don't use a JLabel. Instead use a JButton with an ActionListener. Then use `setBorderPaintedFalse(...)`, `setFocusPainted(false)` so the button will look like a label. – camickr Jun 08 '21 at 15:32
  • 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) **Don't** use a `JLabel` for this. **Don't** use a `KeyListener`. An (undecorated) `JButton` with an `ActionListener` will look like a label and act on both mouse click **and** keyboard action (e.g. hitting the `Enter` key). – Andrew Thompson Jun 08 '21 at 15:40
  • By default, a `JLabel` does not get keyboard focus and therefore will not react to key presses. You can change that. See method `setFocusable`. However, I think you should adopt Andrew Thompson's suggestion to use `JButton` instead of `JLabel`. – Abra Jun 08 '21 at 17:55
  • i know that Jbutton is another option. But I was trying to do something else. But no problem i will use Jbutton then.... thank u so much for figure it out. – Mr.Roy Jun 08 '21 at 18:46

1 Answers1

1

You can use JButton as others say and remove its border to make it look like JLabel but if you really want to use JLabel and detect clicks I think you should write a MouseAdapter for it.

JLabel fooLabel = new JLabel("foo");

fooLabel.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                doSomething();
            }
        }
);

You can also override mouseClicked method but in that case the user must not move the cursor while clicking.

Metin Usta
  • 175
  • 1
  • 2
  • 11