import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Ellipse2D.Double;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ChessPanel extends JFrame {
public ChessPanel()
{
setTitle("Chess");
setSize(800,700);
add(new Chess());
}
private class Chess extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Rectangle2D rect=new Rectangle2D.Double(100,100,500,500);
// double l=250*Math.sin(Math.PI/5)*2;
// double ly=
g2.draw(rect);
Ellipse2D ellipse=new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
// Line2D line1=new Line2D.Double(200,200,500,200);
// Line2D line2=new Line2D.Double()
// g2.draw(line1);
g2.setBackground(Color.BLUE);
// try {
// Image image=ImageIO.read(new File("pic/a.jpg"));
// g2.drawImage(image, 0, 0, null);
//
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// Image backGround=this.getToolkit().getImage("pic/a.jpg");
ImageIcon img = new ImageIcon("a.jpg");
g2.drawImage(img.getImage(), 0, 0, null);
// g2.drawImage(backGround,0,0,500,500,this);
// g2.drawImage(new Image("pic/a.jpg"), 100, 100, 300, 100, 100, 300, 300, 300, "dd");
}
}
public static void main(String[] a)
{
ChessPanel frame=new ChessPanel();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
我只是想为JPanel添加一个背景图片 为上面方法都不能实现 能简述以下 以上方法的区别吗 谢谢
------解决方案--------------------------------------------------------
我也是菜鸟,我知道怎么改能添加图片,原因不知
ImageIcon img = new ImageIcon("a.jpg");这句改下:
ImageIcon img = new ImageIcon(this.getClass().getClassLoader().getResource("a.jpg"));
我试过,没问题。