日期:2014-05-20  浏览次数:20767 次

创建窗口显示图片出错了
//MyJFrame类
import java.awt.*;
import javax.swing.*;
public class MyJFrame extends JFrame
{
JSplitPane jsp;
MyJPanel panel2=new MyJPanel();
public MyJFrame(String s){
super(s);
Container contentPane=getContentPane();
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(5,1));

JButton btn[]=new JButton[5];
for(int i=0;i<5;i++){
btn[i]=new JButton("按钮"+(i+1));
panel.add(btn[i]);
}
 
jsp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel2,panel);
contentPane.add(jsp,BorderLayout.CENTER);
setSize(400,300);
setVisible(true);
}
public static void main(String [] args){
MyJFrame myJFrame=new MyJFrame("TongXunLu");
}
}
//MyJPanel类
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class MyJPanel extends JPanel {
  Image image;
  public MyJPanel(){
  Toolkit tk=this.getToolkit();
  image=tk.getImage("abc.jpg");
  }
  public void paint(Graphics g){
  super.paint(g);
  g.drawImage(image,20,20,50,50,this);
  }
  public Dimension getPreferredSize(){
  return new Dimension(100,100);
  }
}
我就是想创建一个窗口、左边显示一张图片、右边显示5个按钮、但是出错了、错在哪里啊?求指导。谢谢了啊

------解决方案--------------------
比较推荐的做法是将abc.jpg文件放在跟MyPanel.java文件同一个目录下,然后代码改成这样
Java code

import javax.swing.*;
import java.awt.*;

class MyJPanel extends JPanel {
    Image image;
    public MyJPanel(){
        Toolkit tk=this.getToolkit();
        image=tk.getImage(this.getClass().getResource("abc.jpg"));
    }
    public void paint(Graphics g){
        super.paint(g);
        g.drawImage(image,20,20,50,50,this);
    }
    public Dimension getPreferredSize(){
        return new Dimension(100,100);
    }
}