画图板的简单实现


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) {
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值