我测试了下,把你的panel1.setAlignmentX(JPanel.LEFT_ALIGNMENT);改为
panel1.setLayout(new FlowLayout(FlowLayout.LEFT));这样应该行了。
下面是我的测试代码:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TestJPanel {
public TestJPanel() {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(3,0));
//设置JPanel的对齐方式,暂时发现只有这样才能使JPanel改变对齐方式。
JPanel JP1 = new JPanel();
JP1.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel JP2 = new JPanel();
JP2.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel JP3 = new JPanel();
JP3.setLayout(new FlowLayout(FlowLayout.LEFT));
//测试标签
JLabel JL1 = new JLabel("测试1");
JLabel JL2 = new JLabel("测试2");
JLabel JL3 = new JLabel("测试三");
//增加则是标签
JP1.add(JL1);
JP2.add(JL2);
JP3.add(JL3);
//增加JPanel
frame.add(JP1);
frame.add(JP2);
frame.add(JP3);
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestJPanel();
}
}
附上运行图片
-
追问:
-
你说的那一句我已经打上了啊~~~改了就变成写了两次了···
-
回答:
-
add(panel1,BorderLayout.NORTH);
add(panel2,BorderLayout.NORTH);
add(panel3,BorderLayout.NORTH);
add(push);
上面这一部分有问题,你的代码我整理下如下:import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TestJPanel {JLabel Label1;
JLabel Label2;
JLabel Label3;
JPanel panel1;
JPanel panel2;
JPanel panel3;
JPanel panel4;
JTextField TextField1;
JTextField TextField2;
JTextField TextField3;
JButton push;
public TestJPanel() {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(4,0)); //用GridLayout布局实现
Label1 = new JLabel("To");
Label1.setAlignmentX(JLabel.LEFT_ALIGNMENT);
Label2 = new JLabel("CC");
Label3 = new JLabel("Bcc");panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.LEFT));
panel2.setLayout(new FlowLayout(FlowLayout.LEFT));
panel3.setLayout(new FlowLayout(FlowLayout.LEFT));TextField1 = new JTextField(30);
TextField2 = new JTextField(30);
TextField3 = new JTextField(45);push = new JButton("Send");
panel4.add(push);
// push.addActionListener(new ButtonListener());panel1.add(Label1);
panel1.add(TextField1);
panel2.add(Label2);
panel2.add(TextField2);
panel3.add(Label3);
panel3.add(TextField3);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.add(panel4);
frame.setVisible(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}public static void main(String[] args) {
new TestJPanel();
}}
效果图如下