当前位置: 代码迷 >> J2SE >> JLabel对齐啥意思,该怎么解决
  详细解决方案

JLabel对齐啥意思,该怎么解决

热度:293   发布时间:2016-04-24 01:39:17.0
JLabel对齐啥意思
Java code
import java.awt.*;import javax.swing.*;public class TestField{    public static void main(String args[]){        MyFrame mFrame = new MyFrame();        mFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        mFrame.setVisible(true);    }}class MyFrame extends JFrame{    public MyFrame(){        setTitle("TextField");        setSize(400,300);        setLocation(550,350);        MyPanel myPanel = new MyPanel();        getContentPane().add(myPanel);    }}class MyPanel extends JPanel{    public MyPanel(){        JLabel label = new JLabel("<html>Hello</html>",SwingConstants.LEFT);        //JLabel label = new JLabel("<html>Hello</html>",SwingConstants.RIGHT);                   这个标签组件一开始怎么在中间?设置左边和右边都无用,请问对齐是啥意思?        add(label);    }}


------解决方案--------------------
上面说错了,JPanel默认是FlowLayout,但默认不是左对齐,是居中。

楼主代码这么改一下就行了:

Java code
import java.awt.*;import javax.swing.*;public class TestField{    public static void main(String args[]){        MyFrame mFrame = new MyFrame();        mFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        mFrame.setVisible(true);    }}class MyFrame extends JFrame{    public MyFrame(){        setTitle("TextField");        setSize(400,300);        setLocation(550,350);        MyPanel myPanel = new MyPanel();        getContentPane().add(myPanel);    }}class MyPanel extends JPanel{    public MyPanel(){        JLabel label = new JLabel("<html>Hello</html>",SwingConstants.LEFT);        FlowLayout layout = (FlowLayout)getLayout();        layout.setAlignment(FlowLayout.LEFT);        add(label);    }}