首页 > 解决方案 > 自动将 JTextFilds 放在 GUI 上,repaint()

问题描述

当我在另一个文本字段中获得多个文本字段时,如何自动将其他文本字段放在面板上?!我尝试使用 repaint(),但我不明白。

import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Example extends JFrame {

    private Container container;
    private JPanel panel;
    private JTextField number; //get a number of TextFields
    private JTextField text;  // this to put in gui automatically 

    public Example() {
        super("Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(200, 400);
        setLocationRelativeTo(null);
        openView();
    }

    public void openView() {
        container = this.getContentPane();

        panel = new JPanel();
        panel.setSize(new Dimension(200, 400));
        panel.setLayout(null);

        number = new JTextField();
        number.setBounds( 50, 10, 100, 40);
        number.addKeyListener(new KeyListener() {

            @Override
            public void keyPressed(KeyEvent e) {
                // put others TextFields on gui
                int y= 50;
                int count = Integer.parseInt(number.getText());
                for(int i=0; i<count; i++) {
                    text = new JTextField();
                    text.setBounds(50, y, 100, 40);
                    panel.add(text);
                    y=y+50;
                }

            }

            @Override
            public void keyReleased(KeyEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void keyTyped(KeyEvent e) {
                // TODO Auto-generated method stub

            }

        });

        panel.add(number);
        container.add(panel);

    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Example example = new Example();
        example.setVisible(true);
    }

}

如您所见,我正在尝试将其他 TetxFields 放在面板上,但是当我在 Textfield 上放置一些数字时,我有一个例外,例如
java.lang.NumberFormatException: For input string: "".

但我实际上已经将 String 更改为 int。

标签: javaswingjtextfieldnumberformatexception

解决方案


推荐阅读