在paintComponent中绘制另一个组件

时间:2011-07-20 09:56:47

标签: java swing

我使用Java Tutorials中的SwingPaintDemo2:

http://download.oracle.com/javase/tutorial/uiswing/examples/painting/SwingPaintDemo2Project/src/painting/SwingPaintDemo2.java

我这样修改了它:

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw Text
    g.drawString("This is my custom Panel!",10,20);

    JLabel c = new JLabel("Label");
    c.paint(g);
}

g.drawString工作正常。但是我如何从这种方法中绘制JLabel?它不起作用。

3 个答案:

答案 0 :(得分:4)

我认为您必须为标签设置尺寸。

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw Text
    g.drawString("This is my custom Panel!",10,20);

    JLabel c = new JLabel("Label");
    c.setBounds(0, 0, 400, 30);
    c.paint(g);
}

答案 1 :(得分:4)

请参阅this thread上的LabelRenderTest.java来源。标签最终被绘制到屏幕上,但在显示之前它被绘制到BufferedImage

来源的重要部分是..

textLabel.setSize(textLabel.getPreferredSize());

答案 2 :(得分:-1)

JLabel label_name = new JLabel("Some text");

label_name.setBounds(position_x, position_y, width, height);

label_name.setFont(new Font("Dialog", Font.PLAIN, 10));

add(label_name);