【JAVA语言程序设计基础篇】--图形-- 三种时钟--增强对类的理解和应用

1.显示任意时间时钟

2.设置三个可见性属性 分别表示时针,分针,秒针的可见性

3.一个精细的时钟

主类:StillClock

@SuppressWarnings("serial")
class DetailedClock extends JPanel {
  private int hour;
  private int minute;
  private int second;
  protected int xCenter, yCenter;
  protected int clockRadius;

  public DetailedClock() {
  }

  // Construct a clock panel
  public DetailedClock(int hour, int minute, int second) {
    this.hour = hour;
    this.minute = minute;
    this.second = second;
  }

  // Draw the clock
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Initialize clock parameters
    clockRadius =
      (int)(Math.min(getSize().width, getSize().height) * 0.9 * 0.5);
    xCenter = (getSize().width) / 2;
    yCenter = (getSize().height) / 2;

    // Draw circle
    g.setColor(Color.black);
    g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
               2 * clockRadius, 2 * clockRadius);

    // Draw second hand
    if (secondHandVisible) {
      int sLength = (int)(clockRadius * 0.7);
      int xSecond =
        (int)(xCenter + sLength * Math.sin(second * (2 * Math.PI / 60)));
      int ySecond =
        (int)(yCenter - sLength * Math.cos(second * (2 * Math.PI / 60)));
      g.setColor(Color.red);
      g.drawLine(xCenter, yCenter, xSecond, ySecond);
    }

    // Draw minute hand
    if (minuteHandVisible) {
      int mLength = (int)(clockRadius * 0.6);
      int xMinute =
        (int)(xCenter + mLength * Math.sin(minute * (2 * Math.PI / 60)));
      int yMinute =
        (int)(yCenter - mLength * Math.cos(minute * (2 * Math.PI / 60)));
      g.setColor(Color.blue);
      g.drawLine(xCenter, yCenter, xMinute, yMinute);
    }
    // Draw hour hand
    if (hourHandVisible) {
      int hLength = (int)(clockRadius * 0.5);
      int xHour = (int)(xCenter +
                        hLength *
                        Math.sin((hour + minute / 60.0) * (2 * Math.PI / 12)));
      int yHour = (int)(yCenter -
                        hLength *
                        Math.cos((hour + minute / 60.0) * (2 * Math.PI / 12)));
      g.setColor(Color.black);
      g.drawLine(xCenter, yCenter, xHour, yHour);
    }
    // Display more details on the clock
    for (int i = 0; i < 60; i++) {
      double percent;

      if (i % 5 == 0) {
        percent = 0.9;
      }
      else {
        percent = 0.95;
      }

      int xOuter = (int)(xCenter +
                         clockRadius * Math.sin(i * (2 * Math.PI / 60)));
      int yOuter = (int)(yCenter -
                         clockRadius * Math.cos(i * (2 * Math.PI / 60)));
      int xInner = (int)(xCenter +
                         percent * clockRadius * Math.sin(i * (2 * Math.PI / 60)));
      int yInner = (int)(yCenter -
                         percent * clockRadius * Math.cos(i * (2 * Math.PI / 60)));

      g.drawLine(xOuter, yOuter, xInner, yInner);
    }

    // Display hours on the clock
    g.setColor(Color.black);
    for (int i = 0; i < 12; i++) {
      int x = (int)(xCenter +
                    0.8 * clockRadius * Math.sin(i * (2 * Math.PI / 12)));
      int y = (int)(yCenter -
                    0.8 * clockRadius * Math.cos(i * (2 * Math.PI / 12)));

      g.drawString("" + ((i == 0) ? 12 : i), x, y);
    }
  }

  /** Return hour */
  public int getHour() {
    return hour;
  }

  /** Set a new hour */
  public void setHour(int hour) {
    this.hour = hour;
    repaint();
  }

  /** Return minute */
  public int getMinute() {
    return minute;
  }

  /** Set a new minute */
  public void setMinute(int minute) {
    this.minute = minute;
    repaint();
  }

  /** Return second */
  public int getSecond() {
    return second;
  }

  /** Set a new second */
  public void setSecond(int second) {
    this.second = second;
    repaint();
  }

  private boolean hourHandVisible = true;
  private boolean minuteHandVisible = true;
  private boolean secondHandVisible = true;

  public boolean isHourHandVisible() {
    return hourHandVisible;
  }

  public boolean isMinuteHandVisible() {
    return hourHandVisible;
  }

  public boolean isSecondHandVisible() {
    return secondHandVisible;
  }

  public void setHourHandVisible(boolean hourHandVisible) {
    this.hourHandVisible = hourHandVisible;
    repaint();
  }

  public void setMinuteHandVisible(boolean minuteHandVisible) {
    this.minuteHandVisible = minuteHandVisible;
    repaint();
  }

  public void setSecondHandVisible(boolean secondHandVisible) {
    this.secondHandVisible = secondHandVisible;
    repaint();
  }

}

MessagePanel类

@SuppressWarnings("serial")
class MessagePanel extends JPanel {
  /** The message to be displayed */
  private String message = "Welcome to Java";

  /** The x coordinate where the message is displayed */
  private int xCoordinate = 20;

  /** The y coordinate where the message is displayed */
  private int yCoordinate = 20;

  /** Indicate whether the message is displayed in the center */
  private boolean centered;

  /** The interval for moving the message horizontally
   * and vertically */
  private int interval = 10;

  /** Construct with default properties */
  public MessagePanel() {
  }

  /** Construct a message panel with a specified message */
  public MessagePanel(String message) {
    this.message = message;
  }

  /** Return message */
  public String getMessage() {
    return message;
  }

  /** Set a new message */
  public void setMessage(String message) {
    this.message = message;
    repaint();
  }

  /** Return xCoordinator */
  public int getXCoordinate() {
    return xCoordinate;
  }

  /** Set a new xCoordinator */
  public void setXCoordinate(int x) {
    this.xCoordinate = x;
    repaint();
  }

  /** Return yCoordinator */
  public int getYCoordinate() {
    return yCoordinate;
  }

  /** Set a new yCoordinator */
  public void setYCoordinate(int y) {
    this.yCoordinate = y;
    repaint();
  }

  /** Return centered */
  public boolean isCentered() {
    return centered;
  }

  /** Set a new centered */
  public void setCentered(boolean centered) {
    this.centered = centered;
    repaint();
  }

  /** Return interval */
  public int getInterval() {
    return interval;
  }

  /** Set a new interval */
  public void setInterval(int interval) {
    this.interval = interval;
    repaint();
  }

  /** Paint the message */
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (centered) {
      // Get font metrics for the current font
      FontMetrics fm = g.getFontMetrics();

      // Find the center location to display
      int stringWidth = fm.stringWidth(message);
      int stringAscent = fm.getAscent();
      // Get the position of the leftmost character in the baseline
      xCoordinate = getWidth() / 2 - stringWidth / 2;
      yCoordinate = getHeight() / 2 + stringAscent / 2;
    }

    g.drawString(message, xCoordinate, yCoordinate);
  }

  /** Move the message left */
  public void moveLeft() {
    xCoordinate -= interval;
    repaint();
  }

  /** Move the message right */
  public void moveRight() {
    xCoordinate += interval;
    repaint();
  }

  /** Move the message up */
  public void moveUp() {
    yCoordinate -= interval;
    repaint();
  }

  /** Move the message down */
  public void moveDown() {
    yCoordinate += interval;
    repaint();
  }
  /** Override get method for preferredSize */
  public Dimension getPreferredSize() {
    return new Dimension(200, 30);
  }
}

1.显示任意时间时钟

package chapter15_编程练习题;

import java.awt.*;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.swing.*;

@SuppressWarnings("serial")
public class Exercise15_18 extends JFrame {
  public Exercise15_18() {
    setLayout(new GridLayout(1, 2));
    StillClock clock1 = new StillClock(4, 20, 45);
    StillClock clock2 = new StillClock(22, 46, 15);
    add(clock1);
    add(clock2);
  }

  public static void main(String[] args) {
    Exercise15_18 frame = new Exercise15_18();
    frame.setTitle("Exercise15_18");
    frame.setSize(400, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setVisible(true);
  }
}

@SuppressWarnings("serial")
class StillClock extends JPanel {
	private int hour;
	private int minute;
	private int second;

	/** Construct a default clock with the current time */
	public StillClock() {
		setCurrentTime();
	}

	/** Construct a clock with specified hour, minute, and second */
	public StillClock(int hour, int minute, int second) {
		this.hour = hour;
		this.minute = minute;
		this.second = second;
	}

	/** Return hour */
	public int getHour() {
		return hour;
	}

	/** Set a new hour */
	public void setHour(int hour) {
		this.hour = hour;
		repaint();
	}

	/** Return minute */
	public int getMinute() {
		return minute;
	}

	/** Set a new minute */
	public void setMinute(int minute) {
		this.minute = minute;
		repaint();
	}

	/** Return second */
	public int getSecond() {
		return second;
	}

	/** Set a new second */
	public void setSecond(int second) {
		this.second = second;
		repaint();
	}

	/** Draw the clock */
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		// Initialize clock parameters
		int clockRadius = (int) (Math.min(getWidth(), getHeight()) * 0.8 * 0.5);
		int xCenter = getWidth() / 2;
		int yCenter = getHeight() / 2;

		// Draw circle
		g.setColor(Color.black);
		g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
				2 * clockRadius, 2 * clockRadius);
		g.drawString("12", xCenter - 5, yCenter - clockRadius + 12);
		g.drawString("9", xCenter - clockRadius + 3, yCenter + 5);
		g.drawString("3", xCenter + clockRadius - 10, yCenter + 3);
		g.drawString("6", xCenter - 3, yCenter + clockRadius - 3);

		// Draw second hand
		int sLength = (int) (clockRadius * 0.8);
		int xSecond = (int) (xCenter + sLength
				* Math.sin(second * (2 * Math.PI / 60)));
		int ySecond = (int) (yCenter - sLength
				* Math.cos(second * (2 * Math.PI / 60)));
		g.setColor(Color.red);
		g.drawLine(xCenter, yCenter, xSecond, ySecond);

		// Draw minute hand
		int mLength = (int) (clockRadius * 0.65);
		int xMinute = (int) (xCenter + mLength
				* Math.sin(minute * (2 * Math.PI / 60)));
		int yMinute = (int) (yCenter - mLength
				* Math.cos(minute * (2 * Math.PI / 60)));
		g.setColor(Color.blue);
		g.drawLine(xCenter, yCenter, xMinute, yMinute);

		// Draw hour hand
		int hLength = (int) (clockRadius * 0.5);
		int xHour = (int) (xCenter + hLength
				* Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
		int yHour = (int) (yCenter - hLength
				* Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
		g.setColor(Color.BLACK);
		g.drawLine(xCenter, yCenter, xHour, yHour);
	}

	public void setCurrentTime() {
		// Construct a calendar for the current date and time
		Calendar calendar = new GregorianCalendar();

		// Set current hour, minute and second
		this.hour = calendar.get(Calendar.HOUR_OF_DAY);
		this.minute = calendar.get(Calendar.MINUTE);
		this.second = calendar.get(Calendar.SECOND);
	}

	public Dimension getPreferredSize() {
		return new Dimension(200, 200);
	}
}

2.设置三个可见性属性 分别表示时针,分针,秒针的可见性

package chapter15_编程练习题;
import javax.swing.*;

import java.awt.*;
import java.util.Calendar;
import java.util.GregorianCalendar;

@SuppressWarnings("serial")
public class Exercise15_19 extends JFrame {
    public Exercise15_19() {
    StillClock2 clock = new StillClock2();
    clock.setSecondHandVisible(false);
    clock.setHour((int)(Math.random() * 12));
    clock.setMinute((int)(Math.random() * 2) == 0 ? 0 : 30);

    add(clock);
  }
  public static void main(String[] args) {
    Exercise15_19 frame = new Exercise15_19();
    frame.setSize(400, 400);
    frame.setTitle("Exercise15_19");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setVisible(true);
  }
}
@SuppressWarnings("serial")
class StillClock2 extends JPanel {
	private int hour;
	private int minute;
	private int second;
	/** Construct a default clock with the current time */
	public StillClock2() {
		setCurrentTime();
	}
	/** Construct a clock with specified hour, minute, and second */
	public StillClock2(int hour, int minute, int second) {
		this.hour = hour;
		this.minute = minute;
		this.second = second;
	}
	/** Return hour */
	public int getHour() {
		return hour;
	}
	/** Set a new hour */
	public void setHour(int hour) {
		this.hour = hour;
		repaint();
	}
	/** Return minute */
	public int getMinute() {
		return minute;
	}
	/** Set a new minute */
	public void setMinute(int minute) {
		this.minute = minute;
		repaint();
	}
	/** Return second */
	public int getSecond() {
		return second;
	}
	/** Set a new second */
	public void setSecond(int second) {
		this.second = second;
		repaint();
	}
	/** Draw the clock */
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		// Initialize clock parameters
		int clockRadius = (int) (Math.min(getWidth(), getHeight()) * 0.8 * 0.5);
		int xCenter = getWidth() / 2;
		int yCenter = getHeight() / 2;

		// Draw circle
		g.setColor(Color.black);
		g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
				2 * clockRadius, 2 * clockRadius);
		g.drawString("12", xCenter - 5, yCenter - clockRadius + 12);
		g.drawString("9", xCenter - clockRadius + 3, yCenter + 5);
		g.drawString("3", xCenter + clockRadius - 10, yCenter + 3);
		g.drawString("6", xCenter - 3, yCenter + clockRadius - 3);

		// Draw second hand
		if(secondHandVisible){
		int sLength = (int) (clockRadius * 0.8);
		int xSecond = (int) (xCenter + sLength
				* Math.sin(second * (2 * Math.PI / 60)));
		int ySecond = (int) (yCenter - sLength
				* Math.cos(second * (2 * Math.PI / 60)));
		g.setColor(Color.red);
		g.drawLine(xCenter, yCenter, xSecond, ySecond);
		}
		// Draw minute hand
		if(minuteHandVisible){
		int mLength = (int) (clockRadius * 0.65);
		int xMinute = (int) (xCenter + mLength
				* Math.sin(minute * (2 * Math.PI / 60)));
		int yMinute = (int) (yCenter - mLength
				* Math.cos(minute * (2 * Math.PI / 60)));
		g.setColor(Color.blue);
		g.drawLine(xCenter, yCenter, xMinute, yMinute);
		}
		// Draw hour hand
		if(hourHandVisible){
		int hLength = (int) (clockRadius * 0.5);
		int xHour = (int) (xCenter + hLength
				* Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
		int yHour = (int) (yCenter - hLength
				* Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
		g.setColor(Color.BLACK);
		g.drawLine(xCenter, yCenter, xHour, yHour);
		}
	}
	public void setCurrentTime() {
		// Construct a calendar for the current date and time
		Calendar calendar = new GregorianCalendar();

		// Set current hour, minute and second
		this.hour = calendar.get(Calendar.HOUR_OF_DAY);
		this.minute = calendar.get(Calendar.MINUTE);
		this.second = calendar.get(Calendar.SECOND);
	}

	public Dimension getPreferredSize() {
		return new Dimension(200, 200);
	}
	private boolean hourHandVisible = true;
	private boolean minuteHandVisible = true;
	private boolean secondHandVisible = true;

	public boolean isHourHandVisible() {
		return hourHandVisible;
	}

	public void setHourHandVisible(boolean hourHandVisible) {
		this.hourHandVisible = hourHandVisible;
		repaint();
	}

	public boolean isMinuteHandVisible() {
		return minuteHandVisible;
	}

	public void setMinuteHandVisible(boolean minuteHandVisible) {
		this.minuteHandVisible = minuteHandVisible;
		repaint();
	}

	public boolean isSecondHandVisible() {
		return secondHandVisible;
	}

	public void setSecondHandVisible(boolean secondHandVisible) {
		this.secondHandVisible = secondHandVisible;
		repaint();
	}

}

3.一个精细的时钟

package chapter15_编程练习题;

import java.awt.*;

import javax.swing.*;

@SuppressWarnings("serial")
public class Exercise15_20 extends JFrame {
  public static void main(String[] args) {
    // Obtain the total seconds since the midnight, Jan 1, 1970
    long totalSeconds = System.currentTimeMillis() / 1000;

    // Compute the current second in the minute in the hour
    int currentSecond = (int)(totalSeconds % 60);

    // Obtain the total minutes
    long totalMinutes = totalSeconds / 60;

    // Compute the current minute in the hour
    int currentMinute = (int)(totalMinutes % 60);

    // Obtain the total hours
    long totalHours = totalMinutes / 60;

    // Compute the current hour
    int currentHour = (int)(totalHours % 24);

    // Create a frame to hold the clock
    Exercise15_20 frame = new Exercise15_20();
    frame.setTitle("Exercise15_20");
    DetailedClock clock = new DetailedClock(currentHour, currentMinute, currentSecond);
    clock.setSecondHandVisible(false);
    frame.add(clock);
    MessagePanel messagePanel = new MessagePanel(
      currentHour + ":" + currentMinute + ":" + currentSecond + " GMT");
    messagePanel.setCentered(true);
    messagePanel.setForeground(Color.blue);
    frame.add(messagePanel, BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 350);
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setVisible(true);
  }
}

@SuppressWarnings("serial")
class DetailedClock extends JPanel {
  private int hour;
  private int minute;
  private int second;
  protected int xCenter, yCenter;
  protected int clockRadius;

  public DetailedClock() {
  }

  // Construct a clock panel
  public DetailedClock(int hour, int minute, int second) {
    this.hour = hour;
    this.minute = minute;
    this.second = second;
  }

  // Draw the clock
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Initialize clock parameters
    clockRadius =
      (int)(Math.min(getSize().width, getSize().height) * 0.9 * 0.5);
    xCenter = (getSize().width) / 2;
    yCenter = (getSize().height) / 2;

    // Draw circle
    g.setColor(Color.black);
    g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
               2 * clockRadius, 2 * clockRadius);

    // Draw second hand
    if (secondHandVisible) {
      int sLength = (int)(clockRadius * 0.7);
      int xSecond =
        (int)(xCenter + sLength * Math.sin(second * (2 * Math.PI / 60)));
      int ySecond =
        (int)(yCenter - sLength * Math.cos(second * (2 * Math.PI / 60)));
      g.setColor(Color.red);
      g.drawLine(xCenter, yCenter, xSecond, ySecond);
    }

    // Draw minute hand
    if (minuteHandVisible) {
      int mLength = (int)(clockRadius * 0.6);
      int xMinute =
        (int)(xCenter + mLength * Math.sin(minute * (2 * Math.PI / 60)));
      int yMinute =
        (int)(yCenter - mLength * Math.cos(minute * (2 * Math.PI / 60)));
      g.setColor(Color.blue);
      g.drawLine(xCenter, yCenter, xMinute, yMinute);
    }
    // Draw hour hand
    if (hourHandVisible) {
      int hLength = (int)(clockRadius * 0.5);
      int xHour = (int)(xCenter +
                        hLength *
                        Math.sin((hour + minute / 60.0) * (2 * Math.PI / 12)));
      int yHour = (int)(yCenter -
                        hLength *
                        Math.cos((hour + minute / 60.0) * (2 * Math.PI / 12)));
      g.setColor(Color.black);
      g.drawLine(xCenter, yCenter, xHour, yHour);
    }
    // Display more details on the clock
    for (int i = 0; i < 60; i++) {
      double percent;

      if (i % 5 == 0) {
        percent = 0.9;
      }
      else {
        percent = 0.95;
      }

      int xOuter = (int)(xCenter +
                         clockRadius * Math.sin(i * (2 * Math.PI / 60)));
      int yOuter = (int)(yCenter -
                         clockRadius * Math.cos(i * (2 * Math.PI / 60)));
      int xInner = (int)(xCenter +
                         percent * clockRadius * Math.sin(i * (2 * Math.PI / 60)));
      int yInner = (int)(yCenter -
                         percent * clockRadius * Math.cos(i * (2 * Math.PI / 60)));

      g.drawLine(xOuter, yOuter, xInner, yInner);
    }

    // Display hours on the clock
    g.setColor(Color.black);
    for (int i = 0; i < 12; i++) {
      int x = (int)(xCenter +
                    0.8 * clockRadius * Math.sin(i * (2 * Math.PI / 12)));
      int y = (int)(yCenter -
                    0.8 * clockRadius * Math.cos(i * (2 * Math.PI / 12)));

      g.drawString("" + ((i == 0) ? 12 : i), x, y);
    }
  }

  /** Return hour */
  public int getHour() {
    return hour;
  }

  /** Set a new hour */
  public void setHour(int hour) {
    this.hour = hour;
    repaint();
  }

  /** Return minute */
  public int getMinute() {
    return minute;
  }

  /** Set a new minute */
  public void setMinute(int minute) {
    this.minute = minute;
    repaint();
  }

  /** Return second */
  public int getSecond() {
    return second;
  }

  /** Set a new second */
  public void setSecond(int second) {
    this.second = second;
    repaint();
  }

  private boolean hourHandVisible = true;
  private boolean minuteHandVisible = true;
  private boolean secondHandVisible = true;
  public boolean isHourHandVisible() {
    return hourHandVisible;
  }

  public boolean isMinuteHandVisible() {
    return hourHandVisible;
  }

  public boolean isSecondHandVisible() {
    return secondHandVisible;
  }

  public void setHourHandVisible(boolean hourHandVisible) {
    this.hourHandVisible = hourHandVisible;
    repaint();
  }

  public void setMinuteHandVisible(boolean minuteHandVisible) {
    this.minuteHandVisible = minuteHandVisible;
    repaint();
  }

  public void setSecondHandVisible(boolean secondHandVisible) {
    this.secondHandVisible = secondHandVisible;
    repaint();
  }
}

@SuppressWarnings("serial")
class MessagePanel extends JPanel {
  /** The message to be displayed */
  private String message = "Welcome to Java";

  /** The x coordinate where the message is displayed */
  private int xCoordinate = 20;

  /** The y coordinate where the message is displayed */
  private int yCoordinate = 20;

  /** Indicate whether the message is displayed in the center */
  private boolean centered;

  /** The interval for moving the message horizontally
   * and vertically */
  private int interval = 10;

  /** Construct with default properties */
  public MessagePanel() {
  }

  /** Construct a message panel with a specified message */
  public MessagePanel(String message) {
    this.message = message;
  }

  /** Return message */
  public String getMessage() {
    return message;
  }

  /** Set a new message */
  public void setMessage(String message) {
    this.message = message;
    repaint();
  }

  /** Return xCoordinator */
  public int getXCoordinate() {
    return xCoordinate;
  }

  /** Set a new xCoordinator */
  public void setXCoordinate(int x) {
    this.xCoordinate = x;
    repaint();
  }

  /** Return yCoordinator */
  public int getYCoordinate() {
    return yCoordinate;
  }

  /** Set a new yCoordinator */
  public void setYCoordinate(int y) {
    this.yCoordinate = y;
    repaint();
  }

  /** Return centered */
  public boolean isCentered() {
    return centered;
  }

  /** Set a new centered */
  public void setCentered(boolean centered) {
    this.centered = centered;
    repaint();
  }

  /** Return interval */
  public int getInterval() {
    return interval;
  }

  /** Set a new interval */
  public void setInterval(int interval) {
    this.interval = interval;
    repaint();
  }

  /** Paint the message */
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (centered) {
      // Get font metrics for the current font
      FontMetrics fm = g.getFontMetrics();

      // Find the center location to display
      int stringWidth = fm.stringWidth(message);
      int stringAscent = fm.getAscent();
      // Get the position of the leftmost character in the baseline
      xCoordinate = getWidth() / 2 - stringWidth / 2;
      yCoordinate = getHeight() / 2 + stringAscent / 2;
    }

    g.drawString(message, xCoordinate, yCoordinate);
  }

  /** Move the message left */
  public void moveLeft() {
    xCoordinate -= interval;
    repaint();
  }

  /** Move the message right */
  public void moveRight() {
    xCoordinate += interval;
    repaint();
  }

  /** Move the message up */
  public void moveUp() {
    yCoordinate -= interval;
    repaint();
  }

  /** Move the message down */
  public void moveDown() {
    yCoordinate += interval;
    repaint();
  }
  /** Override get method for preferredSize */
  public Dimension getPreferredSize() {
    return new Dimension(200, 30);
  }
}

时间: 2024-12-27 05:39:44

【JAVA语言程序设计基础篇】--图形-- 三种时钟--增强对类的理解和应用的相关文章

Java语言程序设计基础篇 数组(六)

Java语法之数组 数组的定义 数组是对象. 如:int [ ]  x = new int[100];或 :int x [ ]  = new int[100];(这种方式主要是为了适应C/C++程序员) 声明一个数组变量:int [ ] x;并不会在内存中给数组分配任何空间,仅创建一个引用数组的存储地址. 数组创建后,其元素赋予默认值,数值型基本数据类型默认值为0,char类型为'\u0000',boolean类型为false. 数组的静态初始化 如:int [ ] x = new int [

Java语言程序设计基础篇 循环(四)

①打印:***** **** *** ** * for(int x=1; x<=5; x++) { for(int y=x; y<=5; y++) { System.out.print("*"); //向下一般的格式for(int y=x; y<=5; y++) } System.out.println(); } ②打印:* ** *** **** ***** for (int x=1; x<=5 ;x++ ) { for (int y=1;y<=x ;y

Java语言程序设计基础篇 方法(五)

生成随机字符 生成随机字符就是生成0到65535之间的一个随机整数,因为0<=Math.random()<1.0,必须在65535+1 (int) (Math.random() * (65535+1)) 随机生成小写字母 public class RandomCharacter { public static char getRandomCharacter(char ch1,char ch2){ return (char)(ch1 +Math.random() * (ch2 - ch1 + 1

Java语言程序设计基础篇 循环(四)练习

*4.21(计算不同利率下的贷款)编写程序,让用户输入贷款总额及以年为单位的贷款期限,以1/8为递增量,显示从5%到8%的利率下每月支付额和总偿还额.假设输入贷款总量为10 000,还贷期限为5年,所显示的输出如下: 贷款总额:to 000 年数:5 利率月支付额总偿还额 5%188 .71   11322.74 5 .125%189.28   11357.13 5 .25%189.85   11391.59 ... //Exercise3_26.java: displays the month

【JAVA语言程序设计基础篇】--图形用户界面基础--一些总结

第12章 图形界面基础 1.那个类是JAVA GUI组件的根?容器类是component的子类吗?哪个类是Swing GUI组建的根? java.awt.component是所有java GUI组件类的根. 容器类如JFrame是组件的子类. JComponent是Swing GUI组件类的根. 2.AWT组件与Swing组建的不同? AWT的组件是重而swing组件轻量化. 3. 你可以添加一个按钮到一个框架. 答:正确 您可以将一个框架添加到面板中. 答:错误 你可以添加一个面板到一个框架.

【JAVA语言程序设计基础篇】--事件驱动程序设计--定义监听器的另一种方式

有很多种方式定义监听类,哪种方式比较好呢? 使用内部类或者匿名内部类定义监听类已经成了事件处理程序设计的标准. 因为他通常都能提供清晰.干净和简洁的代码. package chapter16; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFram

【JAVA语言程序设计基础篇】--图形用户界面基础--练习

exercise12_1 练习FLowLayout package chapter12; import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JPanel; @SuppressWarnings("serial") public class exercise12_1 extends JFrame{ public exercise12_1(

【JAVA语言程序设计基础篇】--图形--一些练习

exercise15-01 package chapter15; import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; @SuppressWarnings("serial") public class exercise15_01 extends JFrame { public exercise15_01() { add(new newp

【JAVA语言程序设计基础篇】--图形-- 绘制封装表格类的思考

开始用的方法没有体现类的封装性 没有类的普遍性 package chapter15; import java.awt.*; import javax.swing.*; @SuppressWarnings("serial") public class exercise15_14 extends JFrame { public exercise15_14() { add(new barchart()); } public static void main(String[] args) {