一个问题,不应该继承WindowAdapter吧。那是个事件监听类的默认类。应该继承Frame 或者JFrame的才对。之后在想要的地方调用repaint();就可以了。

解决方案 »

  1.   

    我改成继承frame后和原来一样,还是没有画出来。
    是不是我读文件的方法不对啊,就是对那个文本文件,一个数值一个数值的读,不包括“,“,用read()对吗?
      

  2.   

    读值的问题解决了,用readline(),但还是画不出来。哪位帮我调调程序,好吗?
    另外JOptionPane.showMessageDialog的用法对不对?
    代码如下:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    import javax.swing.*;public class RasterCode extends Frame implements ActionListener{
    public Panel pnl;
    public MenuBar mnub;
    public Menu mnu,mnu1;
    public MenuItem item2,item11;
    public File f1;
    public FileReader fr;
    public BufferedReader br;
    public int x,y;   //用来绘制每个栅格时的左上角坐标
    public int len,wid;   //每次绘制矩形的长和宽
    public int i,j;   //坐标过渡参数
    int m,n;          //所绘栅格行列数
    int fillcolor;    //将栅格属性值赋给此参数,用来确定栅格表现颜色
    public Color col[]={Color.red,Color.blue,Color.cyan,Color.orange,Color.green,Color.gray,Color.magenta,Color.pink,Color.yellow};
    RasterCode(){
    super("栅格编码");
    setVisible(true);
    setResizable(true);
    setLayout(new FlowLayout());
    setBounds(200,200,240,300);
    mnub=new MenuBar();
    setMenuBar(mnub);
    mnu = new Menu("文件");
      mnu1 = new Menu("打开文件");
    item2 =new MenuItem("退出",new MenuShortcut(KeyEvent.VK_X));
    item11=new MenuItem("直接栅格编码");
    mnub.add(mnu);
    mnu.add(mnu1);
    mnu.addSeparator();
    mnu.add(item2);
    mnu1.add(item11);
    pnl=new Panel();
    add(pnl);
    mnu.addActionListener(this);
    item2.addActionListener(this);
    item11.addActionListener(this);
    }
    public void paint(Graphics g) {
    g.setColor(col[fillcolor-1]);
    g.fillRect((x-1)*40,(y-1)*40,len*40,wid*40);
    }
    public void actionPerformed(ActionEvent e){
    if(e.getSource()==item2){
    System.exit(0);
    }

    //直接栅格编码
    else if(e.getSource()==item11){
    try{
    FileDialog op=new FileDialog(this,"打开直接栅格编码文件",0);
    op.setVisible(true);
    f1=new File(op.getDirectory(),op.getFile());
    fr=new FileReader(f1);//读入文件到fr
    br=new BufferedReader(fr);//将文件读到缓冲区
    String str=br.readLine();
    String []s1=str.split(",");
    m=Integer.parseInt(s1[0]);
    n=Integer.parseInt(s1[1]);
    setBounds( 200, 200,m*40,n*40+20);
    for(x=1;i<=m;i++){
    str=br.readLine();
    for(y=1;j<=n;j++){
    String []s2=str.split(",");
    fillcolor=Integer.parseInt(s2[j-1]);
    len=wid=1;
    repaint();
    }
    }
    br.close();
    }
    catch(IOException i){
    JOptionPane.showMessageDialog(null,"file read Error!");
    }
    } public static void main(String args[]){
    new RasterCode();
    }
    }
    运行后打开一个文本文件,内容为:
    10,10
    1,1,1,1,1,2,2,2,4,4
    1,1,1,1,2,2,2,4,4,4
    1,1,1,3,3,2,2,2,4,4
    1,1,3,3,3,3,2,4,4,4
    1,3,3,3,3,3,3,4,4,4
    4,4,3,3,3,3,2,1,1,1
    4,4,4,3,3,2,2,2,1,1
    4,4,4,4,2,2,2,2,2,1
    4,4,4,2,2,2,2,2,2,2
    4,4,2,2,2,2,2,2,2,2
    运行结果应当跟上面的方正一样,只不过不同值用颜色表示而已。