从Panel中删除/清空gridLayout

时间:2016-04-26 16:17:22

标签: java swing grid-layout

我有一个9x9的网格布局并生成Jtextareas来填充它。如果用户按下按钮,我希望网格布局再次变为空,这样我可以再次重新填充,但与之前填充的内容无关。 是否有像gridlayout.delete()之类的命令?

1 个答案:

答案 0 :(得分:2)

我猜你要清除GridLayout使用容器所持有的文本组件(你没有告诉我们,请理解这是关于你的问题的关键信息)。如果是这样,将它们放入一个集合(如ArrayList)中,并遍历循环中调用setText("")的列表。

如果您使用的是Java 8,则可以使用Stream上的forEach(...)调用替换此“for循环”。例如,如果你有一个像这样的ArrayList:

List<JTextComponent> textComponentList = new ArrayList<>();

然后你可以通过这个调用清除它所拥有的所有文本组件:

textComponentList.stream().forEach(tc -> tc.setText(""));

例如:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;
import javax.swing.text.JTextComponent;

@SuppressWarnings("serial")
public class ClearGrid extends JPanel {
    private static final int ROWS = 9;
    private static final int COLS = ROWS;
    private static final int GAP = 2;
    private static final Font FONT = new Font(Font.SANS_SERIF, Font.BOLD, 32);
    private static final int FIELD_COLS = 2;
    List<JTextComponent> textComponentList = new ArrayList<>();

    public ClearGrid() {
        JPanel gridPanel = new JPanel(new GridLayout(ROWS, COLS, GAP, GAP));
        gridPanel.setBackground(Color.BLACK);
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                JTextField textField = new JTextField(FIELD_COLS);
                textField.setFont(FONT);
                textField.setHorizontalAlignment(JTextField.CENTER);
                textComponentList.add(textField);
                gridPanel.add(textField);
            }
        }

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(new JButton(new ClearAllAction("Clear All", KeyEvent.VK_C)));

        setLayout(new BorderLayout());
        add(gridPanel);
        add(buttonPanel, BorderLayout.PAGE_END);
    }

    private class ClearAllAction extends AbstractAction {
        public ClearAllAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            textComponentList.stream().forEach(tc -> tc.setText(""));
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("ClearGrid");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new ClearGrid());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}