There seems to be an issue with aligning certain characters to the center of a BoxLayout along the y-axis in Java. I don't know what could cause this, & I've created an SSCCE to demonstrate the effect. In the example, I only use the character 'a', & I draw a line down the direct middle of each JPanel to demonstrate how far off each case is from the center. The case with bold text seems to line up fine, but normal formatting & italics are both grossly off-center, despite using both setAlignmentX & setHorizontalAlignment. Any help on understanding this effect is appreciated.
In the case that somehow the problem is with Java on my specific computer, this is an image of what displays on my screen when I run the SSCCE, which loads three different JPanels with BoxLayouts along the y-axis & puts a centered JLabel with only the character 'a' in each:
& here is the code for the SSCCE:
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class AlignmentTest extends JPanel
{
public AlignmentTest(char label, int style)
{
JLabel l = new JLabel(Character.toString(label));
setBorder(BorderFactory.createLineBorder(Color.BLACK,1));
setBackground(Color.WHITE);
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
setPreferredSize(new Dimension(300,50));
add(Box.createVerticalGlue());
add(l);
l.setFont(l.getFont().deriveFont(style));
l.setAlignmentX(CENTER_ALIGNMENT);
l.setHorizontalAlignment(JLabel.CENTER);
add(Box.createVerticalGlue());
}
public static void main(String[] args)
{
JFrame f = new JFrame("Alignment Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(1,0,5,5));
f.add(new AlignmentTest('a',Font.PLAIN));
f.add(new AlignmentTest('a',Font.BOLD));
f.add(new AlignmentTest('a',Font.ITALIC));
f.pack();
f.setVisible(true);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(getWidth()/2,0,getWidth()/2,getHeight());
}
}
style
names. – Interscholasticstyle
names now. Thank you for the input. – Taille