BorderLayout,询问用户输入HGap和VGap

时间:2015-10-23 22:45:12

标签: java swing border-layout

我想知道是否有人可以给我任何关于从哪里开始我的任务的指示。我应该创建一个程序,允许用户输入一个值,该值可以设置BorderLayout中按钮之间的HGap或VGap。我已经尝试将其映射到纸上,但我不知道是否应该使用面板或标签,或者如何实现使用文本区域设置间隙的方法,甚至不知道如何将框架扩展到按钮之外(我有一个按钮代码,但它们填满了整个空间)。这就是它应该是这样的:

enter image description here

同样适用于VGap。非常感谢任何帮助,但请记住,我只是一个初学者。我只需要建议,我会尝试用我的编码更新你,但是现在我没有任何东西。

1 个答案:

答案 0 :(得分:2)

以下代码可能会给您一个想法...

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class BorderDemo extends JFrame {
    private JPanel buttonPanel = new JPanel();
    private JPanel propertiesPanel = new JPanel();
    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 BorderDemo() {
        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);

        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) {
        BorderDemo borderDemo = new BorderDemo();
        borderDemo.setVisible(true);
        borderDemo.setSize(400, 400);
        borderDemo.setLocationRelativeTo(null);
        borderDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}