Java

基于java怎么实现画图板功能

小亿
90
2024-03-05 21:30:02
栏目: 编程语言

要实现画图板功能,可以使用Java的Swing库来创建一个简单的绘图应用。以下是一个基本的示例代码,用于实现画图板功能:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class DrawingBoard extends JFrame {

    private int startX, startY, endX, endY;
    private Color currentColor = Color.BLACK;

    public DrawingBoard() {
        setTitle("Drawing Board");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel controlPanel = new JPanel();
        JButton redButton = new JButton("Red");
        redButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentColor = Color.RED;
            }
        });

        JButton blackButton = new JButton("Black");
        blackButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentColor = Color.BLACK;
            }
        });

        controlPanel.add(redButton);
        controlPanel.add(blackButton);

        JPanel drawingPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(currentColor);
                g.drawLine(startX, startY, endX, endY);
            }
        };

        drawingPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                startX = e.getX();
                startY = e.getY();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                endX = e.getX();
                endY = e.getY();
                drawingPanel.repaint();
            }
        });

        getContentPane().add(controlPanel, BorderLayout.NORTH);
        getContentPane().add(drawingPanel, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                DrawingBoard drawingBoard = new DrawingBoard();
                drawingBoard.setVisible(true);
            }
        });
    }
}

此代码创建了一个简单的绘图板应用程序,用户可以在画板上绘制直线,并可以选择绘制的颜色。用户可以使用鼠标按下并拖动来绘制线条。您可以根据需要扩展此示例代码,以实现更复杂的绘图功能,如绘制不同形状、使用不同的画笔风格等。

0
看了该问题的人还看了