我正在使用 JFrame 和 JPanel 以及 ActionListener 处理 Java 中的 GUI,以便在单击按钮时编辑图像。目前,我在让名为 ButtonPanel 的 JPanel 类与 BufferedImage img 进行交互时遇到了很多麻烦。我试图显示图像的高度,但没有任何效果,我尝试了各种解决方案。我的 ButtonPanel 类的代码是:
class ButtonPanel extends JPanel
{
//JButton makeBlue;
BufferedImage img;
ButtonPanel(BufferedImage x)
{
final JButton makeBlue = new JButton ("Make Blue");
img = x;
//int width, height;
setBackground(Color.RED);
int height = 0;
add(makeBlue);
ActionListener action =
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource()== makeBlue)
{
//img = x;
height = img.getHeight();
// System.out.println(rgbvalue);
//System.out.println(width + " " + height);
setBackground(Color.GREEN);
repaint();
}
}
};
makeBlue.addActionListener(action);
}
}
每当我尝试使用 BufferedImage API 中的方法来编辑图像时(例如上面的代码),我都会收到此错误:
ImageEditorDeluxe.java:184: error: local variable height is accessed from within inner class; needs to be declared final
height = img.getHeight();
我已经尝试过初始化高度的地方,但没有任何效果。任何帮助,将不胜感激。
我有另一个名为 ProgramWindow 的类,其中我将图像编辑器的所有不同 JPanel 添加到一个主 JFrame 中,我认为这可能是我的问题所在,因为 BufferedImage 为空。以下是 ProgramWindow 的代码:
class ProgramWindow extends JFrame
{
ProgramWindow()
{
ImagePanel ip = new ImagePanel();
ChooseFile cf = new ChooseFile();
ButtonPanel bp = new ButtonPanel(ip.getImg());
add(ip, BorderLayout.CENTER);
add(cf, BorderLayout.SOUTH);
add(bp, BorderLayout.WEST);
}
}
我得出结论,ProgramWindow 中的 ButtonPanel 正在传递一个空参数,但我不知道这是为什么。我在 ImagePanel 类中有一个名为 getImg 的方法,我将其作为 ButtonPanel 的参数进行调用。这是 ImagePanel 的代码:
class ImagePanel extends JPanel
{
BufferedImage img;
ImagePanel()
{
setBackground(Color.BLUE); //to test
final JButton button = new JButton ("Display picture");
add(button);
ActionListener action =
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==button)
{
try
{
img = ImageIO.read(ChooseFile.getFile());
}
catch(IOException f)
{
f.printStackTrace();
}
repaint();
}
}
};
button.addActionListener(action);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (img != null)
g.drawImage(img, 0, 0, this);
}
public void setImage(BufferedImage i)
{
img = i;
repaint();
}
public BufferedImage getImg()
{
return img;
}
}
最佳答案
您在构造函数中声明高度,因此它是构造函数的本地高度。也许将其作为类的实例字段会更好。
public class ButtonPanel extends JPanel {
private BufferedImage img;
private int height;
话虽如此,为什么还要有一个高度变量字段,因为您可以随时通过调用 img.getHeight()
来获取它?
编辑
您的第二个问题(我们还无法帮助您解决)是您的 img 变量包含空引用。根据您的新代码,这表明 ip.getImg()
返回 null
,但不要相信我的话,测试一下。将此行放入您的代码中:
System.out.println("is ip.getImg() returning null? " + (ip.getImg()));
<小时/>
编辑2
当然你会得到空值。在用户有机会与其交互之前,您就从 ImagePanel 中提取了 img。由于它仅在用户按下按钮时获取图像,并且由于您在类创建时提取图像,因此在用户有机会蹲下之前,唯一的可能性是当您在类创建时提取图像时,你将会得到 null。解决方案:不要这样做。
关于java - 从 ActionListener 方法访问类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726416/