import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class DrawBoardFrame extends JFrame {
public static void main(String[] args) {
DrawBoardFrame dbf = new DrawBoardFrame();
dbf.initFrame();
}
public void initFrame() {
// 实现的逻辑
// 构造窗体对象
// 设置窗体默认关闭方式
this.setDefaultCloseOperation(3);
// 设置大小
this.setSize(600, 600);
// 设置标题
this.setTitle("画图板工具");
//设置窗体布局
this.setLayout(new FlowLayout());
//单选按钮
JRadioButton jrb = new JRadioButton();
jrb.setText("直线");
jrb.setActionCommand("line");
this.add(jrb);
JRadioButton jrb1 = new JRadioButton();
jrb1.setText("矩形");
jrb1.setActionCommand("rect");
this.add(jrb1);
JRadioButton jrb2 = new JRadioButton();
jrb2.setText("椭圆");
jrb2.setActionCommand("oval");
this.add(jrb2);
//按钮组类对象,实现单选
ButtonGroup bg = new ButtonGroup();
bg.add(jrb);
bg.add(jrb1);
bg.add(jrb2);
// 设置窗体可见
this.setVisible(true);
// 获取画笔
Graphics g = this.getGraphics();
// 给窗体添加鼠标监听器
DrawListener ml = new DrawListener(g,bg);
this.addMouseListener(ml);
}
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
public class DrawListener implements MouseListener {
public Graphics g1;
public ButtonGroup bg;
public int x1, y1, x2, y2;
public DrawListener(Graphics g,ButtonGroup bg) {
this.g = g;
this.bg = bg;
}
// 鼠标按下自动执行
public void mousePressed(MouseEvent e) {
// 保存当前按下点的坐标
x1 = e.getX();
y1 = e.getY();
}
// 鼠标释放自动执行
public void mouseReleased(MouseEvent e) {
// 保存当当前释放点的坐标
x2 = e.getX();
y2 = e.getY();
// 确定按钮组中,被选中的按钮对象是哪个?
// 获取按钮组中被选中的按钮对象
ButtonModel bm = bg.getSelection();
String command = bm.getActionCommand();
// 在按下点和释放点之间绘制图形
// TODO 获取画笔
if("line".equals(command)){
g.drawLine(x1, y1, x2, y2);
}else if("rect".equals(command)){
g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1),
Math.abs(y2 - y1));
}else if("oval".equals(command)){
g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1),
Math.abs(y2 - y1));
}
}
// 鼠标点击自动执行
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}