0
我有一个JPanel
三个按钮和一个标签。一个按钮和标签位于第一行,另外两个按钮位于第二行。我需要标签位于右上方,但这样做会导致标签意外增大,并将两个向下按钮向左推。Java Swing GridBagLayout:JLabel占用太多空间
public class UserInterface extends JFrame {
int width;
int height;
JPanel panel;
public static void main(String[] args) {
run();
}
public UserInterface() {
setup();
}
private void setup() {
width=800;
height=600;
panel=new UserInterfacePanel();
getContentPane().add(panel, BorderLayout.NORTH);
setSize(width, height);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void run() {
UserInterface gui=new UserInterface();
gui.setVisible(true);
}
}
class UserInterfacePanel extends JPanel {
private JToggleButton startButton;
private JToggleButton stopButton;
private JButton homeStatusButton;
private JLabel timeStatusLabel;
public static void main(String[] args) {
}
public UserInterfacePanel() {
setup();
}
private void setup() {
setLayout(new GridBagLayout());
setupButtons();
timeStatusLabel=new JLabel();
timeStatusLabel.setMinimumSize(new Dimension(180,200));
timeStatusLabel.setPreferredSize(new Dimension(180,200));
timeStatusLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 2));
GridBagConstraints c1 = new GridBagConstraints();
c1.fill = GridBagConstraints.HORIZONTAL;
c1.weightx=0;
c1.weighty=0;
c1.anchor=GridBagConstraints.CENTER;
c1.gridx=0;
c1.gridy=0;
c1.insets=new Insets(20, 20, 250, 50);
add(homeStatusButton, c1);
c1.gridx=1;
c1.gridy=0;
c1.insets=new Insets(0, 50, 10, 10);
c1.weightx=1;
add(timeStatusLabel, c1);
GridBagConstraints c2=new GridBagConstraints();
c2.insets=new Insets(30,20,30,20);
c2.anchor=GridBagConstraints.CENTER;
c2.weightx=0.0;
c2.gridx=0;
c2.gridy=1;
add(startButton, c2);
c2.gridx=1;
c2.gridy=1;
add(stopButton, c2);
}
private void setupButtons() {
startButton=new JToggleButton("Start Button");
stopButton=new JToggleButton("Stop Button");
homeStatusButton=new JButton("OUT");
homeStatusButton.setBackground(Color.RED);
homeStatusButton.setForeground(Color.BLACK);
homeStatusButton.setSize(new Dimension(100, 20));
}
}
我不明白为什么会发生这种情况。看起来我隐含地说明了按钮的位置以及标签的位置。为什么标签变大,按钮被推到左边。
您正在为标签设置插页。 – camickr
@camickr,是的,但它仍然太大,并且对按钮来说太大了。 – parsecer
你是什么意思太大。您可以使用(250,50)的添加插入来指定大小(180,200)。 “按钮的推动力太大” - 所有组件都使用约束,除非每次将组件添加到面板时重置约束。 – camickr