【发布时间】:2013-06-04 02:16:09
【问题描述】:
如何通过 Listener 从网格面板更新组件?
我有以下问题: 我用这种方式创建了一个网格表
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 用新图像更改我的gridPanel 的组件 1 但此代码不起作用,我尝试在网络上搜索但我没有找到解决方案.
【问题讨论】:
-
别这样,也许有人....
-
您使用变量
gui两次 - 但它在任何地方都没有声明(只是gui1)。注意:类名使用大写,变量/字段使用小写。 -
是编译时错误还是运行时异常?
-
是的,我在这段代码中声明了 gui1 和使用 gui,但这只是一个错字,因为我重命名了原始变量,但我的代码是正确的;)是的,有一个运行时异常“NullPointerException” JPanel panel = (JPanel)getGridPanel().getComponent(1) 但我不明白为什么...
标签: java swing awt actionlistener