创建画图板窗口

:lol: //创建一个画图板窗体

//引入类和接口
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JColorChooser;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;


public class MyJFrame extends javax.swing.JFrame {
//写出主函数
private String command="line";
private Color color=Color.black;
java.awt.Graphics g;
public static void main(String[] args){
// 创建窗口对象
MyJFrame frame=new MyJFrame();
//调用方法
frame.showUI();
}
//编写showUI方法
public void showUI(){
//设置窗口的大小,标题,关闭按钮,居中,可视性
this.setTitle("简单模仿画图板");
this.setSize(400, 400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(3);
//设置流式布局
FlowLayout layout=new FlowLayout();
this.setLayout(layout);
//添加按钮
javax.swing.JButton line_button=new javax.swing.JButton("直线");
line_button.setActionCommand("line");
this.add(line_button);
javax.swing.JButton rect_button=new javax.swing.JButton("矩形");
rect_button.setActionCommand("rect");
this.add(rect_button);
javax.swing.JButton oval_button=new javax.swing.JButton("椭圆");
oval_button.setActionCommand("oval");
this.add(oval_button);
javax.swing.JButton color_button=new javax.swing.JButton("颜色");
this.add(color_button);
//添加形状按钮监听器,这里用到了匿名内部类的方法
//匿名内部类是指在另一类里面定义一个类,用于那些简短的类的命
名和调用
ActionListener action_listener=new ActionListener(){
//添加方法
public void actionPerformed(ActionEvent e){
command=e.getActionCommand();
}
};
//将监听器安装到按钮上
line_button.addActionListener(action_listener);
rect_button.addActionListener(action_listener);
oval_button.addActionListener(action_listener);
//添加颜色按钮监听器
ActionListener action_listen=new ActionListener(){
public void actionPerformed(ActionEvent e){
color=JColorChooser.showDialog(null,"请选择颜色",Color.black);
}
};
//添加按钮
color_button.addActionListener(action_listen);
this.setVisible(true);
//获取画布
g=this.getGraphics();
//准备画图要创建一个鼠标监听器
MouseListener mouse_listener=new MouseListener(){
int x1,y1,y2,x2;
public void mouseClicked(MouseEvent e){

}
public void mouseEntered(MouseEvent e){

}
public void mouseExited(MouseEvent e){

}
public void mousePressed(MouseEvent e){
x1=e.getX();
y1=e.getY();

}
public void mouseReleased(MouseEvent e){
x2=e.getX();
y2=e.getY();
g.setColor(color);
//通过判断来决定画什么
if(command.equals("line")){
g.drawLine(x1, y1, x2, y2);
}
else if(command.equals("rect")){
g.drawRect(Math.min(x1, x2),Math.min( y1,y2),Math.abs(x1-x2),Math.abs(y1-y2));
}
else if(command.equals("oval")){
g.drawOval(Math.min(x1,x2),Math.min(y1, y2),Math.abs( x2-x1),Math.abs(y2-y1));
}
}
};
this.addMouseListener(mouse_listener);
}

}
以上是我敲过的代码,运行后会显示四个按钮,你可以画三种形状,可以改变他们的颜色。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值