1

如何通过侦听器从网格面板更新组件?

我有以下问题:我以这种方式创建一个网格表

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);
...
}

好的,这很好用,但我想向 JButton 添加一个允许更新的动作侦听器gridPanel,我想在我的 GUI 的构建器中添加它:

piece.addActionListener(new Listener(this));

我以这种方式创建了一个新类 ActionListener:

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()
}
}

我想在按下按钮时用新图像actionPerformed更改我的组件 1,gridPanel但这段代码不起作用,我尝试在网上搜索,但我没有找到解决方案。

4

1 回答 1

1

看看这些线程:

CardLayout 显示下一个面板 - java Swing

java swing动态添加组件

希望对您有所帮助。

于 2013-06-07T17:52:25.857 回答