最近我尝试制作一个简单的程序,需要在屏幕上多次移动按钮,但为了做到这一点,我必须能够从代码的某些部分访问JPanel,我似乎没有能够做到,或找到另一种方法.这是一个小程序,应该指出我遇到的问题.
public class ButtonMover extends JFrame
{
public static void main(String[] args) {
new ButtonMover();
}
JButton actionButton;
public ButtonMover() {
JPanel buttonMoverPanel = new JPanel();
buttonMoverPanel.setLayout(new GridBagLayout());
this.add(buttonMoverPanel);
this.setSize(500,500);
this.setResizable(true);
this.setVisible(true);
JButton actionButton = new JButton("Testing Button");
buttonMoverPanel.add(actionButton);
ClickListener c = new ClickListener();
actionButton.addActionListener(c);
}
private class ClickListener
implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == actionButton)
buttonMoverPanel.add(new JLabel("Testing Label"));
//insert code to move button here
}
}
}
Run Code Online (Sandbox Code Playgroud)
| buttonMoverPanel.add(新的JLabel("测试标签")); | line是唯一不起作用的部分,因为我似乎无法从该区域引用buttonMoverPanel.虽然它实际上不会导致任何错误,但它会阻止actionButton做任何事情.