我做的是一个简单的画板程序,我的预期效果应该是点击MenuItem后会在Canvas上显示相应的图形,可我编的过程中发现点击MenuItem后Canvas上没有显示,必须把窗口最小化然后恢复后才能显示出来,各位这是为什么啊?我的部分代码如下:
import java.awt.*;
import java.awt.event.*;
public class CanvasTest extends Canvas
{
static int x1,y1,x2,y2;
static Frame f;
static Choice ch;
static MenuBar mb;
static Menu m;
static MenuItem line;
static Boolean draw=false;
public static void main(String arg[])
{
MouseAction ma=new MouseAction();
ch=new Choice();
CanvasTest d=new CanvasTest();
f=new Frame("MyCanvas");
line=new MenuItem("Line");
mb=new MenuBar();
m=new Menu("Tools");
line.setActionCommand("line");
line.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String cmd;
cmd=e.getActionCommand();
if(cmd=="line")
draw=true;
}
});
d.addMouseListener(ma);
d.addMouseMotionListener(ma);
d.setSize(200,200);
m.add(line);
mb.add(m);
f.setMenuBar(mb);
f.add(d,BorderLayout.SOUTH);
f.add(ch,BorderLayout.NORTH);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.pack();
f.setVisible(true);
}
public void paint(Graphics g)
{
if(draw==true)
g.drawLine(x1,y1,x2,y2);
}
static class MouseAction extends MouseAdapter implements MouseMotionListener
{
public void mousePressed(MouseEvent e)
{
x1=e.getX();
y1=e.getY();
}
public void mouseDragged(MouseEvent e)
{
x2=e.getX();
y2=e.getY();
}
public void mouseMoved(MouseEvent e){}
}
}