use*_*440 5 java user-interface swing
我是一名java初学者,在我的第一个项目中,我开始构建一个大富翁游戏.
我正在使用Graphics方法在SWING中构建GUI.
出现了两个我无法找到答案的问题.
第一个是我似乎无法将背景颜色设置为我的JPanel,我以前在同一个项目中的另一个JPanel中以相同的方式进行了操作.
第二个是我NullPointerException试图添加一个图像.我设法纠正这个错误,try/catch但似乎图形不会绘制.我再次使用相同的方法加载和添加图像JPanel和它工作.
我应该提一下,我的JFrame目前包含3个元素,每个人都在单独的类中,并通过BorderLayout()添加.
这是创建问题的类的代码:
public class MonopolyBoard extends JPanel{
Image atlantic;
MonopolyBoard() {
this.setBorder(new EtchedBorder());
this.setBackground(new Color( (80), (180), (210) )); //this code dosent work
//this throws exception without try catch
try{
ImageIcon a = new ImageIcon(this.getClass().getResource("../Card/Atlantic Ave.jpg"));
atlantic = a.getImage();
}
catch(NullPointerException e){}
}
public void paint(Graphics g){
}
Graphics2D g2 = (Graphics2D) g;
//this code should draw the image but it dosent
g2.drawImage(atlantic, 100, 100, null);
g.drawImage(atlantic, 100, 100, this);
};
}
Run Code Online (Sandbox Code Playgroud)
除非您在 catch 块内打印堆栈跟踪,否则您不会知道。如果构造函数new ImageIcon()不抛出异常,而是返回空对象,则下一行a.getImage()肯定会导致 NPE,因为您无法在空对象上调用方法。
而不是这个
//this throws exception without try catch
try
{
ImageIcon a = new ImageIcon(this.getClass().getResource("../Card/AtlanticAve.jpg"));
atlantic = a.getImage();
}
catch(NullPointerException e){}
Run Code Online (Sandbox Code Playgroud)
尝试这个
// the next line may be wrapped incorrectly due to MarkDown
ImageIcon a = new ImageIcon(this.getClass().getResource("../Card/AtlanticAve.jpg"));
if (a == null)
{
System.out.println("Can not find AtlanticAve.jpg");
return;
}
atlantic = a.getImage();
Run Code Online (Sandbox Code Playgroud)
线路
// the next line may be wrapped incorrectly due to MarkDown
ImageIcon a = new ImageIcon(this.getClass().getResource("../Card/AtlanticAve.jpg"));
Run Code Online (Sandbox Code Playgroud)
基本上,您需要首先了解如果 ImageIcon 返回空对象,可能会导致构造函数的原因。这会让你走上正轨。这可能是由于 getResource() 调用失败造成的。找出答案的一个简单方法是将上面的行分成几个部分,并为它们提供自己的结果变量。这很混乱且效率低下,但这就是有时故障排除的方式。
// using _var_ because I'm too lazy to look up the return types of the methods
var x1 = this.getClass().getResource("../Card/AtlanticAve.jpg");
if (x1 == null)
{
System.out.println("Can't find my resource");
}
Run Code Online (Sandbox Code Playgroud)
你明白了图片
| 归档时间: |
|
| 查看次数: |
451 次 |
| 最近记录: |