用java制作绘画应用程序的更简单方法?

用java制作绘画应用程序的更简单方法?,java,swing,jframe,paint,jcomponent,Java,Swing,Jframe,Paint,Jcomponent,所以基本上我有一些我几天前正在编写的代码,有点像画画,它允许你用鼠标在屏幕上画画。我偶然发现了这个属性,我意识到它的效率很低,我想知道是否有更实用的方法来实现这一点。没有任何理由给出我所有的代码,但这里是重要的部分 private static void createAndShowGui() { SimpleDraw mainPanel = new SimpleDraw(); MenuBar.createMenuBar(); JLabel label = new JLab

所以基本上我有一些我几天前正在编写的代码,有点像画画,它允许你用鼠标在屏幕上画画。我偶然发现了这个属性,我意识到它的效率很低,我想知道是否有更实用的方法来实现这一点。没有任何理由给出我所有的代码,但这里是重要的部分

private static void createAndShowGui() {
    SimpleDraw mainPanel = new SimpleDraw();
    MenuBar.createMenuBar();
    JLabel label = new JLabel();
    label.setText("Drawing prototype 0.0.1");
     // label.setHorizontalTextPosition(JLabel.NORTH);
    label.setFont(new Font("Serif", Font.BOLD, 20));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(mainPanel);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.PAGE_AXIS));
    frame.setVisible(true);
    frame.setJMenuBar(MenuBar.getMenuBar());
    frame.setBackground(Color.WHITE);
    frame.add(label);
上面的代码块设置jframe(窗口)

上面的代码几乎只设置MOUSE_X和MOUSE_Y变量以及repaint();方法


这是我偶然碰到的东西。当我发现这一点的时候,我想做的就是在你移动鼠标的时候,让一个正方形跟随你的光标。但是我忘了键入代码部分
paintComponent(g),它将这个程序变成我最初想要的东西。下面的部分基本上是我如何清理董事会。我100%确定这不是清除/重置这样的帧的正确方法,但我找不到其他方法。如果有人有任何技巧或更好的方法来正确地做到这一点,我将非常感激。谢谢D

您当前的方法基本上是通过不调用
super.paintComponent
来打破绘制链的要求。
paintComponent
方法执行一组操作,您不会接管这些操作,这可能会导致一些非常奇怪的绘制工件,这些工件很难一致地复制

Graphics
是一个共享资源,因此用于绘制其他控件的
Graphics
上下文将与用于绘制组件的上下文相同,除非您在手前“清理”上下文,否则先前绘制到上下文的内容将保留(这就是为什么您当前的代码“似乎”起作用)

相反,您应该使用
MouseListener
来定义一个锚定点,该锚定点表示鼠标被按下的点,然后使用
MouseMotionListener
来定义选择区域的范围,例如

为了强调如果继续违反
paintComponent
方法的要求,您将面临的问题,当我不调用
super.paintComponent

我只是简单地将两个
JButton
添加到
JFrame
(因此甚至不直接添加到面板)
paintComponent
执行一系列重要的工作,但您忽略了这些工作,这将导致更多的问题

自由格式行示例。。。 自由形式的线实际上是一种错觉,它是在一系列点之间绘制的一系列(小)线,其原因是
MouseListener
不会报告它移动的每个鼠标位置,根据鼠标移动的速度,您可能会收到很多回叫或一些回叫

因此,我们不只是绘制点,而是将点存储在
列表中
并在它们之间绘制线,例如

导入java.awt.AlphaComposite;
导入java.awt.Dimension;
导入java.awt.EventQueue;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.Point;
导入java.awt.Rectangle;
导入java.awt.event.MouseAdapter;
导入java.awt.event.MouseEvent;
导入java.util.ArrayList;
导入java.util.List;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.UIManager;
导入javax.swing.UnsupportedLookAndFeelException;
公共类自由格式线{
公共静态void main(字符串[]args){
新自由形式线();
}
公共自由格式线(){
invokeLater(新的Runnable(){
@凌驾
公开募捐{
试一试{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(ClassNotFoundException |实例化Exception | IllegalacessException |不支持ookandfeelException ex){
例如printStackTrace();
}
JFrame=新JFrame(“测试”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(newtestpane());
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
});
}
公共类TestPane扩展了JPanel{
私人名单点;
公共测试窗格(){
点=新阵列列表(25);
MouseAdapter ma=新的MouseAdapter(){
私有列表路径;
@凌驾
公共无效鼠标按下(MouseEvent e){
currentPath=新阵列列表(25);
添加(例如getPoint());
添加(当前路径);
}
@凌驾
公共无效鼠标标记(鼠标事件e){
点dragPoint=e.getPoint();
添加(拖动点);
重新油漆();
}
@凌驾
公共无效MouseEvent(MouseEvent e){
currentPath=null;
}
};
addMouseListener(硕士);
addMouseMotionListener(ma);
}
@凌驾
公共维度getPreferredSize(){
返回新维度(200200);
}
受保护组件(图形g){
超级组件(g);
Graphics2D g2d=(Graphics2D)g.create();
用于(列表路径:点){
起点=空;
对于(点p:路径){
if(from!=null){
g2d.绘制线(从.x开始,从.y开始,从.x开始,从.y开始);
}
from=p;
}
}
g2d.disp
 @Override
    public void mouseDragged(MouseEvent e)
    {
    // These console outputs are just so that I know what is happening
        System.out.println("Event: MOUSE_DRAG");
        System.out.println(e.getX());
        System.out.println(e.getY());
        System.out.println(e.getComponent());
        System.out.println(e.getWhen());
        System.out.println(e.getButton());
         MOUSE_X = e.getX() - 5;  //-5 so that the cursor represents the center of the square, not the top left corner.
         MOUSE_Y = e.getY() - 5;  //^
         rect = new Rectangle(MOUSE_X, MOUSE_Y, 10, 10 ); //This doesn't ever come into action.
         repaint();  

     }
@Override
    protected void paintComponent(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;
    if (rect != null) {

        if (!colorChoice.equals("Default"))
        {
            g2.setColor(Color.BLACK);
        }

        switch(colorChoice) {

        case "GRAY":
            g2.setColor(Color.GRAY);
            break;
        case "CYAN":
            g2.setColor(Color.CYAN);
            break;
        case "BLUE":
            g2.setColor(Color.BLUE);
            break;
        case "RED":
            g2.setColor(Color.RED);
            break;
        case "PINK":
            g2.setColor(Color.PINK);
            break;
        case "YELLOW":
            g2.setColor(Color.YELLOW);
            break;
        case "GREEN":
            g2.setColor(Color.GREEN);
            break;
        case "PURPLE":
            g2.setColor(Color.MAGENTA);
            break;
        case "RESET":
            g2.setColor(Color.WHITE);
        case "WHITE":
            g2.setColor(Color.WHITE);

        }





        g2.fillRect(MOUSE_X, MOUSE_Y, 15, 15); 

        if (colorChoice.equals("RESET")) 
        resetColorOnCursor(); 

        }
    }

    public static void clearBoard()
    {
    tempColor = colorChoice;
    setColorChoice("RESET");
    frame.repaint();




    }


    public static void resetColorOnCursor()
    {
    setColorChoice(tempColor);
    }
import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class SelectExample {

    public static void main(String[] args) {
        new SelectExample();
    }

    public SelectExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Rectangle selection;

        public TestPane() {
            MouseAdapter ma = new MouseAdapter() {

                private Point clickPoint;

                @Override
                public void mousePressed(MouseEvent e) {
                    clickPoint = e.getPoint();
                    selection = null;
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    Point dragPoint = e.getPoint();
                    int x = Math.min(clickPoint.x, dragPoint.x);
                    int y = Math.min(clickPoint.y, dragPoint.y);

                    int width = Math.max(clickPoint.x, dragPoint.x) - x;
                    int height = Math.max(clickPoint.y, dragPoint.y) - y;

                    if (selection == null) {
                        selection = new Rectangle(x, y, width, height);
                    } else {
                        selection.setBounds(x, y, width, height);
                    }
                    repaint();
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    selection = null;
                    repaint();
                }

            };

            addMouseListener(ma);
            addMouseMotionListener(ma);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (selection != null) {
                g.setColor(UIManager.getColor("List.selectionBackground"));
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
                g2d.fill(selection);
                g2d.dispose();
                g2d = (Graphics2D) g.create();
                g2d.draw(selection);
                g2d.dispose();
            }
        }

    }

}
import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class FreeFormLines {

    public static void main(String[] args) {
        new FreeFormLines();
    }

    public FreeFormLines() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private List<List<Point>> points;

        public TestPane() {
            points = new ArrayList<>(25);
            MouseAdapter ma = new MouseAdapter() {

                private List<Point> currentPath;

                @Override
                public void mousePressed(MouseEvent e) {
                    currentPath = new ArrayList<>(25);
                    currentPath.add(e.getPoint());

                    points.add(currentPath);
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    Point dragPoint = e.getPoint();
                    currentPath.add(dragPoint);
                    repaint();
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    currentPath = null;
                }

            };

            addMouseListener(ma);
            addMouseMotionListener(ma);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            for (List<Point> path : points) {
                Point from = null;
                for (Point p : path) {
                    if (from != null) {
                        g2d.drawLine(from.x, from.y, p.x, p.y);
                    }
                    from = p;
                }
            }
            g2d.dispose();
        }

    }

}
public class Main extends Application{
    @Override
    public void start(Stage stage){
        try{
            g = can.getGraphicsContext2D();
            g.setStroke(Color.BLACK);
            g.setLineWidth(1);
            c.setValue(Color.BLACK);
            c.setOnAction(e->{
                g.setStroke(c.getValue());
            });
            sli.setMin(1);
            sli.setMax(100);
            sli.setShowTickLabels(true);
            sli.setShowTickMarks(true);
            sli.valueProperty().addListener(e->{
                double val = sli.getValue();
                String str = String.format("%.1f",  val);
                lab.setText(str);
                g.setLineWidth(val);
            });
            gri.addRow(0,  c, sli, lab);
            gri.setHgap(20);
            gri.setAlignement(Pos.TOP_CENTER);
            gri.setPadding( new Insets( 20, 0, 0, 0));

            scene.setOnMousePressed(e->{.
               g.beginPath();
               g.lineTo(e.getSceneX(), e.getSceneY());
               g.stroke();
            });
            scene.setOnMoudrDragged(e->{. 
                g.lineTo(e.getSceneX(),  e.getSceneY());
                g.stroke();
            });
            pan.getChildren().addAll(can, gri);
            stage.setScene(scene);
            stage.show();
        }catch(Exception e){

            e.printStrackTrace();
        }

       Canvas can = new Canvas(760, 490);
       GraphicsContext  g ;
       ColorPicker  c =  new ColorPicker();
       Slider sli = new Slider();
       Label lab = new Label("1.0");
       GridPane gri = new GridPane();
       StackPane pan =  new StackPane();
       Scene  scene = new Scene(pan, 760, 490);
   public static void main (String [] args){
       launch(args);
   }
}
package drawingbymouse;

import java.awt.*;
import java.awt.event.*;

public class DrawingByMouse extends Frame 
                          implements MouseMotionListener{

    DrawingByMouse(){
        addMouseMotionListener(this);
        setSize(400, 400);
        setLayout(null);
        setVisible(true);
    }
    @Override
    public void mouseDragged(MouseEvent e){
        Graphics g = getGraphics();
        g.setColor(Color.BLACK);
        g.fillOval(e.getX(), e.getY(), 10, 10);
    }
    public void mouseMoved(MouseEvent e){
    }
    public static void main (String[]args){
        new DrawingByMouse();
    }
}