我的代码工作得很好,就像它应该做的那样,(感谢这个网站的帮助!)但是我忘了一个细节:我错过了我的面板周围的边框。事实上,我不知道该怎么做,当我为一个面板分配一个标签时,它并不包围所有组件,而是以一种非常奇怪的形式出现。我明白为什么会这样,但我不知道如何解决它以及如何得到我想要的东西。我需要的是:
但我得到的是:
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);
}
}
答案 0 :(得分:2)
TitledBorder titled1 = new TitledBorder("Container");
buttonPanel.setBorder(titled1);
TitledBorder titled2 = new TitledBorder("Properties");
propertiesPanel.setBorder(titled2);