I have used Romain Hippeau's answer. In order to set the default font of the application when it is first built.
public static void setUIFont(javax.swing.plaf.FontUIResource f) {
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof javax.swing.plaf.FontUIResource)
UIManager.put(key, f);
}
And then calling it:
setUIFont(new javax.swing.plaf.FontUIResource("Sans", Font.PLAIN, 24));
However when new text is written to the swing application: I.e
JTextArea textArea = new JTextArea();
onSomeEventHappening(){
textArea.setText("Hello world");
}
Hello world appears in the standard swing font whereas all my other elements remain at the font I want everything to stay in. Is there any way to make sure that all new text added to the application, doesn't have its font changed.
Above shows an example of this, the word "FOOTBALL"
has be written into its combo box and therefore appears with Swing's normal font, whereas my button "Generate one link"
appears in the font I've set.
Below shows a copy and paste example, if you click on the button, despite setting the font above, the label is still in Swings original style:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class test extends JFrame {
private static final int WIDTH = 1000;
private static final int HEIGHT = 700;
private JTextArea textArea = new JTextArea();
public static void setUIFont(javax.swing.plaf.FontUIResource f) {
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof javax.swing.plaf.FontUIResource)
UIManager.put(key, f);
}
}
public test(){
initialize();
}
final ActionListener buttonClick = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText("new Text");
}
};
public void initialize(){
new JFrame();
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1,2));
setUIFont(new javax.swing.plaf.FontUIResource("Sans", Font.PLAIN, 24));
JButton button = new JButton("test");
button.addActionListener(buttonClick);
this.add(button);
this.add(textArea);
setVisible(true);
}
public static void main(String[] args){
test test1 = new test();
}
}