简体   繁体   中英

How can I add graphics in the JPanel in Java

I have the JPanel GuiMap and now I want to draw some different Graphics (at first some lines) in this Panel. At first I have the start point currentX=0 and currentY=0 . Then I put new Points in the method updatePos. This method changes the points. And the method paintComponent draw the line between the new and the old Points.

My problem is only the last line is visible.

How can I repaint or redraw or update the Panel right??

I want to see the old and the new Graphics!

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JPanel;

public class GuiMap extends JPanel{
    private int currentX = 0, currentY = 0;
    private int prevX, prevY;

    GuiMap(int xpos, int ypos){
        this.currentX = xpos;
        this.currentY = ypos;
    }   
    public void updatePoint(int xpos, int ypos) {
        prevX = currentX;
        prevY = currentY;
        currentX = xpos;
        currentY = ypos;
    }   
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                RenderingHints.VALUE_ANTIALIAS_ON); 
        g.drawLine(prevX, prevY, currentX, currentY);
    }
}
public class GuiMapFrame extends JFrame {   
    static GuiMap guiPanel;
    static JFrame frame;

    public static void main(String[] args) throws InterruptedException{
        frame = new JFrame("SuperGui"); 
        guiPanel = new GuiMap();            
        frame.setContentPane(guiPanel); 
        frame.setSize(600, 480);
        frame.setLocation(100,100);
        frame.setVisible(true);     
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guiPanel.updatePoint(20, 80);
        guiPanel.updatePoint(130, 50);
        guiPanel.updatePoint(60, 175);
        guiPanel.repaint();     
    }
}

Actually your problem is what camickr said it was. Every time you repaint it clears what it had drawn before. So you need to create multiple objects and render each one in the paint component

My problem is only the last line is visible.

You need to do one of two things:

  1. Draw each line to a BufferedImage and the paint the BufferedImage
  2. Keep a list of all the line you want to draw and then iterate through this list

See Custom Painting Approaches for a working example of both of these approaches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM