import javax.swing.*;
import java.awt.*;
public class TestCenterMessage extends JFrame {
public TestCenterMessage() {
add(new MessagePanel());
}
public static void main(String[] args) {
TestCenterMessage frame = new TestCenterMessage();
frame.setTitle("CenterMessage");
frame.setSize(400, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class MessagePanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
FontMetrics fm = g.getFontMetrics();
int stringHeight = fm.getHeight();
int stringWidth = fm.stringWidth("Welcome to Java");
int x = getWidth() / 2 - stringWidth / 2;
int y = getHeight() / 2 - stringHeight;
g.drawString("Welcome to ", x, y);
stringWidth = fm.stringWidth("Welcome to ");
x += stringWidth;
y += stringHeight;
g.drawString("Java", x, y);
}
}
import java.awt.*;
public class TestCenterMessage extends JFrame {
public TestCenterMessage() {
add(new MessagePanel());
}
public static void main(String[] args) {
TestCenterMessage frame = new TestCenterMessage();
frame.setTitle("CenterMessage");
frame.setSize(400, 100);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class MessagePanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
FontMetrics fm = g.getFontMetrics();
int stringHeight = fm.getHeight();
int stringWidth = fm.stringWidth("Welcome to Java");
int x = getWidth() / 2 - stringWidth / 2;
int y = getHeight() / 2 - stringHeight;
g.drawString("Welcome to ", x, y);
stringWidth = fm.stringWidth("Welcome to ");
x += stringWidth;
y += stringHeight;
g.drawString("Java", x, y);
}
}