Label Alignment
I'm making a couple of little Swing widgets for editing data, I've come accross this little alignment problem and it's doing my head in. When the component is disabled, it shows a label, but this label is not aligned the way I want it, and nothing I do (setVerticalAlignment/setVerticalTextPosition) seems to affect it!
I've mocked up a little demo that reproduces the problem without you having to trawl through all my code, the main method creates a JFrame with a custom JPanel in it, which toggles between enabled and disabled every 1500 ms.
Can anyone see what I'm doing wrong, I know this is not going to be difficult, probably a one liner, but I can't for the life of me figure it out.
Here's the demo code..
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
publicclass LabelAlignmentextends JPanel{
private Color BORDER_COLOR = Color.GRAY;
private Color BACKGROUND_COLOR = Color.WHITE;
private Font LABEL_FONT =new Font("dialog",Font.PLAIN,12);
privateboolean enabled;
private JPanel content, enabledPanel, disabledPanel;
private JLabel disabledLabel;
public LabelAlignment(){
// create main content panel
content =new JPanel();
content.setLayout(new BoxLayout(content,BoxLayout.X_AXIS));
content.setBackground(BACKGROUND_COLOR);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(BORDER_COLOR));
setLayout(new BorderLayout(0,0));
// create enabled/disabled panels, and add them to content panel
enabledPanel = buildEnabledPanel();
disabledPanel = buildDisabledPanel();
content.add(enabledPanel);
content.add(disabledPanel);
add(content,BorderLayout.NORTH);
setEnabled(true);
}
private JPanel buildEnabledPanel(){
JPanel panel =new JPanel();
panel.setBackground(Color.GREEN);
panel.setPreferredSize(new Dimension(195,30));
return panel;
}
private JPanel buildDisabledPanel(){
JPanel panel =new JPanel(new FlowLayout(FlowLayout.LEFT,1,1));
disabledLabel =new JLabel("Some Text");
disabledLabel.setBackground(BACKGROUND_COLOR);
disabledLabel.setFont(LABEL_FONT);
panel.add(Box.createHorizontalStrut(3));
panel.add(disabledLabel);
panel.setBackground(BACKGROUND_COLOR);
return panel;
}
publicvoid setEnabled(boolean b){
System.out.println("setEnabled("+b+")");
super.setEnabled(b);
disabledPanel.setPreferredSize(new Dimension(enabledPanel.getSize()));
enabledPanel.setVisible(b);
disabledPanel.setVisible(!b);
}
/**
* This is just for testing
*/
publicstaticvoid main(String [] args)throws IOException{
JFrame frame =new JFrame("TestFrame");
LabelAlignment la =new LabelAlignment();
JPanel p1 =new JPanel();
p1.add(la);
frame.getContentPane().add(p1);
frame.addWindowListener(new WindowAdapter(){
publicvoid windowClosing(WindowEvent e){
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
boolean toggle =false;
while(true){
try{
Thread.sleep(1500);
}
catch (InterruptedException ie){};
la.setEnabled(toggle);
toggle = (toggle ?false :true);
}
}
}

