这是我的圈子课程

import java.awt.*;

public class Circle
{
  private int diameter, x, y;
  private Color color;
  private String name, number;

  public Circle(int x, int y,  String number, String name, Color color,int diameter)
  {
    this.x = x;
    this.y = y;
    this.name = name;
    this.color = color;
    this.number = number;
    this.diameter = diameter;

  }

  public void draw(Graphics page)
  {
    page.setColor(color);
    page.fillOval(x, y, diameter, diameter);
    page.drawString(name, x, y);
    page.drawString(number, x, y);
    page.drawRect(150, 100, 30, 100);   // rectangle
    page.fillRect(150, 100, 30, 100);
  }
}


这是我的TablePanel

import javax.swing.*;
import java.awt.*;

public class TablePanel extends JPanel
{
  private Circle circle1, circle2, circle3, circle4, circle5, circle6;

  public TablePanel()
  {
    circle1 = new Circle(150, 60,"1", "Murray", Color.blue, 30);
    circle2 = new Circle(210, 100,"2", "Anne", Color.pink, 30);
    circle3 = new Circle(210, 190,"3", "Roger", Color.blue, 30);
    circle4 = new Circle(150, 220, "4", "Bella", Color.pink, 30);
    circle5 = new Circle(90, 190,"5", "Colin", Color.blue, 30);
    circle6 = new Circle(90, 100,"6", "Josie", Color.pink, 30);

    setPreferredSize (new Dimension(300, 300));
    setBackground(Color.white);
  }

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

    circle1.draw(page);
    circle2.draw(page);
    circle3.draw(page);
    circle4.draw(page);
    circle5.draw(page);
    circle6.draw(page);
  }
}


最后这是我的应用程序类

import javax.swing.JFrame;

public class Table
{
  public static void main (String[] args)
  {
    JFrame frame = new JFrame("Table Setting");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.getContentPane().add(new TablePanel());

    frame.pack();
    frame.setVisible(true);
  }
}


假设要在一张桌子周围以不同的颜色显示不同性别的座位安排,这在我跑步时效果很好,但是我似乎无法将姓名和座位号放在圆圈的中间。任何建议如何解决这个问题?

最佳答案

int radius = diameter/2;
page.drawString(number, x+radius, y+radius);


这将导致String的渲染以圆弧的左下角为中心。为了使其居中,有必要考虑渲染的String的宽度和高度。对于后者,请使用FontMetricsTextLayout

关于java - 帮忙找出姓名和号码在圈子中的位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7304974/

10-08 22:30