在Windows操作系统中有一个“画图”程序,可以用来绘制各种各样的图形。请编写一个程序,实现该软件的基本功能。

题目:在Windows操作系统中有一个“画图”程序,可以用来绘制各种各样的图形。请编写一个程序,实现该软件的基本功能,只要实现画直线、椭圆和矩形这3个功能即可。

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class PaintDemo extends JFrame{
    
    public static void main(String args[]){
        PaintDemo demo = new PaintDemo();
        demo.go();
    }
    
    public void go(){
        this.setTitle("画图");
        this.setSize(600,500);
        this.setLayout(new FlowLayout());
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
        //按钮组
        ButtonGroup group = new ButtonGroup();
        //单选按钮  
        JRadioButton line = new JRadioButton("直线");
        //设置按钮的动作命令  
        line.setActionCommand("line");
        //默认选中直线  
        line.setSelected(true);
        JRadioButton rect = new JRadioButton("矩形");
        rect.setActionCommand("rect");
        JRadioButton oval = new JRadioButton("椭圆");
        oval.setActionCommand("oval");
        group.add(line);
        group.add(rect);
        group.add(oval);
        this.add(line);
        this.add(rect);
        this.add(oval);
        Graphics g = this.getGraphics();
        MyListener listener = new MyListener(g,group);
        this.addMouseListener(listener);
    }
}

class MyListener implements MouseListener {
    int startX, startY, endX, endY;
    Graphics g;
    ButtonGroup group;
    
    public MyListener(Graphics g,ButtonGroup group) {
        this.g = g;
        this.group = group;
    }
    
    // 按下  
    public void mousePressed(MouseEvent e) {
        startX = e.getX();
        startY = e.getY();
    }
    
    // 释放  
    public void mouseReleased(MouseEvent e) {
        endX = e.getX();
        endY = e.getY();
        String str = group.getSelection().getActionCommand();
        if ("line".equals(str)) {
            g.drawLine(startX, startY, endX, endY);
        } else if (str.equals("rect")) {
            g.drawRect(startX, startY, endX - startX, endY - startY);
        } else{
            g.drawOval(startX, startY, endX - startX, endY - startY);
        }
    }
    
    // 进入  
    public void mouseEntered(MouseEvent e) {
    }
    
    // 离开  
    public void mouseExited(MouseEvent e) {
    }
    
    // 点击  
    public void mouseClicked(MouseEvent e) {
    }
}  

运行效果:

在Windows操作系统中有一个“画图”程序,可以用来绘制各种各样的图形。请编写一个程序,实现该软件的基本功能。_第1张图片

你可能感兴趣的:(Java)