1

How to update a component from a grid panel through a Listener?

I have the following problem: I create a grid table in this way

public class gui {

JPanel gridPanel = new JPanel();
JPanel background = new JPanel();
JLayeredPane layeredPanel = new JLayeredPane();
...

public gui{
...
for(int i=0; i<2; i++){
            JPanel panel= new JPanel(new BorderLayout());
            panel.setOpaque(false);
            gridPanel.add(panel);
            }


gridPanel.setOpaque(false);
layered.add(background,new Integer(1));
layered.add(gridPanel, new Integer(2));

JButton piece = new JButton( new ImageIcon("an image"));
JPanel panel = (JPanel)gridPanel.getComponent(0);
panel.add(piece);
...
}

Ok, this works good, but I want to add an Action Listener to JButton that allow to update the gridPanel, I thought of addign this in the builder of my GUI:

piece.addActionListener(new Listener(this));

I create a new class ActionListener in this way:

public class Listener implements ActionListener{
private gui gui1;
public movimentoListener(gui gui1){
    gui1=gui;       
}
public void actionPerformed(ActionEvent e){
    JButton piece = new JButton( new ImageIcon("an other image"));
            JPanel panel = (JPanel)getGridPanel().getComponent(1); //obviously I've created getGridPanel
            panel.add(piece);
            gui.getGridPanel().repaint()
}
}

I want when I press the button my actionPerformed change the component 1 of my gridPanel with a new image but this code don't work, I try to search on the web but I've not found a solution.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • don't do that this way, maybe someone .... – mKorbel Jun 07 '13 at 17:33
  • 2
    You use variable `gui` two times - but it is declared nowhere (just `gui1`). Note: use capital names for classes and lower case for variables/fields. – Howard Jun 07 '13 at 17:33
  • Is it a compile-time error or a runtime exception? – gparyani Jun 07 '13 at 17:34
  • See also this [`GridButtonPanel`](http://stackoverflow.com/a/7706684/230513). – trashgod Jun 07 '13 at 20:08
  • Yes, I declare gui1 and the use gui in this code but it's only a typo because I rename the original variable, but my code is right ;) Yes, there is a runtime exception "NullPointerException" on JPanel panel = (JPanel)getGridPanel().getComponent(1) But I don't understand why... – user2464276 Jun 07 '13 at 20:11

1 Answers1

1

Have a look on these threads:

CardLayout display Next panel - java Swing

java swing dynamically adding components

Wish it helps you.

Community
  • 1
  • 1
Kaem Jii
  • 82
  • 8