21xrx.com
2024-09-20 01:08:26 Friday
登录
文章检索 我的文章 写文章
Java画图程序源代码分享
2023-06-17 09:18:38 深夜i     --     --
Java 画图程序 源代码

Java是一种跨平台的编程语言,具有良好的可移植性和跨平台性,同时也是许多开发者喜欢的编程语言。Java中的绘图功能也十分强大,用Java编写的画图程序可以满足日常的绘图需求。本文将分享Java画图程序的源代码,帮助想要学习Java绘图的读者快速入门。

下面是一个简单的Java画图板完整代码示例:


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class SimpleDraw extends JFrame implements ActionListener, MouseListener, MouseMotionListener {

  private static final long serialVersionUID = 1L;

  JButton clearButton, quitButton;

  JPanel buttonPanel, drawPanel;

  Point[] points = new Point[10000];

  int pointIndex = 0;

  

  public static void main(String[] args)

  {

    SimpleDraw frame = new SimpleDraw();

    frame.setVisible(true);

  }

  public SimpleDraw()

  {

    setTitle("Simple Draw");

    setSize(640, 480);

    

    buttonPanel = new JPanel();

    clearButton = new JButton("Clear");

    clearButton.addActionListener(this);

    buttonPanel.add(clearButton);

    quitButton = new JButton("Quit");

    quitButton.addActionListener(this);

    buttonPanel.add(quitButton);

    add(buttonPanel, BorderLayout.NORTH);

    

    drawPanel = new JPanel();

    drawPanel.setBackground(Color.WHITE);

    drawPanel.addMouseListener(this);

    drawPanel.addMouseMotionListener(this);

    add(drawPanel, BorderLayout.CENTER);

  }

  public void paint(Graphics g)

  {

    super.paint(g);

    for (int i = 1; i < pointIndex; i++)

      g.drawLine(points[i - 1].x, points[i - 1].y, points[i].x, points[i].y);

  }

  public void actionPerformed(ActionEvent e)

  {

    if (e.getSource() == clearButton)

    {

      pointIndex = 0;

      drawPanel.repaint();

    }

    else if (e.getSource() == quitButton)

    {

      System.exit(0);

    }

  }

  public void mousePressed(MouseEvent e)

  {

    drawPanel.getGraphics().drawOval(e.getX(), e.getY(), 1, 1);

    points[pointIndex] = new Point(e.getX(), e.getY());

    pointIndex++;

  }

  public void mouseDragged(MouseEvent e)

  {

    drawPanel.repaint();

    drawPanel.getGraphics().drawOval(e.getX(), e.getY(), 1, 1);

    points[pointIndex] = new Point(e.getX(), e.getY());

    pointIndex++;

  }

  public void mouseClicked(MouseEvent arg0) {}

  public void mouseEntered(MouseEvent arg0) {}

  public void mouseExited(MouseEvent arg0) {}

  public void mouseMoved(MouseEvent arg0) {}

  public void mouseReleased(MouseEvent arg0) {}

}

上述代码实现了一个可以绘制圆形线条的简单画图板。代码中包含了绘图的基本操作,例如初始化画板、绘制图形、清空画板等。读者可以通过学习代码,深入了解Java绘图的原理和实现方法,从而快速入门Java绘图。

总结一下,Java绘图可以满足日常的绘图需求,同时也是学习Java编程的一种好方式。本文分享了一个简单的Java画图板完整代码,帮助读者快速入门Java绘图,希望对大家有所帮助。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复