A quick post here really, as I found it difficult to find this information all in one place, anywhere else.
I’m not usually a Java programmer, but it is used as part of some of our courses and assignments at Uni. We’ve recently gone into setting up GUIs and something that I wanted to do was style my read-only text, or JLabels. Searching brought me to many incomplete answers, or answers on forums like “
Font() is your friend”, hinting to look into the documentation.
However the documentation for
Font() is incredibly broad and not the smallest of pages, so for this specific case, I think it would be more useful to have all the information on the page. There are also other types of styling which
Font() does not cover…
Font() to style your JLabel
It is assumed that you understand what a JLabel is, how to create an instance of one and what to do with one after you’ve created it and styled it. But just for completeness to start with, we’ll add in a JLabel creation. Styling the actual text is done by creating a Font object with the necessary parameters specified. First we’ll style a label to the default styling given to a JLabel.
JLabel label = new JLabel("Hello There!"); label.setFont(new Font("Sans Serif", Font.PLAIN, 12));
Testing this won’t really show much visually, as it will look like this, regardless of whether you specify the style. But it’s good to know what you’re changing the styling from, especially if you ever want to return a label to it’s normal style. But now let’s try something a bit different.