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