java - 对象未出现在 JPanel 上
问题描述
我正在尝试添加一个形状(矩形到 GUI),请告诉我我的代码有什么问题?- 目标是使用按钮添加形状,但在我什至使用 ActionListener 之前,我试图在界面上显示形状。
public class FactoryPattern extends JFrame {
public static void main(String[] args) {
ShapeFactory shapes = new ShapeFactory();
JPanel panel = new JPanel();
JButton loadBtn = new JButton("Load Shapes");
JButton sortBtn = new JButton("Sort Shapes");
panel.add(sortBtn);
panel.add(loadBtn);
panel.add(shapes);
JFrame frame = new JFrame("Display two shapes (rectangles)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ShapeFactory extends JComponent{
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Color color = new Color(222,222,222);
Rectangle rect1 = new Rectangle(150, 95, 150, 150, color);
g2d.setColor(rect1.getColor());
rect1.drawShape(g2d);
}
}
解决方案
推荐阅读
- python - 无法调用 canvas.show()
- python - 如何循环回到程序的开头?Python
- python - 为什么多个 on_message 事件不起作用?
- geometry - 将点从一个坐标变换到另一个坐标
- python - Python - 连接由双换行符分隔的两个字符串
- jenkins - 触发作业时的Multibranch管道时,Jenkins工作区中存储了什么?
- c# - 停止 Alertdialog 以自动向上滚动?
- windbg - 类指针值成员上的 WinDBG 条件断点
- vue.js - 如何使用 vue-router 重定向非动态 url
- c - ncurses 子窗口不保持固定宽度