/**
* 有选择的画图板的实现,
*/
package 有选择的画图板;
import javax.swing.*;
import java.awt.*;
public class DrawUI extends JFrame {
public static void main(String[] args ) {
new DrawUI();
}
public DrawUI() {
this.setSize(500,600);
this.setLayout(null);
JButton bu1 = new JButton("画直线");
bu1.setBounds(50, 400, 100, 50);
this.add(bu1);
JButton bu2 = new JButton("画圆");
bu2.setBounds(350, 400,100 ,50 );
this.add(bu2);
/**
* 定义一个面板,并设置背景颜色,便于与窗体的区分
*/
JPanel jp = new JPanel();
jp.setBackground(Color.blue);
jp.setBounds(40, 40, 400, 300);
this.add(jp);
this.setDefaultCloseOperation(3);
this.setVisible(true);
/**
* 从窗体上获取画布对象,必须定义在setVisible()后面
*/
Graphics g = jp.getGraphics();
/**
* 创建监听器对象
*/
DrawListener dlis = new DrawListener(g);
//给面板加鼠标监听器
jp.addMouseListener(dlis);
//给按钮加动作监听器
bu1.addActionListener(dlis);
bu2.addActionListener(dlis);
}
}
/**
* 创建监听器
*/
package 有选择的画图板;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
/**
*
*DrawListener继承两个接口MouseListener, ActionListener
*抽象方法都要初始化
*/
public class DrawListener implements MouseListener, ActionListener {
private Graphics g;
/**
* 重载构造函数,并传参
* @param g
*/
public DrawListener(Graphics g){
this.g = g;
}
private String command;
private int x1,y1,x2,y2;
public void actionPerformed(ActionEvent e) {
command = e.getActionCommand(); //获取按下按钮得到的结果
//System.out.println(command);
}
public void mousePressed(MouseEvent e) {
x1 = e.getX();
y1 = e.getY();
}
/**
* 判断是画圆还是画直线
*/
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
if(command=="画直线")
{
g.drawLine(x1, y1, x2, y2);
}
else if(command=="画圆")
{
g.drawOval(x1, y1, x2, y2);
}
else {
}
}
/**
* 暂时用不到的抽象方法定义为空
*/
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
}
截图结果:
点击画直线:
点击画圆: