How to add a paintComponent() to a JPanel

白昼怎懂夜的黑 提交于 2021-02-11 15:14:49

问题


I have 2 classes, Class2 and Class4. I wish to add the paint in Class2 from Class4 onto a JPanel in Class4 using the p4.add(c2o) and f.add(p4) methods. I have no problems adding GUI but I simply couldn't add graphics.

Class4:

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Class4 {


    public void mainMethod(int event){
        JFrame f = new JFrame("Love Test");
        if(event == 0){

            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(500,200);
            f.setLayout(null);

            JPanel p = new JPanel(new BorderLayout());
            p.setBounds(150, 0, 350, 75);
            Class3 c3o = new Class3();
            p.add(c3o);
            f.add(p);

            JPanel p2 = new JPanel();
            Class7 c7o = new Class7();
            p2.add(c7o);
            p2.setBounds(0, 75, 500, 40);
            f.add(p2);

            JPanel p3 = new JPanel();
            p3.setBounds(0, 0, 150, 75);
            Class5 c5o = new Class5();
            p3.add(c5o);
            f.add(p3);

            f.setVisible(true);

        }

        if(event == 5){

            JPanel p4 = new JPanel();
            Class2 c2o = new Class2();
            p4.add(c2o);
            p4.setBounds(0,115,500,55);
            f.add(p4);
        }

    }


}

Class2:

import javax.swing.JOptionPane;
import javax.swing.JPanel;

import java.util.Random;
import java.awt.*;



public class Class2 extends JPanel{

    public void paint(Graphics g){
        super.paint(g);
        this.setBackground(Color.WHITE);
        g.setColor(new Color(0,0,0));
        String str = "";
        String str2 = "";
        Random rlove = new Random();
        int love = rlove.nextInt(101);
        Class3 c3o = new Class3();
        str = c3o.boy.getText() + " and " + c3o.girl.getText() + "'s amount of love is " + love + "%.";
        if(love >= 0 && love < 10){         
            str2 = "Stop thinking about that person anymore!";
        }
        if(love >= 10 && love < 20){
            str2 = "1/100 percent chance...";
        }
        if(love >= 20 && love < 30){
            str2 = "Little hope...";
        }
        if(love >= 30 && love < 40){
            str2 = "Not even a kiss, stop talking about French kisses! (wise words of Rubesh)";
        }
        if(love >= 40 && love < 50){
            str2 = "Near passing";
        }
        if(love >= 50 && love < 60){
            str2 = "Just Pass";
        }
        if(love >= 60 && love < 70){
            str2 = "Some effort needed.";
        }
        if(love >= 70 && love < 80){
            str2 = "Grade A. A good chance.";
        }
        if(love >= 80 && love < 90){
            str2 = "Good pair. Very good relationship!";
        }
        if(love >= 90 && love < 100){
            str2 = "Perfect pair. Lost for words.";
        }
        if(love == 100){
            str2 = "OH MY GOD!!!!!";
        }
        g.drawString(str,10,10);
        g.drawString(str2,10,30);
    }


}

How do I add the paintComponent to JPanel p4? Thanks!


回答1:


  1. Don't use JPanel#paint, it is recommended that use JPanel#paintComponent, check out Performing Custom Painting
  2. Make use of appropriate layout managers. The problem you having comes from two issues. The first is, you panel has no preferred size. Override the getPreferredSize method of Class2 and return an appropriate size of the layout manager.

...

JPanel p4 = new JPanel(); // Default layout manager is FlowLayout
Class2 c2o = new Class2();
// c2o has not size (0x0 by default)...
p4.add(c2o);
p4.setBounds(0,115,500,55);
f.add(p4);



回答2:


There is no straight easy answer to this, but I'll try to explain.

What you need to do is setup a canvas, just like you would place a button or label, then you need to add a MouseListener to this. The MouseListener interface is used to track the mouse where you want to draw items. I've setup a full example, with color selection and shapeselection, because of the share amount of code, Im using pastebin to share this.

After this, I've explained key komponents to this. Take a look at: http://pastebin.com/YRr0LGPX

The key komponents here are the following.

The inner helper class "Board" is the canvas, this implements MouseListener and MouseMotionListener, this is done to track the mouse movements and key pressed.

private class Board extends JPanel implements 
    MouseListener, MouseMotionListener {

paintComponent(Graphics g) is the method that takes care of the painting, and Im using Graphics2D library to create the shapes.

mousePressed(MouseEvent e) recieves a starting coordinate of where the shape should be painted.

public void mousePressed(MouseEvent e) {
    startPoint = e.getPoint();
}

mouseReleased(MouseEvent e) is called when the keyclick ends, this method handles the drawing of the shape. I've used a switch case to handle the different shapes and then check the coordinates to handle the drawing of the shape. For more details on Shapes, http://docs.oracle.com/javase/7/docs/api/java/awt/Shape.html

When the mouse is released the following code is runned:

shapes.add(s); //Adds the new shape to the Vector of shapes
startPoint = null; //Resets the starting ...
endPoint = null; //and ending coordinates to the system
colorList.add(color); 
repaint(); //Repaints the entire canvas with the shapes in the Vector<Shape>

I dont only want to draw the shape when I release the mouse key, when the mouse is dragged I want to redraw the shape as I go, this is done in mouseDragged(MouseEvent e) method

DISCALIMER:

this was a test project I did back in the days, If I was to set up this now, I would do it a bit more DRY, but I hope this helps you to fix your problem.

If you need to draw "free-hand" with a pensil like functionallity, this dont really cover it, unless you can build on the logic. "Graphics" was a bit foggy.. :)

But here is some help presented by Prine Java making a 'dot/pixel' In swing/awt on how to create dots. I sugest create a 2D array, so you can add reverse options :)



来源:https://stackoverflow.com/questions/16496041/how-to-add-a-paintcomponent-to-a-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!