我是Java的新手。我试图通过paintComponent()
在我的框架中添加layeredPane
方法所做的绘图,但它没有显示在JFrame
但是,如果我放置代码frame.getContentPane().add(drawing)
并注释分层部分代码可以正常工作..
我做错了什么?
这是代码: 框架类
public class FrameTest extends JFrame {
static JFrame frame= new JFrame("Frame");
public static void main(String[] args) {
FrameTest test= new FrameTest ();
}
public FrameTest (){
this.openfrane();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void openframe(){
//window properties
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(1000,600);
frame.setResizable(false);
//changing icon of window
ImageIcon image = new ImageIcon("assets/icon.png");
card.setIconImage(image.getImage());
//label picture background
JLabel background = new JLabel();
ImageIcon back = new ImageIcon("assets/background.jpg");
background.setIcon(back);
background.setLocation(0,-125);
background.setSize(1000,700);
//label for first
JLabel first = new JLabel("Sample text");
first.setForeground(Color.RED);
first.setSize(500,200);
first.setLocation(31, 150);
Draw drawing = new Draw();
JLayeredPane layers = new JLayeredPane();
layers.add(drawing, new Integer(3));
layers.add(first, new Integer(2));
layers.add(background,new Integer(1));
frame.setLayeredPane(layers);
}
}
画班:
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
int startX = 00;
int startY = 00;
// First circle
Ellipse2D circle1 = new Ellipse2D.Double(startX, startY, 30, 30);
g2.setColor(Color.Black);
g2.draw(circle1);
g2.fill(circle1);
// Second circle
Ellipse2D circle2 = new Ellipse2D.Double(startX+20, startY, 30, 30);
g2.setColor(Color.Black);
g2.draw(circle2);
g2.fill(circle2);
}
}
答案 0 :(得分:1)
我试图通过layeredPane在我的框架中添加paintComponent()方法绘制的图形,但它没有在JFrame中显示
你的DrawPanel
没有大小,因此大小为(0,0)并且没有任何颜色可供绘制。
但是如果我放置代码frame.getContentPane()。添加(绘图)并注释分层部分代码可以工作..
将DrawPanel
直接添加到内容窗格时,面板会添加到" CENTER"并且面板大小由布局管理器自动设置为框架中可用的空间。