我需要在中间画一个带有文字的圆圈,请帮忙

时间:2013-12-20 09:36:41

标签: java swing jpanel geometry gridbaglayout

嗨,我需要制作一个可以在中间放置文字的圆圈。 目前我可以绘制圆圈,但我不知道如何调整它们以便将文本放在中间。

如果有人能告诉我如何做到这一点或帮助我,我将不胜感激。

谢谢, 什哈布

2 个答案:

答案 0 :(得分:3)

在Swing中绘制圆圈:

public class CirclePanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
    //Adding  super.paintComponent....  
    super.paintComponent(g);

    g.drawOval(0, 0, g.getClipBounds().width, g.getClipBounds().height);
    }
}

要在圈子中添加文字,您可以使用 GridBagLayout .i.e。

CirclePanel panel = new CirclePanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints cl;
cl = new GridBagConstraints();
cl.gridy = 0;
panel.add(new JLabel("Hello"), cl);

这是Link,你可以使用swing来使用Canvas绘制一个圆圈。

Draw canvas with color and text

答案 1 :(得分:0)

有关更一般的解决方案,请查看Playing With Shapes。然后,您可以创建ShapeIcon并将图标添加到JLabel。然后,您可以使用JLabel显示以图标为中心的文本:

JLabel label = new JLabel( new ShapeIcon(...) );
label.setText( "Centered Text" );
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);

您需要确保形状足够大以包含文本。