java 中JLabel中的内容垂直居中和水平居中问题
之前网上找了很多,有第三方插件的,但是没有解决问题,最终发现Java自带的布局就能实现其功能;主要如下:水平居中,垂直居中,即水平居中又垂直居中。
1.水平居中
代码如下:
public class Demo extends JFrame{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1345343984399264602L;
public Demo(){
super("label中内容水平居中");
setBounds(100, 100, 400, 300);
JPanel p = new JPanel();
p.add(new JLabel("General",JLabel.CENTER));
p.setBackground(Color.green);
getContentPane().add(p);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Demo demo = new Demo();
}
}
代码分析:new JLabel(“General”,JLabel.CENTER);这个JLabel有自带的居中,所有不需要其他的布局。
2.垂直居中:
代码如下:
public class Demo extends JFrame{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1345343984399264602L;
public Demo(){
super("label中内容垂直居中");
setBounds(100, 100, 400, 300);
JPanel p = new JPanel(new BorderLayout());
p.add(new JLabel("General"),BorderLayout.CENTER);
p.setBackground(Color.green);
getContentPane().add(p);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Demo demo = new Demo();
}
}
代码解析:new JLabel(“General”),BorderLayout.CENTER;BorderLayout布局主要是东西南北中五块,所以用它就可以实现垂直居中。具体代码可以去找API解决。
3.即垂直又水平居中,即将JLabel中的内容放到正中央。
public class Demo extends JFrame{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1345343984399264602L;
public Demo(){
super("label中内容即垂直又水平居中");
setBounds(100, 100, 400, 300);
JPanel p = new JPanel(new BorderLayout());
p.add(new JLabel("General",JLabel.CENTER),BorderLayout.CENTER);
p.setBackground(Color.green);
getContentPane().add(p);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Demo demo = new Demo();
}
}
这个就更简单了,即水平又垂直,其实就是将1,2结合起来就行了。问题简单,仅供参考,不足之处,多多指教。