在 JPanel 上绘制矩形
我有一个 JScrollPane,在它上面有一个名为“panel1”的 JPanel。 我想要在这个 JPanel 上绘制一些矩形。
我有一个名为 DrawRectPanel 的类,它扩展了 JPanel 并完成所有绘图工作。 问题是,我尝试通过编写以下代码在 panel1 上绘制矩形:
panel1.add(new DrawRectPanel());
但 panel1 上没有出现任何内容 然后我尝试了,就像对 DrawRectPanel 类的测试一样:
JFrame frame = new JFrame();
frame.setSize(1000, 500);
Container contentPane = frame.getContentPane();
contentPane.add(new DrawRectPanel());
frame.show();
这有效,并生成了绘图,但在单独的 JFrame 上 如何在 panel1 上绘制矩形? 提前致谢。
编辑 : DrawRectPanel 的代码
public class DrawRectPanel extends JPanel {
DrawRectPanel() {
Dimension g = new Dimension(400,400);
this.setPreferredSize(g);
System.out.println("label 1");
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("label 2");
g.setColor(Color.red);
g.fillRect(20, 10, 80, 30);
}
}
仅在屏幕上打印标签 1
I have a JScrollPane and on top of it I have a JPanel named 'panel1'.
I want some rectangles to be drawn on this JPanel.
I have a class named DrawRectPanel which extends JPanel and does all the drawing stuff.
The problem is that, I tried to draw the rectangles on panel1 by writing the following code :
panel1.add(new DrawRectPanel());
but nothing appeared on panel1
then I tried, just as a test to the class DrawRectPanel :
JFrame frame = new JFrame();
frame.setSize(1000, 500);
Container contentPane = frame.getContentPane();
contentPane.add(new DrawRectPanel());
frame.show();
This worked, and produced the drawings but on a separate JFrame
How can I draw the rectangles on panel1 ?
Thanks in advance.
EDIT :
code for DrawRectPanel
public class DrawRectPanel extends JPanel {
DrawRectPanel() {
Dimension g = new Dimension(400,400);
this.setPreferredSize(g);
System.out.println("label 1");
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("label 2");
g.setColor(Color.red);
g.fillRect(20, 10, 80, 30);
}
}
only label 1 is printed on the screen
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仍然不知道,
例如
still no idea,
for example
而不是添加,
你应该这样做
,因为你已经在 panel1 中有了新的
DrawRectPanel
。但在您的代码中,您将在contentPane
中添加另一个DrawRectPanel
实例。并且从未在任何容器
中添加panel1
。instead of adding
you should do
Because you already have new
DrawRectPanel
in panel1. But in your code you are adding another instance ofDrawRectPanel
incontentPane
. And never addedpanel1
in none of yourcontainer
.要解决您的问题,当窗口自动重新绘制时,将“paintComponent”更改为“paint”,它应该可以工作。
to fix your problem, change "paintComponent" to "paint" when the window repaints automatically, it should work.