我的代码工作正常,正如它应该做的那样,(感谢这个网站的帮助!)但我忘记了一个细节:我错过了面板周围的边框。问题是,我不知道该怎么做,当我为面板分配标签时,它不会包围所有组件,而是以一种非常奇怪的形式出现。我确实理解它为什么会发生,但我不知道如何解决它以及如何获得我想要的东西。我需要的:
但我得到的是:
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.event.*;
import java.awt.*;
public class HW2BorderLayoutSettings extends JFrame {
private JPanel buttonPanel = new JPanel();
private JPanel propertiesPanel = new JPanel();
private JLabel label1 = new JLabel();
private JLabel label2 = new JLabel();
private JButton north = new JButton("North");
private JButton south = new JButton("South");
private JButton west = new JButton("West");
private JButton east = new JButton("East");
private JButton center = new JButton("Center");
private BorderLayout border = new BorderLayout();
private JLabel label = new JLabel("BorderLayout Properties:");
private JLabel hGapLabel = new JLabel("HGap:");
private JLabel vGapLabel = new JLabel("VGap:");
private JTextField hGapField = new JTextField();
private JTextField vGapField = new JTextField();
private GridLayout grid = new GridLayout(2, 2);
private Integer hGapInt;
private Integer vGapInt;
public HW2BorderLayoutSettings() {
buttonPanel.setLayout(border);
buttonPanel.add(north, BorderLayout.NORTH);
buttonPanel.add(center, BorderLayout.CENTER);
buttonPanel.add(south, BorderLayout.SOUTH);
buttonPanel.add(west, BorderLayout.WEST);
buttonPanel.add(east, BorderLayout.EAST);
propertiesPanel.setLayout(grid);
propertiesPanel.add(hGapLabel);
propertiesPanel.add(hGapField);
propertiesPanel.add(vGapLabel);
propertiesPanel.add(vGapField);
add(buttonPanel, BorderLayout.CENTER);
add(propertiesPanel, BorderLayout.SOUTH);
buttonPanel.add(label1);
propertiesPanel.add(label2);
label1.setHorizontalAlignment(JLabel.LEFT);
label2.setHorizontalAlignment(JLabel.LEFT);
TitledBorder titled1 = new TitledBorder("Container");
label1.setBorder(titled1);
TitledBorder titled2 = new TitledBorder("Properties");
label2.setBorder(titled2);
hGapField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hGapInt = Integer.parseInt(hGapField.getText());
border.setHgap(hGapInt);
setSize((int) (getWidth() + hGapInt), getHeight());
validate();
}
});
vGapField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
vGapInt = Integer.parseInt(vGapField.getText());
border.setVgap(vGapInt);
setSize(getWidth(), (int) (getHeight() + vGapInt));
validate();
}
});
}
public static void main(String[] args) {
HW2BorderLayoutSettings borderDemo = new HW2BorderLayoutSettings();
borderDemo.setTitle("Border Layout");
borderDemo.setSize(400, 400);
borderDemo.setLocationRelativeTo(null);
borderDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
borderDemo.setVisible(true);
}
}