如何在JPanel中绘制? (Swing /图形Java)

问题描述 投票:48回答:4

我正在做一个项目,我正在尝试制作一个绘画程序。到目前为止,我已经使用Netbeans创建了一个GUI并设置了该程序。

到目前为止,我可以调用所有必要的协调来绘制内部,但我对如何在其中进行实际绘制非常困惑。

在我的代码结束时,我尝试在面板内绘图失败。

谁能解释/展示如何在这样的例子中使用图形?

我找到的所有示例都创建了一个类并使用JPanel扩展它,但我不知道是否可以执行此操作,因为它是在netbeans中生成的。

我需要在我的JPanel里面画一个JFrame。我不知道在哪里放图形类。

JavaPaintUI Class

package javapaint;

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

public class JavaPaintUI extends javax.swing.JFrame {

public JavaPaintUI() {
    initComponents();
}


private void initComponents() {


    jPanel2 = new javax.swing.JPanel();

    jPanel2.setBackground(new java.awt.Color(255, 255, 255));
    jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
    jPanel2.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jPanel2MousePressed(evt);
        }
        public void mouseReleased(java.awt.event.MouseEvent evt) {
            jPanel2MouseReleased(evt);
        }
    });
    jPanel2.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseDragged(java.awt.event.MouseEvent evt) {
            jPanel2MouseDragged(evt);
        }
    });
    pack();
}// </editor-fold>                        

int currentX, currentY, oldX, oldY;

private void jPanel2MouseDragged(java.awt.event.MouseEvent evt) {                                     
    if (tool == 1) {
        currentX = evt.getX();
        currentY = evt.getY();
        oldX = currentX;
        oldY = currentY;
        System.out.println(currentX + " " + currentY);
        System.out.println("PEN!!!!");
    }

}                                    

private void jPanel2MousePressed(java.awt.event.MouseEvent evt) {                                     
    oldX = evt.getX();
    oldY = evt.getY();
    System.out.println(oldX + " " + oldY);
}                                    


//mouse released//
private void jPanel2MouseReleased(java.awt.event.MouseEvent evt) {                                      
    if (tool == 2) {
        currentX = evt.getX();
        currentY = evt.getY();
        System.out.println("line!!!! from" + oldX + "to" + currentX);
    }
}                                     

//set ui visible//
public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new JavaPaintUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JPanel jPanel2;
// End of variables declaration                   

class jPanel2 extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.drawString("BLAH", 20, 20);
        g.drawRect(200, 200, 200, 200);
    }
}
}

Screen shot

整个事情是JFrame,中间的白色部分是jPanel2,这是我想要绘制的。

java swing jpanel draw paintcomponent
4个回答
36
投票

请注意额外的评论。

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

class JavaPaintUI extends JFrame {

    private int tool = 1;
    int currentX, currentY, oldX, oldY;

    public JavaPaintUI() {
        initComponents();
    }

    private void initComponents() {
        // we want a custom Panel2, not a generic JPanel!
        jPanel2 = new Panel2();

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        jPanel2.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent evt) {
                jPanel2MousePressed(evt);
            }
            public void mouseReleased(MouseEvent evt) {
                jPanel2MouseReleased(evt);
            }
        });
        jPanel2.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent evt) {
                jPanel2MouseDragged(evt);
            }
        });

        // add the component to the frame to see it!
        this.setContentPane(jPanel2);
        // be nice to testers..
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
    }// </editor-fold>

    private void jPanel2MouseDragged(MouseEvent evt) {
        if (tool == 1) {
            currentX = evt.getX();
            currentY = evt.getY();
            oldX = currentX;
            oldY = currentY;
            System.out.println(currentX + " " + currentY);
            System.out.println("PEN!!!!");
        }
    }

    private void jPanel2MousePressed(MouseEvent evt) {
        oldX = evt.getX();
        oldY = evt.getY();
        System.out.println(oldX + " " + oldY);
    }


    //mouse released//
    private void jPanel2MouseReleased(MouseEvent evt) {
        if (tool == 2) {
            currentX = evt.getX();
            currentY = evt.getY();
            System.out.println("line!!!! from" + oldX + "to" + currentX);
        }
    }

    //set ui visible//
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JavaPaintUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private JPanel jPanel2;
    // End of variables declaration

    // This class name is very confusing, since it is also used as the
    // name of an attribute!
    //class jPanel2 extends JPanel {
    class Panel2 extends JPanel {

        Panel2() {
            // set a preferred size for the custom panel.
            setPreferredSize(new Dimension(420,420));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            g.drawString("BLAH", 20, 20);
            g.drawRect(200, 200, 200, 200);
        }
    }
}

屏幕截图

其他示例 - 更适合多线和多线段

HFOE作为该线程的第一条评论提供了一个很好的链接。 Camickr还描述了在BufferedImage文章中主动绘画与绘画到Custom Painting Approaches

另见使用painting in a BufferedImage的这种方法。


14
投票

使用图形用户界面时,您需要记住窗格上的绘图是在Java AWT/Swing event queue中完成的。你不能只使用Graphics / paint() / etc之外的paintComponent()对象。方法。

但是,您可以使用一种名为“Frame buffering”的技术。基本上,你需要有一个BufferedImage并直接在它上面绘制(参见它的createGraphics()方法;你可以在同一个BufferedImage实例上保留和重用多个操作的图形上下文,不需要一直重新创建它,只有在创建一个新的时候实例)。然后,在你的JPanelpaintComponent()中,你只需要将BufferedImage实例绘制到JPanel。使用此技术,您可以通过affine transformations轻松执行缩放,平移和旋转操作。


11
投票

这是一个简单的例子。我想这很容易理解:

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Graph extends JFrame {
JFrame f = new JFrame();
JPanel jp;


public Graph() {
    f.setTitle("Simple Drawing");
    f.setSize(300, 300);
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);

    jp = new GPanel();
    f.add(jp);
    f.setVisible(true);
}

public static void main(String[] args) {
    Graph g1 = new Graph();
    g1.setVisible(true);
}

class GPanel extends JPanel {
    public GPanel() {
        f.setPreferredSize(new Dimension(300, 300));
    }

    @Override
    public void paintComponent(Graphics g) {
        //rectangle originates at 10,10 and ends at 240,240
        g.drawRect(10, 10, 240, 240);
        //filled Rectangle with rounded corners.    
        g.fillRoundRect(50, 50, 100, 100, 80, 80);
    }
}

}

输出看起来像这样:


0
投票

Java 8接受的Bijaya Bidari代码的变化,没有关于构造函数中的可覆盖方法调用的警告:

public class Graph extends JFrame {
    JPanel jp;

    public Graph() {
        super("Simple Drawing");
        super.setSize(300, 300);
        super.setDefaultCloseOperation(EXIT_ON_CLOSE);

        jp = new GPanel();
        super.add(jp);
    }

    public static void main(String[] args) {
        Graph g1 = new Graph();
        g1.setVisible(true);
    }

    class GPanel extends JPanel {
        public GPanel() {
            super.setPreferredSize(new Dimension(300, 300));
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            //rectangle originated at 10,10 and end at 240,240
            g.drawRect(10, 10, 240, 240);
                    //filled Rectangle with rounded corners.    
            g.fillRoundRect(50, 50, 100, 100, 80, 80);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.