Question

Hi I need to make a circle that can have text in the middle. At the moment I can draw circles but I don't know how to adapt them in order to place text in the middle.

If anyone can show me how to do this or help me in anyway I would be grateful.

Thanks, Shihab

Was it helpful?

Solution

For Drawing a circle in 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);
    }
}

For adding text inside the circle you can use 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);

Here is the Link in that you can use swing to draw a circle using Canvas.

Draw canvas with color and text

OTHER TIPS

For a more general solution check out Playing With Shapes. Then you can create a ShapeIcon and add the Icon to a JLabel. Then you can use the JLabel to display the text centered on the Icon:

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

You will need to make sure the shape is large enough to contain the text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top