Malwaregeek
Malwaregeek

Reputation: 2274

Displaying a JPanel on JFrame by a label click

I have tried it over and over.Its not working.When I click the lablel, nothing happens.

 private void jLabel1MouseClicked(java.awt.event.MouseEvent evt)                 

  {                                     
        setLayout(new BorderLayout());
        JPanel o = new JPanel ();
        o.setPreferredSize(new Dimension(122,200));
        o.setBackground(Color.red);
    add(o,BroderLayout.CENTER);

        // TODO add your handling code here:
    } 

Upvotes: 0

Views: 251

Answers (3)

MMujtabaRoohani
MMujtabaRoohani

Reputation: 483

I Think you are using Netbeans, If yes then the method you showed is auto-generated which means that it has correctly implemented Listeners in it's Auto-Generated Code Segment, well for now this means that you have error in Showing JPanel not in implementing listener, so I found some suggestions for you,

  1. you have written BroderLayout but its BorderLayout but this seems to be a typo when posting Question.
  2. Secondly you are not updating your frame, just adding the JPanel is not enough for showing it, so Add this code, this.revalidate();

so finally your block code should be like this,

private void jLabel1MouseClicked(java.awt.event.MouseEvent evt)                 

{                                     
    setLayout(new BorderLayout());
    JPanel o = new JPanel ();
    o.setPreferredSize(new Dimension(122,200));
    o.setBackground(Color.red);
    add(o,BorderLayout.CENTER);
    revalidate();        
}

Upvotes: 0

Arctigor
Arctigor

Reputation: 247

if the Listener is implemented correctly, then you should change this

o.setPreferredSize(new Dimension(122,200));

with this

o.setSize(122,200);

you can put a setVisible method too, but it should work without it, too

Upvotes: 0

José Ramón
José Ramón

Reputation: 182

Looks a stupid question, but, are you sure that your method is getting called? Is your object registered as an event listener of this label?

Just to be sure, you should implement the MouseListener interface:

public class YourClass () implements MouseListener{
    public YourClass(){
        ...
        label.addListener(this);
    }
    // and then implement the method to handle the event
    public void mouseClicked(MouseEvent e) {
        // TODO: Handle the event
    }
}

jLabel1MouseClicked does not look like the event handler method

EDIT: By the way, you may want to implement the other methods in this interface, even if you don't need them. Check the documentation: MouseListener example

Upvotes: 1

Related Questions