Java画图(直线,矩形,椭圆),并显示其周长面积

Shape类 父类

package com.lovoinfo.shape;

import java.awt.Color;
import java.awt.Graphics;
/**
 * 图形(抽象类,不能实例化)
 * @author Administrator
 *
 */
public abstract class Shape {
    protected int startX,startY;//起点横纵坐标
    protected int endX,endY;//终点横纵坐标

    protected Color color;

    public void setColor(Color color) {
        this.color = color;
    }

    /**
     * 绘图(抽象方法留给子类重写)
     * @param g 画笔
     */
    public abstract void draw(Graphics g);

    public abstract void calculate(Graphics g);

    public int getStartX() {
        return startX;
    }
    public void setStartX(int startX) {
        this.startX = startX;
    }
    public int getStartY() {
        return startY;
    }
    public void setStartY(int startY) {
        this.startY = startY;
    }
    public int getEndX() {
        return endX;
    }
    public void setEndX(int endX) {
        this.endX = endX;
    }
    public int getEndY() {
        return endY;
    }
    public void setEndY(int endY) {
        this.endY = endY;
    }

}

定义子类
Rectangle
Oval
Line

package com.lovoinfo.shape;

import java.awt.Graphics;

public class Rectangle extends Shape {
    private int width;
    private int height;
    private String s;
    @Override
    public void draw(Graphics g) {
        g.setColor(color);
        width= Math.abs(endX-startX);
        height=Math.abs(endY-startY);

        int x1=startX<endX?startX:endX;
        int y1=startY<endY?startY:endY;

        g.drawRect(x1, y1, width, height);

    }

    @Override
    public void calculate(Graphics g) {
        s="此图为矩形"+"矩形周长为:"+2*(width+height)+"面积为:"+width*height;

        g.drawString(s, 100,100 );

    }

}
package com.lovoinfo.shape;

import java.awt.Graphics;

public class Oval extends Shape{
    private static final double PI = 3.14;
    private String s;
    private int width;
    private int height;
    @Override
    public void draw(Graphics g) {

        g.setColor(color);

        width= Math.abs(endX-startX);
        height=Math.abs(endY-startY);

        int x1=startX<endX?startX:endX;
        int y1=startY<endY?startY:endY;

        g.drawOval(x1, y1, width, height);
    }

    @Override
    public void calculate(Graphics g) {
        double a=width/2;
        double b=height/2;
        s="此图为椭圆:"+"面积为:"+PI *a*b+"周长为:"+2*PI*b+4*(Math.abs(a-b));
        g.drawString(s, 100, 100);

    }


}
package com.lovoinfo.shape;

import java.awt.Graphics;

public class Line extends Shape {
    private String s;
    @Override
    public void draw(Graphics g) {
        g.setColor(color);
        g.drawLine(startX,startY, endX, endY);

    }

    @Override
    public void calculate(Graphics g) {
        s="此图为直线"+"长度为:"+Math.sqrt((startX-endX)*(startX-endX)+
                (startY-endY)*(startY-endY));
        g.drawString(s, 100, 100);

    }

}

工具类
产生直线椭圆矩形坐标随机数

package com.lovoinfo.util;

import java.awt.Color;
/**
 * 工具类:第一:加上final,让这个类不能被继承
 *      第二:构造器私有,让别人只能以对象加点调用方法
 * @author Administrator
 *
 */
public final class MyUtil {
    private MyUtil(){

    }

    /**
     * 产生指定范围的随机整数
     * @param min 最小值(闭区间)
     * @param max 最大值(闭区间)
     * @return 指定范围的随机整数
     */
    public static int random(int min,int max){

        return (int) (Math.random()*(max-min+1)+min);
    }

    public static Color randomColor(){
        int r=random(0,255);
        int g=random(0,255);
        int b=random(0,255);
        return new Color(r,g,b);
    }

}

UI

package com.lovoinfo.ui;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;





import com.lovoinfo.shape.Line;
import com.lovoinfo.shape.Oval;
import com.lovoinfo.shape.Rectangle;
import com.lovoinfo.shape.Shape;
import com.lovoinfo.util.MyUtil;

@SuppressWarnings("serial")
public class MyFrame extends JFrame {

    private class ButtonHandler implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            String command=e.getActionCommand();
            if(command.equals("Line")){
                shape=new Line();
            }else if(command.equals("Oval")){
                shape=new Oval();
            }else{
                shape=new Rectangle();
            }
            shape.setStartX(MyUtil.random(0, 1000));
            shape.setStartY(MyUtil.random(0, 600));
            shape.setEndX(MyUtil.random(0, 1000));
            shape.setEndY(MyUtil.random(0, 600));
           // shape.setColor(MyUtil.randomColor());
            shape.setColor(Color.black);
            repaint();
        }

    }

    private JButton lineButton;
    private JButton ovalButton;
    private JButton recButton;


//  private Line line = null;
//  private Rectangle rec = null;
//  private Oval oval = null;
    private Shape shape=null;
    public MyFrame() {
        this.setSize(1000, 600);
        this.setTitle("绘图窗口");
        // super.setTitle("我的第一个窗口");
        this.setResizable(false);
        this.setLocationRelativeTo(null);// 窗口居中
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);// 设置默认的关闭操作

        lineButton = new JButton("Line");
        ovalButton = new JButton("Oval");
        recButton = new JButton("Rectangle");
//      recButton.addActionListener(new ActionListener() {
//
//          @Override
//          public void actionPerformed(ActionEvent e) {
//              rec = new Rectangle();
//              rec.setStartX(MyUtil.random(0, 1000));
//              rec.setStartY(MyUtil.random(0, 600));
//              rec.setEndX(MyUtil.random(0, 1000));
//              rec.setEndY(MyUtil.random(0, 600));
//              repaint();
//
//          }
//      });

//      ovalButton.addActionListener(new ActionListener() {
//
//          @Override
//          public void actionPerformed(ActionEvent e) {
//              oval = new Oval();
//              oval.setStartX(MyUtil.random(0, 1000));
//              oval.setStartY(MyUtil.random(0, 600));
//              oval.setEndX(MyUtil.random(0, 1000));
//              oval.setEndY(MyUtil.random(0, 600));
//              repaint();
//
//          }
//      });
//      lineButton.addActionListener(new ActionListener() {
//          /**
//           * 点击按钮后要执行的方法
//           */
//          @Override
//          public void actionPerformed(ActionEvent e) {
//
//              line = new Line();
//              line.setStartX(MyUtil.random(0, 1000));
//              line.setStartY(MyUtil.random(0, 600));
//              line.setEndX(MyUtil.random(0, 1000));
//              line.setEndY(MyUtil.random(0, 600));
//
//              repaint();
//          }
//      });// 需要放一个Action监听器
        ActionListener handler=new ButtonHandler();
        lineButton.addActionListener(handler);
        ovalButton.addActionListener(handler);
        recButton.addActionListener(handler);
        this.setLayout(new FlowLayout());// 设置流式布局管理器
        this.add(lineButton);
        this.add(ovalButton);
        this.add(recButton);

    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if(shape!=null){
        shape.draw(g);
        shape.calculate(g);
        }
//      if (line != null) {
//          line.draw(g);
//      }
//      if (rec != null) {
//          rec.draw(g);
//      }
//      if (oval != null) {
//          oval.draw(g);
//      }

    }
}

测试类

package com.lovoinfo.ui;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;





import com.lovoinfo.shape.Line;
import com.lovoinfo.shape.Oval;
import com.lovoinfo.shape.Rectangle;
import com.lovoinfo.shape.Shape;
import com.lovoinfo.util.MyUtil;

@SuppressWarnings("serial")
public class MyFrame extends JFrame {

    private class ButtonHandler implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            String command=e.getActionCommand();
            if(command.equals("Line")){
                shape=new Line();
            }else if(command.equals("Oval")){
                shape=new Oval();
            }else{
                shape=new Rectangle();
            }
            shape.setStartX(MyUtil.random(0, 1000));
            shape.setStartY(MyUtil.random(0, 600));
            shape.setEndX(MyUtil.random(0, 1000));
            shape.setEndY(MyUtil.random(0, 600));
           // shape.setColor(MyUtil.randomColor());
            shape.setColor(Color.black);
            repaint();
        }

    }

    private JButton lineButton;
    private JButton ovalButton;
    private JButton recButton;


//  private Line line = null;
//  private Rectangle rec = null;
//  private Oval oval = null;
    private Shape shape=null;
    public MyFrame() {
        this.setSize(1000, 600);
        this.setTitle("绘图窗口");
        // super.setTitle("我的第一个窗口");
        this.setResizable(false);
        this.setLocationRelativeTo(null);// 窗口居中
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);// 设置默认的关闭操作

        lineButton = new JButton("Line");
        ovalButton = new JButton("Oval");
        recButton = new JButton("Rectangle");
//      recButton.addActionListener(new ActionListener() {
//
//          @Override
//          public void actionPerformed(ActionEvent e) {
//              rec = new Rectangle();
//              rec.setStartX(MyUtil.random(0, 1000));
//              rec.setStartY(MyUtil.random(0, 600));
//              rec.setEndX(MyUtil.random(0, 1000));
//              rec.setEndY(MyUtil.random(0, 600));
//              repaint();
//
//          }
//      });

//      ovalButton.addActionListener(new ActionListener() {
//
//          @Override
//          public void actionPerformed(ActionEvent e) {
//              oval = new Oval();
//              oval.setStartX(MyUtil.random(0, 1000));
//              oval.setStartY(MyUtil.random(0, 600));
//              oval.setEndX(MyUtil.random(0, 1000));
//              oval.setEndY(MyUtil.random(0, 600));
//              repaint();
//
//          }
//      });
//      lineButton.addActionListener(new ActionListener() {
//          /**
//           * 点击按钮后要执行的方法
//           */
//          @Override
//          public void actionPerformed(ActionEvent e) {
//
//              line = new Line();
//              line.setStartX(MyUtil.random(0, 1000));
//              line.setStartY(MyUtil.random(0, 600));
//              line.setEndX(MyUtil.random(0, 1000));
//              line.setEndY(MyUtil.random(0, 600));
//
//              repaint();
//          }
//      });// 需要放一个Action监听器
        ActionListener handler=new ButtonHandler();
        lineButton.addActionListener(handler);
        ovalButton.addActionListener(handler);
        recButton.addActionListener(handler);
        this.setLayout(new FlowLayout());// 设置流式布局管理器
        this.add(lineButton);
        this.add(ovalButton);
        this.add(recButton);

    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if(shape!=null){
        shape.draw(g);
        shape.calculate(g);
        }
//      if (line != null) {
//          line.draw(g);
//      }
//      if (rec != null) {
//          rec.draw(g);
//      }
//      if (oval != null) {
//          oval.draw(g);
//      }

    }
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的Java画图程序,包含七种颜色,可以绘制矩形直线椭圆。 ```java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SimplePaint extends JFrame implements ActionListener, MouseListener, MouseMotionListener { private int startX, startY, endX, endY; private int currentShape; private int currentColor; private JButton[] colorButtons; private JButton[] shapeButtons; private JPanel colorPanel; private JPanel shapePanel; private JPanel controlPanel; private DrawingArea drawingArea; public SimplePaint() { setTitle("Simple Paint"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(600, 400); // 初始化画布和颜色、形状按钮 drawingArea = new DrawingArea(); colorButtons = new JButton[7]; colorButtons[0] = new JButton("Black"); colorButtons[1] = new JButton("Red"); colorButtons[2] = new JButton("Orange"); colorButtons[3] = new JButton("Yellow"); colorButtons[4] = new JButton("Green"); colorButtons[5] = new JButton("Blue"); colorButtons[6] = new JButton("Purple"); for (int i = 0; i < colorButtons.length; i++) { colorButtons[i].addActionListener(this); } shapeButtons = new JButton[3]; shapeButtons[0] = new JButton("Rectangle"); shapeButtons[1] = new JButton("Line"); shapeButtons[2] = new JButton("Oval"); for (int i = 0; i < shapeButtons.length; i++) { shapeButtons[i].addActionListener(this); } // 设置颜色、形状按钮面板 colorPanel = new JPanel(); colorPanel.setLayout(new GridLayout(1, colorButtons.length)); for (int i = 0; i < colorButtons.length; i++) { colorPanel.add(colorButtons[i]); } shapePanel = new JPanel(); shapePanel.setLayout(new GridLayout(1, shapeButtons.length)); for (int i = 0; i < shapeButtons.length; i++) { shapePanel.add(shapeButtons[i]); } // 设置控制面板 controlPanel = new JPanel(); controlPanel.setLayout(new BorderLayout()); controlPanel.add(colorPanel, BorderLayout.NORTH); controlPanel.add(shapePanel, BorderLayout.SOUTH); // 添加组件 add(drawingArea, BorderLayout.CENTER); add(controlPanel, BorderLayout.NORTH); // 添加鼠标事件监听器 drawingArea.addMouseListener(this); drawingArea.addMouseMotionListener(this); } public void actionPerformed(ActionEvent e) { // 处理颜色按钮事件 for (int i = 0; i < colorButtons.length; i++) { if (e.getSource() == colorButtons[i]) { currentColor = i; return; } } // 处理形状按钮事件 for (int i = 0; i < shapeButtons.length; i++) { if (e.getSource() == shapeButtons[i]) { currentShape = i; return; } } } public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { startX = e.getX(); startY = e.getY(); } public void mouseReleased(MouseEvent e) { endX = e.getX(); endY = e.getY(); // 绘制形状 Graphics g = drawingArea.getGraphics(); g.setColor(getColor(currentColor)); switch (currentShape) { case 0: // 矩形 g.drawRect(Math.min(startX, endX), Math.min(startY, endY), Math.abs(endX - startX), Math.abs(endY - startY)); break; case 1: // 直线 g.drawLine(startX, startY, endX, endY); break; case 2: // 椭圆 g.drawOval(Math.min(startX, endX), Math.min(startY, endY), Math.abs(endX - startX), Math.abs(endY - startY)); break; } g.dispose(); } public void mouseDragged(MouseEvent e) {} public void mouseMoved(MouseEvent e) {} private Color getColor(int index) { switch (index) { case 0: // 黑色 return Color.BLACK; case 1: // 红色 return Color.RED; case 2: // 橙色 return Color.ORANGE; case 3: // 黄色 return Color.YELLOW; case 4: // 绿色 return Color.GREEN; case 5: // 蓝色 return Color.BLUE; case 6: // 紫色 return new Color(128, 0, 128); default: return Color.BLACK; } } public static void main(String[] args) { SimplePaint paint = new SimplePaint(); paint.setVisible(true); } // 画布面板 class DrawingArea extends JPanel { public DrawingArea() { setPreferredSize(new Dimension(400, 300)); setBackground(Color.WHITE); } } } ``` 这个程序使用了Java的Swing图形库,创建了一个窗口,在窗口中添加了一个画布和颜色、形状按钮。通过鼠标事件监听器实现了绘制矩形直线椭圆的功能,通过颜色按钮实现了七种颜色的选择。您可以根据需要对程序进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值