- 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); }}