我正在开发一款类似数字口袋妖怪卡片的游戏。当我尝试绘制任何图像时,JFrame仍为空。这可能是一个简单的错误,但我找不到解决方案。在Stack Overflow上,虽然他们的解决方案对我的代码不起作用,但我已经看到了很多像我这样的问题。这是代码: JFrame的类:
import javax.swing.JFrame;
public class Rocks extends JFrame{
public Rocks(){
setVisible(true);
setTitle("Rocks Card Game");
setSize(1200,297);
add(new Display());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Rocks();
}
}
JPanel类:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Display extends JPanel{
Image granite;
public Display(){
granite = new ImageIcon("C:\\Users\\Raj\\Pictures\\Granite.png").getImage();
setBackground(Color.black);
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(granite,0,0,null);
}
}
答案 0 :(得分:2)
如果您没有JFrame
,是否有理由扩展JLabel
。它比继承更受欢迎。由于@camickr不需要自定义绘画,您可以使用setIcon
并致电public class Rocks{
private JFrame frame;
public Rocks(){
frame = new JFrame();
frame.setTitle("Rocks Card Game");
frame.setSize(1200,297);
//frame.add(new Display());
//as camickr comment
JLabel label = new JLabel(new ImageIcon("C:\\Users\\Raj\\Pictures\\Granite.png"));
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); // size components
frame.setVisible(true); // make it visible
}
public static void main(String[] args) {
new Rocks();
}
}
。
public class Display extends JPanel{
Image granite;
public Display(){
granite = new ImageIcon("C:\\Users\\Raj\\Pictures\\Granite.png").getImage();
setBackground(Color.black);
}
@Override // always add override annotation
public void paintComponent(Graphics g){
super.paintComponent(g); // always call super first
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(granite,0,0,this);
}
}
另外你必须看看 Swing程序是否应该覆盖paintComponent()而不是覆盖paint()
所以(如果您仍想使用面板)更改您的面板类
{{1}}
答案 1 :(得分:1)
将setVisible(true);
移至Rocks构造函数的底部。