我试图在组件之间添加空白(清晰)间距。如果您运行我的代码,您将看到它们全部连接在一起。我尝试使用insets
并且似乎没有用。我想在x1Input
和dpLabel
之间添加空格,以使它们显示为没有连接。也许我错过了一些简单的东西,但它并没有为我工作。有什么建议吗?
我的代码如下:
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.");
}
}
答案 0 :(得分:0)
我建议您从How to Use GridBagLayout上的Swing教程中的演示代码开始。使用演示代码,您将拥有一个遵循Swing指南的更好的结构化程序。例如:
add("North", top)
。那就是不要使用"魔法"值,这不是指定约束的顺序。应该最后指定约束,就像使用GridBagLayout一样。我尝试使用插图并且似乎没有用。
是什么让你觉得它不起作用? 3个像素是一个小差距。你有没有尝试过更大的差距?