Java 8/Eclipse 图像不可见
Java 8/Eclipse Image not visible
我正在尝试获取一个小动画的图像,但面板保持白色。
该图像与 class 在同一文件夹中。
public class JBallonPanel extends JPanel implements Runnable{
private Image img;
private int x, y;
JBallonPanel(){
setBackground(Color.white);
img=Toolkit.getDefaultToolkit().createImage(".//Ball.jpg");
x=this.getWidth()/2;
y=this.getHeight()/2;
}
public void paintComponent(Graphics g){
g.drawImage(img, x, y,
img.getWidth(this), img.getWidth(this), this);
}
请看下面,我只是做了一些调整,但您的代码可以正常工作。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
//public class JBallonPanel extends JPanel implements Runnable {
//You can remove implements Runnable
public class JBallonPanel extends JPanel {
private Image img;
private int x, y;
JBallonPanel(){
setBackground(Color.white);
// your path should have \ for example C:\Ball.jpg or C:\myImageFolder\Ball.jpg
// but in your case, it works too.
img=Toolkit.getDefaultToolkit().createImage("C:\Ball.jpg");
x=this.getWidth()/2;
y=this.getHeight()/2;
}
public void paintComponent(Graphics g){
g.drawImage(img, x, y, img.getWidth(this), img.getWidth(this), this);
}
//And run like this
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new JBallonPanel());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(800, 800);
frame.setVisible(true);
}
}
我正在尝试获取一个小动画的图像,但面板保持白色。 该图像与 class 在同一文件夹中。
public class JBallonPanel extends JPanel implements Runnable{
private Image img;
private int x, y;
JBallonPanel(){
setBackground(Color.white);
img=Toolkit.getDefaultToolkit().createImage(".//Ball.jpg");
x=this.getWidth()/2;
y=this.getHeight()/2;
}
public void paintComponent(Graphics g){
g.drawImage(img, x, y,
img.getWidth(this), img.getWidth(this), this);
}
请看下面,我只是做了一些调整,但您的代码可以正常工作。
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
//public class JBallonPanel extends JPanel implements Runnable {
//You can remove implements Runnable
public class JBallonPanel extends JPanel {
private Image img;
private int x, y;
JBallonPanel(){
setBackground(Color.white);
// your path should have \ for example C:\Ball.jpg or C:\myImageFolder\Ball.jpg
// but in your case, it works too.
img=Toolkit.getDefaultToolkit().createImage("C:\Ball.jpg");
x=this.getWidth()/2;
y=this.getHeight()/2;
}
public void paintComponent(Graphics g){
g.drawImage(img, x, y, img.getWidth(this), img.getWidth(this), this);
}
//And run like this
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new JBallonPanel());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(800, 800);
frame.setVisible(true);
}
}