java中一和panel中有三个按钮,如何设置两个左对齐,另外一个右对齐

2024-11-06 21:44:00
推荐回答(1个)
回答(1):

给你个思路,用Gridlayout,没有的地方new JLable();

下面给你个例子:

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {
private JFrame frame;
private JPanel panel;
private JButton b1;
private JButton b2;
private JButton b3;

public void init(){
frame=new JFrame("Test");
panel=new JPanel();
b1=new JButton("b1");
b2=new JButton("b2");
b3=new JButton("b3");

panel.setLayout(new GridLayout(3,2));
panel.add(b1);
panel.add(new JLabel());
panel.add(new JLabel());
panel.add(b2);
panel.add(b3);
panel.add(new JLabel());

frame.add(panel);

frame.setLocation(20, 20);
frame.setSize(350, 280);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String[] args) {
new Test().init();
}
}