我也遇到了这个问题,只有这个问题才是 OP 建议的。
// Only this works for me
this.setBackground(Color.blue);
示例类的完整代码在这里(只是为了显示我试图放置/设置 setBackground();
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CircleDraw extends JFrame {
Float diameter = 150f;
public CircleDraw() {
super("Circle Draw");
this.setSize(300, 300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.add(new CirclePanel(diameter));
this.setVisible(true);
// Only this works for me
this.setBackground(Color.blue);
}
public static void main(String[] args) {
new CircleDraw();
}
}
class CirclePanel extends JPanel {
Float diameter;
public CirclePanel(Float diameter) {
super();
// this.setOpaque(true);
// this.setBackground(Color.WHITE);
this.diameter = diameter;
}
@Override
public void paintComponent(Graphics g) {
int panelWidth = this.getSize().width;
int panelHeight = this.getSize().height;
setPreferredSize(new Dimension(300, 300));
Graphics2D comp2D = (Graphics2D) g;
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
comp2D.setStroke(new BasicStroke(1f));
// comp2D.setBackground(Color.white);
comp2D.setPaint(Color.white);
Ellipse2D.Float e1 = new Ellipse2D.Float((panelWidth / 2) - (diameter / 2), (panelHeight / 2) - (diameter / 2), diameter, diameter);
comp2D.draw(e1);
}
}