0
我試圖在組件之間添加空白(清除)間距。如果你運行我的代碼,你會看到它全部連接在一起。我曾嘗試使用insets
,但似乎沒有工作。我想在x1Input
和dpLabel
之間添加空格,以使它們顯示爲不連接。也許我錯過了一些簡單的東西,但它並沒有爲我工作。有什麼建議?使用GridBagLayout/GridBagConstraints添加空白空間
我的代碼如下:
package problemgbc;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ProblemGBC extends JFrame implements ActionListener {
JLabel x1Label = new JLabel("x1:");
JTextField x1Input = new JTextField(3);
JLabel x2Label = new JLabel("x2:");
JTextField x2Input = new JTextField(3);
JLabel xLabel = new JLabel("x:");
JTextField xInput = new JTextField(3);
JLabel dpLabel = new JLabel("Decimal Value:");
JComboBox decimalPlace = new JComboBox();
public static void main(String[] args) {
try {
//Sets the GUI look and feel to the systems default GUI
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | UnsupportedLookAndFeelException e) {
}
ProblemGBC problemGUI = new ProblemGBC();
}
public ProblemGBC() {
setLayout(new BorderLayout());
setSize(650, 150);
setResizable(false);
setLocationRelativeTo(null);
setTitle("Problem");
ImageIcon iconImg = new ImageIcon("src/resources/icon.png");
setIconImage(iconImg.getImage());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(3, 3, 3, 3);
gbc.weighty = 0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
JPanel top = new JPanel(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
top.add(xLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
top.add(xInput, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
top.add(x1Label, gbc);
gbc.gridx = 3;
gbc.gridy = 0;
top.add(x1Input, gbc);
gbc.gridx = 2;
gbc.gridy = 1;
top.add(x2Label, gbc);
gbc.gridx = 3;
gbc.gridy = 1;
top.add(x2Input, gbc);
gbc.gridx = 4;
gbc.gridy = 0;
top.add(dpLabel);
gbc.gridx = 5;
gbc.gridy = 0;
decimalPlace.addItem("Full Answer");
decimalPlace.addItem("1");
decimalPlace.addItem("2");
decimalPlace.addItem("3");
decimalPlace.addItem("4");
decimalPlace.addItem("5");
decimalPlace.addItem("6");
decimalPlace.addItem("7");
decimalPlace.addItem("8");
decimalPlace.addItem("9");
((JLabel) decimalPlace.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
top.add(decimalPlace, gbc);
add("North", top);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
您可以創建一個沒有任何內容的標籤,只是將其設置爲一定的寬度,並將其放置在兩個元素之間...... – brso05
不要創建一個不需要的破解標籤,並且會混淆網格面板。 – camickr