I am using Kubuntu 21.04 with a screen resolution of 2560x1440 and a global scale of 150% to make the font sizes and other GUI elements of various applications large enough to read.
Unfortunately, this does not seem to extend to the font size of my Java program with Swing GUI.
I have created a test program as a minimal reproducible example. The main function of a plain, vanilla program creates an instance of the following class:
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Test extends JFrame {
Container c;
public Test() {
c = getContentPane();
this.setTitle("Test window");
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel("This is a test label. Consider the font size "
+ "relative to the frame title size."), BorderLayout.NORTH);
panel.add(new JButton("This is a test button"), BorderLayout.SOUTH);
c.add(panel);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
The following screenshot of the resulting window next to the font size of the code in Eclipse illustrates the size problem. Look at the size of the label and button text relative to both the font size in the frame and the Eclipse code text.
I am using OpenJDK version 12 for compilation and, as you can see in the code, call for the System look and feel, though that results in the Metal look and feel on Kubuntu, apparently.
I have found out that I can change the scaling of the application from 100% to 200% by writing something like java -jar -Dsun.java2d.uiScale=2 program.jar
on the terminal. But I suppose most of my users won't start the JAR from the terminal, and values like 1.5
(for 150%) do not seem to work. So not really a solution.
How can I change the font size, and potentially other GUI components, to the default font size of the operating system after scaling to 150% in the operating system? How can I do this in a way that works independently of the operating system and in line with the scaling the user has set?
Edit: I have found a bug description about scaling issues for the JDK and am wondering if this is causing the problem. I am using JDK 14, but the bug description is specifically for 17, so no idea if it also applies to 14.
I have tried it in Windows 7 in a virtual machine, and the scaling seems to work, so I think it may be specifically a Linux (or Unix?) issue. But not sure.