0

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;
                }
            }
        }
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

2 Answers2

0

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

Community
  • 1
  • 1
Jeet
  • 1,006
  • 1
  • 14
  • 25
0

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

Rahul
  • 289
  • 2
  • 7