此代码仅运行窗口框架,但我无法显示小的蓝色填充矩形。这是为什么?这段代码看起来很合乎逻辑。
我正在尝试创建2个JFrame窗口,每个窗口都有一个蓝色矩形。
public class ColoredRectangle {
// attributes of the rectangle
int width = 40;
int height =20;
int x = 80;
int y = 90;
JFrame window = new JFrame("Box Run");
Color color = Color.BLUE;
// the construtor of the window
public ColoredRectangle() {
window.setSize(200,200);
window.setVisible(true);
}
//the actual rectangle
public void paint () {
Graphics g = window.getGraphics();
g.setColor(color);
g.fillRect(x, y, width, height);
}
public static void main(String[] args) throws IOException {
// creating 2 windows
ColoredRectangle r1 = new ColoredRectangle();
ColoredRectangle r2 = new ColoredRectangle();
//drawing a blue rectangle in each window
r1.paint();
r2.paint();
}
}
答案 0 :(得分:3)
根据评论:
paintComponent
不绘画paintComponent
应该受到保护,而不是公开。Runnable
传递到SwingUtilities.invokeLater(...)
方法,在事件线程上创建Swing GUI。getGraphics()
获得的Graphics对象(除了少数例外)。以这种方式获得的对象将不会持久或稳定,冒着消失的图像或更糟的是NullPointerException。相反,Swing图形通常通过在绘制方法中绘制来完成被动,并允许JVM在需要的时间和地点调用此方法。这将需要在绘制动画时进行范例转换。例如:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
@SuppressWarnings("serial")
public class DrawRectPanel extends JPanel {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
private Color RECT_COLOR = Color.BLUE;
private static final int RECT_X = 80;
private static final int RECT_Y = 90;
private static final int RECT_W = 40;
private static final int RECT_H = 20;
public DrawRectPanel() {
setPreferredSize(new Dimension(PREF_W, PREF_H));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(RECT_COLOR);
g.fillRect(RECT_X, RECT_Y, RECT_W, RECT_H);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("DrawRectPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawRectPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
编辑:要创建2个JFrame,请更改GUI:
private static void createAndShowGui() {
JFrame frame = new JFrame("DrawRectPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawRectPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
createAndShowGui();
});
}
通过“按平台”设置JFrame的位置,让操作系统将其定位在它认为合适的位置,尽管我还必须打印指向此相关StackOverflow链接的链接:The Use of Multiple JFrames: Good or Bad Practice?