创建一个简单的绘图程序,可以绘制矩形,椭圆和直线。
1.先生成程序界面:
创一个添加显示图片按钮的方法:
1 privateJButton addButton(String str){2 ImageIcon icon = new ImageIcon(str);//按钮图标
3 JButton button = newJButton(icon);4 button.setContentAreaFilled(false);//按钮透明;
5 returnbutton;6 }
初始化界面:
1 public voidinit(){2 setLayout(new BorderLayout(5,1)); //设置布局;
3 JButton rectFilled = addButton("rectfilled.gif");4 rectFilled.setActionCommand("rectFilled");5 JButton rect = addButton("rect.gif");6 rect.setActionCommand("rect");7 JButton ovalFilled = addButton("ovalfilled.gif");8 ovalFilled.setActionCommand("ovalFilled");9 JButton oval = addButton("oval.gif");10 oval.setActionCommand("oval");11 JButton line = addButton("line.gif");12 line.setActionCommand("line");13 add(rectFilled, BorderLayout.WEST);14 add(rect, BorderLayout.WEST);15 add(ovalFilled, BorderLayout.WEST);16 add(oval, BorderLayout.WEST);17 add(line, BorderLayout.WEST);18 }
2.创建按钮事件
点击按钮分别执行的事件;为了点击按钮画出相应的图形,我设置了5个boolean变量;
private boolean isDrawRectFilled = false, isDrawRect = false, isDrawOvalFilled = false, isDrawOval = false, isDrawLine = false;
按钮事件代码:
1 public voidactionPerformed(ActionEvent e){2 String cmd =e.getActionCommand();3 if(cmd.equals("rectFilled")){4 isDrawRectFilled = true;5 isDrawRect = false;6 isDrawOval &#