我有一个 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
最佳答案
还是不知道,
例如
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);
}
}
关于java - 在 JPanel 上绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7723591/