I am making a customised swing component and I have hit a problem. I want a simple text display (like a jlabel) that changes colour over time. Currently I have extended JPanel and overridden paintComponent(Graphics) to create a component that can draw the text it’s given and cycle the colours as required. However, I do not know how to make it always draw the text in the centre of the component, nor how to make it calculate its own default preferred size (as I do not know the exact dimensions of the text) e.g. a JLabel with text set automatically returns the right value for getPreferredSize and the text always fits neatly into the label, this is the functionality I am looking to emulate. Does anyone know how to achieve this?
Share
The FontMetrics class is used to determine the geometry of rendered text with a specific font. This will tell you how much space you need to render your text.
Take a look at the
getLineMetricsmethods.