要求创建一个菜单并且读入数据,要求绘出地图。
代码如下,刚接触java一个月,写得复杂望各位大神包涵!!
编译出来后没有错位 但是点击打开是没有办法绘出线段,
实在不知道是怎么回事,希望有大神能够指点一下并帮忙改正一下!
感激不尽!!!!import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Menu1 extends Frame
{

int x1,y1,x2,y2; public static void main(String[] args)
{new Menu1().init();}

public void init()
{
MenuBar menubar=new MenuBar();
Menu fileM=new Menu("文件");
Menu editM=new Menu("编辑");
Menu helpM=new Menu("帮助");

MenuItem openM=new MenuItem("打开");
MenuItem MI1=new MenuItem("新建");
MenuItem MI2=new MenuItem("打印");

FlowLayout fl=new FlowLayout();
Frame f=new Frame("TestMenuBar");
f.setLayout(fl);
menubar.add(fileM);
menubar.add(editM);
menubar.add(helpM);
fileM.add(openM);
fileM.add(MI1);
fileM.add(MI2);
f.setMenuBar(menubar);
f.setBounds(0,0,200,200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
   {e.getWindow().dispose();
        System.exit(0);}
}); openM.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{draw();}
});
}

public void draw()
{
try{
FileReader file1 = new FileReader("HubBount.txt");
BufferedReader buff = new BufferedReader(file1);
String strInput=buff.readLine();
buff.close();

String strPnt[] = strInput.split(" ");
int numPnt = strPnt.length;
Graphics g = getGraphics(); for(int i=0;i+1<numPnt;i++)
{
String SPnt1[]=strPnt[i].split(",");
String SPnt2[]=strPnt[i+1].split(",");
float Pnt1x=Float.parseFloat(SPnt1[0]);
float Pnt1y=Float.parseFloat(SPnt1[1]);
float Pnt2x=Float.parseFloat(SPnt2[0]);
float Pnt2y=Float.parseFloat(SPnt2[1]);
x1=(int)Pnt1x;
y1=(int)Pnt1y;
x2=(int)Pnt2x;
y2=(int)Pnt2y;
System.out.println(x1+" "+y1+" "+x2+" "+y2);
        g.drawLine(x1,y1,x2,y2);
}
}
catch(IOException e){
System.out.println("Error--"+ e.toString());}
}
}Javamenudrawline

解决方案 »

  1.   

    你的画图方法不对,下面是一个Swing常用画图的结构,把你需要画的内容放在paintComponent函数里就可以了。
    import javax.swing.*;
    import java.awt.*;class Hello extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2d = (Graphics2D) g;
            // 开启反锯齿功能,绘制出来的效果会更好,但需要消耗一点系统资源
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);        // 开始绘制,例如画一条线段
            g2d.drawLine(0, 0, getWidth(), getHeight());
        }    private static void createGuiAndShow() {
            JFrame frame = new JFrame("");        frame.getContentPane().add(new Hello());        // Set frame's close operation and location in the screen.
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 400);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
        
        public static void main(String[] args) {
            createGuiAndShow();
        }
    }