java - 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);
}
}
解决方案
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();
.
推荐阅读
- firebase - 除了下载的数据之外,附加 Firebase 实时数据库侦听器是否有任何相关成本?
- java - 在 Java 中,我需要用户输入五个整数然后显示平均值。如何在不输入第 6 个条目的情况下获得总和中包含的第 5 个整数?
- javascript - 如何使传单弹出窗口跟随光标的位置?
- java - 在我们声明它为 false 之后的 while 语句中的布尔值
- python - 请用 Python 解释以下代码的输出
- python - 如何在 Python 中与 *args 一起传递附加参数
- svelte - Svelte.js 可以用于数据驱动的模板吗?
- lua - 正在运行的 tarantool 实例上覆盖配置
- vue.js - Azure AD B2C - 具有多个客户帐户的同一用户
- visual-studio-code - VSCode 是否不鼓励编辑已安装的插件?