Java – get font, size, bold, etc
•
Java
I can't find anything to access windows fonts or predefined fonts and sizes So for my java program, I have one JCombo@R_966_2419 @Font, size and color The problem is that I need to input font, size and color in advance How will I get predefined fonts, colors and sizes? So far, this is my font, but it's not the right way
if (font.equals("Arial")) {
if (size.equals("8")) {
setSize = 8;
} else if (size.equals("10")) {
setSize = 10;
} else if (size.equals("12")) {
setSize = 12;
}
if (color.equals("Black")) {
setColor = Color.BLACK;
} else if (color.equals("Blue")) {
setColor = Color.BLUE;
} else if (color.equals("Red")) {
setColor = Color.red;
}
Font font = new Font("Arial",setAttribute,setSize);
Writer.setFont(font);
Writer.setForeground(setColor);
Solution
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fonts = ge.getAvailableFontFamilyNames();
You can set the size and style at run time
For example
import java.awt.*;
import javax.swing.*;
class ShowFonts {
public static void main(String[] args) {
SwingUtilities.invokelater( new Runnable() {
public void run() {
GraphicsEnvironment ge = GraphicsEnvironment.
getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
JCombo@R_966_2419@ fontChooser = new JCombo@R_966_2419@(fonts);
fontChooser.setRenderer(new FontCellRenderer());
JOptionPane.showMessageDialog(null,fontChooser);
}
});
}
}
class FontCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(
JList list,Object value,int index,boolean isSelected,boolean cellHasFocus) {
JLabel label = (JLabel)super.getListCellRendererComponent(
list,value,index,isSelected,cellHasFocus);
Font font = new Font((String)value,Font.PLAIN,20);
label.setFont(font);
return label;
}
}
Javadoc for
GraphicsEnvironment. Jdoc partial status of getavailablefontfamilynames()
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
