简体   繁体   中英

How to make a Jpanel show after clicking on picture

I'm Writing a game where there are a set of islands and there are 5 workers on each island when i left click on a worker a cursor appears on it and when i right click on somewhere in the island the selected worker moves there..i want a JPanel to show on the right side of the screen every time i left click on a worker.the panel will show the workers stats such as Health and carrying weight but the problem is i can't make the panel appear.this is the code where i left click on a worker:

if(SwingUtilities.isLeftMouseButton(e)){
        if(canSelect){
        for (int j = 0; j < countries.size(); j++) {
            for (int i = 0; i < countries.elementAt(j).getMen().size(); i++) {
                if(m==countries.elementAt(j).getMen().elementAt(i).getX()  &&  n==countries.elementAt(j).getMen().elementAt(i).getY()) {
                    countries.elementAt(j).getMen().elementAt(i).setY(countries.elementAt(j).getMen().elementAt(i).getY()+1);


                    countries.elementAt(j).getMen().elementAt(i).setSelected(true);
                    getGraphics().drawImage(arrow.getImage(),  (countries.elementAt(j).getMen().elementAt(i).getX()+mapX)*20+5,(countries.elementAt(j).getMen().elementAt(i).getY()+mapY)*20-12,null);
                    canSelect = false;
                }
            }
        }
    }
}

I tried the below code on a jbutton click within JFrame and it didn't worked as expected. (that is to dynamically creating a panel with 2 labels and show in a JFrame)

JPanel p = new JPanel();
    p.setLayout(new GridLayout(2, 1));
    p.add(new JLabel("Health : 90%"));
    p.add(new JLabel("Carrying weight : 4 Kg"));
    this.add(p); //JFrame
    p.setSize(100, 50);
    p.setLocation(100, 100);
    p.setVisible(true);

But adding the code this.validate(); at the end of the above code, it worked fine. if, is this your problem, then it may help you.

Reference Link

May be your JPanel is created by below your existing JPanel so it can't be seen. Place your new JPanel on your existing JPanel . Like this

JPanel nPanel = new JPanel();
nPanel.setBounds(x,y,w,h);  //your desired location and size
mainPanel.add(nPanel); 
nPanel.setVisible(false);

Your can make it visible again with your event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM