如何通过侦听器从网格面板更新组件?
我有以下问题:我以这种方式创建一个网格表
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
但这段代码不起作用,我尝试在网上搜索,但我没有找到解决方案。