import java.awt.*;
import javax.swing.*;class Fonts2Panel extends JPanel {
public void paintComponent(Graphics g){
String myquote = "Happiness is an attitude.";
Font f = new Font("Times New Roman",Font.BOLD + Font.ITALIC,24);
FontMetrics fm = getFontMetrics(f);
int x = (getSize().width - fm.stringWidth(myquote)) / 2;
System.out.println(getSize().width+" "+fm.stringWidth(myquote)+" "+x);
int y = getSize().height/2;
g.drawString(myquote,x,y);
}
}class FontsFrames extends JFrame {
public FontsFrames(){
setTitle("test");
setSize(300,200);
Container contentPane = getContentPane();
contentPane.add(new Fonts2Panel());
//close the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}public class Fonts2Demo {
public static void main(String [] args){
JFrame frame = new FontsFrames();
frame.show();
}
}//粗体和居中显示都没有实现,哪里错了?
import javax.swing.*;class Fonts2Panel extends JPanel {
public void paintComponent(Graphics g){
String myquote = "Happiness is an attitude.";
Font f = new Font("Times New Roman",Font.BOLD + Font.ITALIC,24);
FontMetrics fm = getFontMetrics(f);
int x = (getSize().width - fm.stringWidth(myquote)) / 2;
System.out.println(getSize().width+" "+fm.stringWidth(myquote)+" "+x);
int y = getSize().height/2;
g.drawString(myquote,x,y);
}
}class FontsFrames extends JFrame {
public FontsFrames(){
setTitle("test");
setSize(300,200);
Container contentPane = getContentPane();
contentPane.add(new Fonts2Panel());
//close the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}public class Fonts2Demo {
public static void main(String [] args){
JFrame frame = new FontsFrames();
frame.show();
}
}//粗体和居中显示都没有实现,哪里错了?
import javax.swing.*;class Fonts2Panel extends JPanel {
public void paintComponent(Graphics g){
String myquote = "Happiness is an attitude.";
Font f = new Font("Times New Roman",Font.BOLD+Font.ITALIC,24);
FontMetrics fm = getFontMetrics(f); g.setFont(f); //<------原来是少了这个 int x = (getSize().width - fm.stringWidth(myquote)) / 2;
System.out.println(getSize().width+" "+fm.stringWidth(myquote)+" "+x);
int y = getSize().height/2;
g.drawString(myquote,x,y);
}
}class FontsFrames extends JFrame {
public FontsFrames(){
setTitle("test");
setSize(300,200);
Container contentPane = getContentPane();
contentPane.add(new Fonts2Panel());
//close the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}public class Fonts2Demo {
public static void main(String [] args){
JFrame frame = new FontsFrames();
frame.show();
}
}