Java JLabel text in middle of vertical axis
I have a JLabel
that contains variable text in a certain location in my GUI. The problem is that the text gets displayed at the bottom of the space where the JLabel
is located. This does not convey to the end user the relevant information about the other contents of the GUI. Instead, I need the text of the JLabel
to be printed in the middle of the vertical axis of the JLabel
. A simplified version of my code is below. Can anyone show me how to alter it so that the text displays in the middle of the vertical axis instead of the bottom?
Main.java:
import java.awt.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Main");
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new VerticalLabel("Hello"));
Dimension prefSize = new Dimension(400, 300);
frame.setPreferredSize(prefSize);
frame.setMinimumSize(prefSize);
frame.pack();
frame.setVisible(true);
}
}
VerticalLabel.java:
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
public class VerticalLabel extends JLabel {
public VerticalLabel(String labelText) {
Dimension myDim = new Dimension(15, 250);
this.setPreferredSize(myDim);
this.setHorizontalAlignment(LEFT);
开发者_如何学Go this.setVerticalAlignment(CENTER);
this.setText(labelText);
this.setVerticalTextPosition(CENTER);
this.setUI(new VerticalLabelUI(false));
this.setBorder(new EtchedBorder());
}
}
Hardcoding a random preferred size is not a good idea.
You wrote a custom UI, so it is the responsibility of the UI to paint the text in the proper position.
Instead of creating a custom UI you can use the Text Icon approach to display vertical text. Create the label as follows:
JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
TextIcon labelIcon = new TextIcon(label, "Hello", TextIcon.Layout.VERTICAL);
label.setIcon( vIcon );
Add the label to the CENTER of a panel using a BorderLayout and the vetical text will be centered vertically and horizontally.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EtchedBorder;
public class VerticalLabel extends JLabel{
public VerticalLabel(String labelText){
this.setHorizontalAlignment(LEFT);
this.setVerticalAlignment(CENTER);
this.setText(labelText);
this.setVerticalTextPosition(CENTER);
//this.setUI( new VerticalLabelUI(false) );
this.setBorder( new EtchedBorder() );
}
public static void main(String[] args){
// should be done on the EDT.
JFrame frame = new JFrame("Main");
frame.getContentPane().setLayout( new GridBagLayout() );
frame.getContentPane().add(new VerticalLabel("Hello"));
Dimension prefSize = new Dimension(200,150);
frame.setPreferredSize(prefSize);
frame.setMinimumSize(prefSize);
frame.pack();
frame.setVisible(true);
}
}
精彩评论