Try and use FontMetrics
. You can learn more here
private final Font font = new Font("impact", Font.ITALIC, 20);
....
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
int height = fm.getAscent();
int y = getHeight()/2 + height/2;
int x = 0;
for (String s : list) {
g.drawString(s, x, y);
x += fm.stringWidth(s);
}
}
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Italic extends JPanel{
private final List<String> list;
private final Font font = new Font("impact", Font.ITALIC, 20);
public Italic() {
list = createList();
}
private List<String> createList() {
List<String> myContentWords = new ArrayList<>();
myContentWords.add("and");
myContentWords.add(" ");
myContentWords.add("additional");
myContentWords.add(" ");
myContentWords.add("description");
myContentWords.add(" ");
myContentWords.add("text");
myContentWords.add(" ");
myContentWords.add("#");
myContentWords.add(" ");
myContentWords.add("4");
return myContentWords;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
int height = fm.getAscent();
int y = getHeight()/2 + height/2;
int x = 0;
for (String s : list) {
g.drawString(s, x, y);
x += fm.stringWidth(s);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 100);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JOptionPane.showMessageDialog(null, new Italic());
}
});
}
}