Mark Thomas wrote:
> Jeffrey Schwab wrote:
>> Mark Thomas wrote:
>>> Jeroen V. wrote:
>>>> koko wrote:
>>>>> how can I create a program that prompts a user to enter a number
>>>>> into a
>>>>> textfield and when they click a button they create that many more
>>>>> textfields?
>>>>>
>>>>
>>>> The question is the answer...
>>>>
>>>> Prob some homework?
>>>>
>>>> Have a look at
>>>> http://java.sun.com/docs/books/tutor...ing/index.html
>>>>
>>>> for(int i = 0; i < userInput; i++){
>>>> container.add(new JTextField());
>>>> }
>>> What would you do to cause a repaint with the new components at this
>>> point?
>>
>> pack()
>
> Would validate() be the way?
Depends what you want to do. If you call invalidate()/validate(), the
components will be laid out anew within their container, but the frame
won't be resized. At the risk of robbing "koko" of a proper education:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TextRabbit {
private JFrame frame = createFrame();
private JTextField createTextField() {
final JTextField field = new JTextField();
field.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int i = Integer.parseInt(field.getText());
while(--i >= 0) {
frame.add(createTextField());
}
} catch(NumberFormatException x) {
System.err.println("Exiting not-so-gracefully.");
System.exit(1);
}
frame.pack();
/* If you use in/validate() instead of pack(), you'll
* have to resize the frame manually to see the new
* text fields. */
// frame.invalidate();
// frame.validate();
}
});
return field;
}
private JFrame createFrame() {
JFrame frame = new JFrame("Text Rabbit");
frame.setContentPane(Box.createVerticalBox());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
frame.add(createTextField());
frame.pack();
return frame;
}
public void setVisible(boolean b) {
frame.setVisible(b);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextRabbit().setVisible(true);
}
});
}
}