当另一个TextField中有多个TextField时,如何自动将其放置在面板上?我尝试使用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);
}
}
如您所见,我正在尝试在面板上放置其他TetxField,但是当我在Textfield上放置一些数字时,我会遇到异常,例如
java.lang.NumberFormatException: For input string: ""
。
但是我实际上已经将String更改为int。