Kri*_*isC 4 java variables swing jpanel jbutton
最近我尝试制作一个简单的程序,需要在屏幕上多次移动按钮,但为了做到这一点,我必须能够从代码的某些部分访问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做任何事情.
如果你需要访问一个变量,在这里你的buttonMoverPanel,那么不要通过在方法或构造函数中声明它使它只在该方法或构造函数中可见来隐藏它.不,在课堂上宣布它,以便在整个班级中可见.
因此,对此代码的一个改进是声明类中的buttonMoverPanel与您当前对actionButton JButton执行的操作相同.
编辑:你正在影响你的actionButton变量 - 你在构造函数中重新声明它,因此actionButton类字段不会引用添加到GUI的按钮.不要在课堂上重新声明它.
换句话说,指示的行创建了一个全新的actionButton变量,该变量只在构造函数中可见:
JButton actionButton;
JPanel buttonMoverPanel = new JPanel();
public ButtonMover() {
buttonMoverPanel.setLayout(new GridBagLayout());
this.add(buttonMoverPanel);
this.setSize(500, 500);
this.setResizable(true);
this.setVisible(true);
JButton actionButton = new JButton("Testing Button"); // ****** here
Run Code Online (Sandbox Code Playgroud)
解决方案是不要重新声明变量而是使用类字段:
JButton actionButton;
JPanel buttonMoverPanel = new JPanel();
public ButtonMover() {
buttonMoverPanel.setLayout(new GridBagLayout());
this.add(buttonMoverPanel);
this.setSize(500, 500);
this.setResizable(true);
this.setVisible(true);
actionButton = new JButton("Testing Button"); // ****** Note the difference???
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
114 次 |
最近记录: |