【发布时间】:2022-01-14 10:01:51
【问题描述】:
我正在尝试拥有多个可以“重叠”的JPanels,也允许我执行自定义绘画。
为此,我使用了MainPanel,它扩展了JLayeredPane,据我所知,我已经正确设置了边界和索引。
预期的结果是两个矩形同时绘制到屏幕上。
我得到的结果是在两个OverlappingPanels 之一上闪烁,我认为这是来自RepaintManager 在哪个面板上绘制 (Found this here)。
我的问题是,如何使用 Swing 正确重叠面板并保留绘画功能?
编辑:
有问题的代码:
import javax.swing.*;
import java.awt.*;
public class Example extends JFrame {
public static class MainPanel extends JLayeredPane implements Runnable {
public OverlappingPanel1 overlappingPanel1;
public OverlappingPanel2 overlappingPanel2;
Thread mainThread;
public void startMainThread() {
mainThread = new Thread(this);
mainThread.start();
}
public MainPanel() {
this.setPreferredSize(new Dimension(1920,720));
this.setBackground(Color.BLACK);
this.setDoubleBuffered(true);
overlappingPanel1 = new OverlappingPanel1();
overlappingPanel2 = new OverlappingPanel2();
overlappingPanel1.setBounds(0,0,1920,720);
overlappingPanel2.setBounds(0,720/2,1920,720);
add(overlappingPanel1,1);
add(overlappingPanel2,2);
}
@Override
public void run() {
while(mainThread != null) {
overlappingPanel1.repaint();
overlappingPanel2.repaint();
}
}
}
public static class OverlappingPanel1 extends JPanel {
public OverlappingPanel1() {
setDoubleBuffered(true);
setPreferredSize(new Dimension(1920,720));
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D graphics2D = (Graphics2D) g;
graphics2D.fillRect(0,0,200,200);
}
}
public static class OverlappingPanel2 extends JPanel {
public OverlappingPanel2() {
setDoubleBuffered(true);
setPreferredSize(new Dimension(1920,720));
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D graphics2D = (Graphics2D) g;
graphics2D.fillRect(0,80,200,200);
}
}
public static void main(String[] args) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
MainPanel mainPanel = new MainPanel();
window.add(mainPanel);
window.setBackground(Color.BLACK);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
mainPanel.startMainThread();
}
}
【问题讨论】:
-
将相关代码放入问题中。
-
@JustanotherJavaprogrammer 提到我的问题的代码在消息末尾附加的超链接中
-
这就是问题所在。在问题中包含代码。
-
覆盖paintComponent而不是paint。绘画是旧的 AWT 方式。
-
Swing 默认为双缓冲,因此无需为每个面板显式设置。