如何通过监听器从网格面板更新组件?
我有以下问题: 我以这种方式创建一个网格表
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);
...
}
好的,这很好,但是我想添加一个允许更新gridPanel
的JButton动作监听器,我想在我的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
用新图片更改我gridPanel
的组件1,但此代码不起作用,我尝试在网上搜索但我已经找不到解决方案。
答案 0 :(得分:1)