【发布时间】:2014-10-02 10:25:36
【问题描述】:
我正在尝试在 JPanel 上绘制一些填充的矩形并将该面板添加到 JFrame,但是当我运行程序时,我看到的只是 JFrame。我使用 frame.add(new RectanglePanel()); 添加了 JPanel,所以我不确定为什么面板没有出现。
框架类:
package h02;
import javax.swing.*;
// frame and its properties
public class RectangleFrame extends JFrame {
public RectangleFrame() {
// JFrame object
JFrame frame = new JFrame();
// properties
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // frame in centre
frame.setTitle("Drawing rectangles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new RectanglePanel());
frame.setVisible(true);
}
public static void main(String[] args) {
new RectangleFrame();
}
}
面板类:
package h02;
import javax.swing.*;
import java.awt.*;
public class RectanglePanel extends JPanel {
// drawing the rectangles
public void PaintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(110, 110, 20, 20);
g.fillRect(10, 10, 30, 120);
g.fillRect(60, 10, 60, 100);
g.fillRect(150, 10, 10, 20);
g.fillRect(240, 10, 10, 20);
g.fillRect(190, 30, 80, 30);
g.fillRect(210, 50, 60, 20);
g.fillRect(190, 70, 80, 50);
g.fillRect(300, 30, 50, 90);
g.fillRect(330, 10, 30, 20);
}
}
【问题讨论】:
-
我不确定这是否能解决问题,但请尝试使用
frame.add(panel, BorderLayout.CENTER)添加面板。我认为您的面板目前没有正确调整大小,只有框架的内容窗格是(并且您没有在框架或框架的内容窗格上绘画)。您还可以使用 Dimension 设置首选大小,它会覆盖当前 LayoutManager 设置的大小。只是建议 -
你在哪里设置矩形的颜色?添加“g.setColor(Color.RED);”给你paintComponent方法。如果您在构造函数中创建 JFrame,则不需要扩展 JFrame。
-
@VinceEmigh 我尝试使用 frame.add(panel, BorderLayout.CENTER) 但这并没有改变任何东西。我不确定如何使用维度,因为我以前从未使用过它,我必须查一下。
-
@Zyion Nowhere,fillRect 只是让矩形完全变黑对吗?
-
@Zyion 添加 g.setColor(Color.RED);也不会改变任何东西。
标签: java swing jframe jpanel awt