我是Java Swing新手。我试图通过 layeredPane
在我的框架中添加由 paintComponent()
方法制作的绘图,但它没有显示在 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);
}
}
最佳答案
i am trying to add the drawing made by the paintComponent() method in my a frame through layeredPane but it is not showing in the JFrame
您的 DrawPanel
没有尺寸,因此尺寸为 (0, 0) 并且没有任何可绘制的内容。
However if i place the code frame.getContentPane().add(drawing) and comment the Layered part the code works..
当您将 DrawPanel
直接添加到内容 Pane 时,面板将添加到“CENTER”,并且布局管理器会自动将面板大小设置为框架中的可用空间。
关于java - 在分层平面java中添加绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25921799/