[英]How to call variables from another class into an ActionListener method?
[英]Accessing class variables from ActionListener method
當我單擊按鈕時,我正在使用JFrame和JPanel使用Java中的GUI,以及ActionListener來編輯圖像。 目前,讓名為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的類,其中將圖像編輯器的所有不同JPanels添加到一個主JFrame中,我認為這可能是我的問題所在,因為BufferedImage為null。 這是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傳遞一個null參數,但是我不知道為什么這樣做。 我在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;
話雖如此,為什么還要有一個height變量字段,因為您可以通過調用img.getHeight()
隨時獲取它?
編輯
您的第二個問題(我們尚無法解決)是img變量包含空引用。 給定您的新代碼,這表明ip.getImg()
返回null
,但是請不要相信我的話,對其進行測試。 將此行放在您的代碼中:
System.out.println("is ip.getImg() returning null? " + (ip.getImg()));
編輯2
當然,您會得到null。 您是在用戶有機會與ImagePanel進行交互之前從ImagePanel中提取img的。 由於只有在用戶按下按鈕時它才會獲得圖像,並且由於您是在創建類時提取圖像的,因此在用戶下蹲之前,唯一的可能性是,當您在類創建時提取圖像時,您將得到null。 解決方案:不要那樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.