gpt4 book ai didi

java - 面板中的背景颜色不会改变

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:48:06 24 4
gpt4 key购买 nike

下面的代码生成一个带有按钮的窗口,但是当我运行 i 并实际按下按钮时会弹出一条错误消息。根据 Spring 工具提示:

Cannot make a static reference to the non-static method setBackground(Color) from the type JComponent

据我所知,这个程序是从我的 Java 教科书逐行输入的。这是一本较旧的书,因此可能存在不兼容性,但似乎不太可能。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonTest
{
public static void main(String[] args)
{
final ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("Button Test");
setSize(Default_width, Default_height);

//panel
ButtonPanel panel = new ButtonPanel();
Container contentPane=getContentPane();
contentPane.add(panel);
}

public static final int Default_width = 300;
public static final int Default_height = 200;
}

class ButtonPanel extends JPanel
{
public ButtonPanel()
{
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");

add(yellowButton);
add(blueButton);
add(redButton);

ColorAction yellowAction= new ColorAction(Color.YELLOW);
ColorAction redAction = new ColorAction(Color.RED);
ColorAction blueAction = new ColorAction(Color.BLUE);

yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
}

class ColorAction implements ActionListener
{
public ColorAction(Color c)
{
backgroundColor=c;
}

public void actionPerformed(ActionEvent event)
{
ButtonPanel.setBackground(backgroundColor);
}

private Color backgroundColor;
}

最佳答案

一种方法是 nest ColorAction 作为 ButtonPanel 中的内部类,它可以隐式访问封闭面板。

附录:正如@Andrew Thompson 和@nachokk 在评论中指出的那样,隐式可访问性可以通过使用封闭类名限定 this 来明确显示。参见 JLS §15.8.4. Qualified this了解详情。在此示例中,这两个调用是等效的:

 setBackground(backgroundColor);
ButtonPanel.this.setBackground(backgroundColor);

作为更通用的替代方案,考虑将目标面板和颜色封装在 Action 中,如 here 所述.

image

class ButtonPanel extends JPanel {

public ButtonPanel() {
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");

add(yellowButton);
add(blueButton);
add(redButton);

ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction redAction = new ColorAction(Color.RED);
ColorAction blueAction = new ColorAction(Color.BLUE);

yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}

private class ColorAction implements ActionListener {

public ColorAction(Color c) {
backgroundColor = c;
}

@Override
public void actionPerformed(ActionEvent event) {
setBackground(backgroundColor);
}
private Color backgroundColor;
}
}

关于java - 面板中的背景颜色不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com