easy question

K

koko

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?
 
J

Jeroen V.

What would you do to cause a repaint with the new components at this
....

container =
someFrameYouHaveToCreateAndConfigureBeforeLikeInTheJavaSwingTutorial.getRootPane();
 
K

koko

thanks and yes it is hw... however, i am getting an error stating my
container cannot be resolved. not sure how to fix that. thanks for
the link - lots of good info.
 
J

Jeffrey Schwab

Mark said:
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_CLOSE);
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);
}
});
}
}
 
A

Alan Krueger

Jeffrey said:
At the risk of robbing "koko" of a proper education: [...]
class TextRabbit {

Since this was Koko, you should have named it FuzzyKitten or something.
 
J

Jeroen V.

koko said:
thanks and yes it is hw... however, i am getting an error stating my
container cannot be resolved. not sure how to fix that. thanks for
the link - lots of good info.
I meant frame.getContentPane()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top