问题描述
我有一个JScrollPane,在它之上我有一个名为'panel1'的JPanel。
我希望在这个JPanel上绘制一些矩形。
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.
我有一个名为DrawRectPanel的类,它扩展了JPanel并完成了所有绘图工作。
问题在于,我尝试通过编写以下代码在panel1上绘制矩形:
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());
但是没有出现在panel1
然后我试过,就像对DrawRectPanel类的测试一样:
but nothing appeared on panel1then 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();
这是有效的,并且在单独的JFrame上生成了图纸
如何绘制panel1上的矩形?
提前致谢。
This worked, and produced the drawings but on a separate JFrameHow can I draw the rectangles on panel1 ?Thanks in advance.
编辑:
代码为DrawRectPanel
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);
}
}
屏幕上只打印标签1
推荐答案
仍然不知道,
例如
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class CustomComponent extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent() {
setTitle("Custom Component Graphics2D");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void display() {
add(new CustomComponents());
pack();
// enforces the minimum size of both frame and component
setMinimumSize(getSize());
setVisible(true);
}
public static void main(String[] args) {
CustomComponent main = new CustomComponent();
main.display();
}
}
class CustomComponents extends JComponent {
private static final long serialVersionUID = 1L;
@Override
public Dimension getMinimumSize() {
return new Dimension(100, 100);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
@Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
这篇关于在JPanel上绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!