我把这个作为家庭练习,但我不知道如何解决它......(只是访问部分有点难以弄清楚)
所以,我有两个类:“Top”和“Main”。 Top 类如下所示:(简短说明:Top 类的变量“pane”将在 Main 类中用作顶部面板,Main 扩展了 JFrame 并具有 BorderLayout)
public class Top extends JPanel implements ActionListener {
//public JPanel pane;
public JButton red, green, blue, white, black;
public Top() {
//pane = new JPanel(); //Useless, as Top is already a JPanel
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setBackground(new Color(0xc9c9c9)); //A gray background
red = new JButton("Red");
red.setBackground(Color.red);
red.addActionListener(this);
this.add(red);
green = new JButton("Green");
green.setBackground(Color.green);
green.addActionListener(this);
this.add(green);
blue = new JButton("Blue");
blue.setBackground(Color.blue);
blue.addActionListener(this);
this.add(green);
white = new JButton("White");
white.setBackground(Color.white);
white.addActionListener(this);
this.add(white);
black = new JButton("Black");
black.setForeground(Color.white);
black.setBackground(Color.black);
black.addActionListener(this);
this.add(black);
}
public void actionPerformed(ActionEvent e) {
Main main = (Main)e.getSource();
if (e.getSource() == this.red)
main.setCENTER(1);
if(e.getSource() == this.green)
main.setCENTER(2);
if(e.getSource() == this.blue)
main.setCENTER(3);
if(e.getSource() == this.white)
main.setCENTER(4);
if(e.getSource() == this.black)
main.setCENTER(5);
}
}
顶级类正在主类中使用,每次按下每个按钮时,主类的中心区域的背景都会发生变化。因此我编写了一个小函数setCENTER,它可以改变背景。它的代码如下所示(代码位于 Main 类中):
public void setCENTER(int var){
switch(var){
case 1: pane.setBackground(Color.red);
break;
case 2: pane.setBackground(Color.green);
break;
case 3: pane.setBackground(Color.blue);
break;
case 4: pane.setBackground(Color.white);
break;
case 5: pane.setBackground(Color.black);
break;
}
}
到目前为止,内容显示正确(主窗口的顶部面板和主窗口本身),但每次我尝试通过按顶部面板中的 5 个按钮之一来更改背景时,都会出现错误并且第一个错误将我指向顶级类中 actionPerformed-method 的这一行:
Main main = (Main)e.getSource();
我尝试将其替换为“Main main = new Main();”。它起作用了,背景发生了变化,但每次我按下它时,它都会打开一个新窗口(这显然不是它应有的行为)。
编辑:我忘记了 Top 已经是一个 JPanel,所以在类中使用另一个 JPanel 是非常没有意义的。 (已编辑来源)
最佳答案
事件的来源是按钮。要查找按钮所属的面板,您可以获取按钮的父级:
JButton button = (JButton)e.getSource();
JPanel parent = button.getParent();
要获取主面板,您可能还需要在父面板上调用 getParent()。
关于java - 使用 ActionListener 访问预父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8695259/