首页 > 解决方案 > JPanel Graphics 不绘制任何东西(Java)

问题描述

我无法让我的 JPanel 的图形正常工作。它拒绝绘制任何东西,无论我尝试过什么以及我在互联网上能找到什么。

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.*;
import java.io.*;
public class Mandelbrot{
    public static void main(String[] args){
        JFrame win=new JFrame();
        JPanel dis=new JPanel();
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        win.setResizable(false);
        win.setVisible(true);
        win.add(dis);
        dis.setPreferredSize(new Dimension(1000,500));
        win.pack();
        Graphics g=dis.getGraphics();
        g.setColor(Color.red);
        g.fillRect(0, 0, 100, 100);
    }
}

标签: javaswingjpanel

解决方案


Posting as an answer because I ran out of comment room:

Note: If you need to be constantly changing things, then a JPanel is probably not your best option. I recommend you rethink what you are trying to do because you should probably use a Canvas or paint to a bunch of different labels/glass panes and overlay them however you want, this will allow you to have moving components/animations in a foreground item, and make different changes to the background item.

Alternatively, you can make the JPanel draw a buffered image, or you can store a list of items to paint, and you can paint them each time. For the buffered image method you can directly edit and draw to the buffered image every time you need to make a change.


Below is an example of how to use the buffered image method.

First create a custom JPanel in a new class:

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class DrawPanel extends JPanel{

    public BufferedImage canvas = new BufferedImage(panelWidth, panelHeight, BufferedImage.TYPE_INT_ARGB);

    @Override
    public void paintComponent(Graphics g){
        //Draw the canvas
        g.drawImage(canvas, 0, 0, this);
    }
}

Now in your main method you can replace JPanel dis=new JPanel() with this:

DrawPanel dis = new DrawPanel();

Graphics g=dis.canvas.getGraphics();
g.setColor(Color.red);
g.fillRect(0, 0, 100, 100);

Note how I use dis.canvas to get the graphics of the bufferedImage instead of the graphics of the JPanel.

It's as simple as that.

As per Andrews comment. You should consider extending a JLabel instead of a JPanel, it is much more lightweight, and easier to update using label.repaint();.


推荐阅读