如何创建未知数量的Swing组件?

时间:2018-04-06 11:15:27

标签: java swing user-interface

我需要显示一个用户输入的标签页数(JTabbedPane)(具有相同的初始内容,但能够单独更改内容),是否有办法在程序上创建这些组件所以我不知道#39; t必须知道在用户输入之前会有多少?

1 个答案:

答案 0 :(得分:1)

以下是依赖于用户输入的tabse更改编号的示例:

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TabbedPaneTest3 implements Runnable {

    private final JTabbedPane tabber = new JTabbedPane();

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TabbedPaneTest3());
    }

    @Override
    public void run() {
        final JSpinner spinner = new JSpinner(new SpinnerNumberModel(3, 1, 10, 1));
        spinner.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                Object val = spinner.getValue();
                if (val instanceof Number) {
                    updateTabsNumber((Number) val);
                }
            }
        });
        updateTabsNumber(3);
        JFrame frm = new JFrame("Tab Pane");
        JPanel panel = new JPanel();
        panel.add(new JLabel("Number of tabs: "));
        panel.add(spinner);
        frm.add(panel, BorderLayout.NORTH);
        frm.add(tabber);
        frm.setSize(600, 400);
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    private void updateTabsNumber(Number val) {
        int count = val.intValue();
        tabber.removeAll();
        for (int i = 0; i < count; i++) {
            String text = "Tab " + (i + 1);
            JTextArea area = new JTextArea(10, 30);
            area.setText("Initial text for tab: " + (i + 1));
            tabber.addTab(text, new JScrollPane(area));
        }

    }
}