aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Adding a New JComponent on a Button Click Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Adding a New JComponent on a Button Click" Watch "Adding a New JComponent on a Button Click" New topic
Author

Adding a New JComponent on a Button Click

Rohit Kedia
Ranch Hand

Joined: Apr 24, 2010
Posts: 79
Hi,
Can anyone throw some light on how can I work on this Situation.
Which is : Every time I click on a button I need to add a JLabel & Jtextbox and secondly this section should be scrollable as I can add multiples of them.
Thirdly how will I fetch the values from the individual textboxes.

Please help me out.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

You can go two ways:

1) use a layout manager that supports "rows", like GridLayout or GridBagLayout. During runtime create a JLabel and JTextField, add them to the parent container (a JPanel most likely), call revalidate() and repaint() on that parent container to update the user interface. Store the JTextFields in a java.util.List<JTextField> to keep an indexed reference to them. To get the content of the text field of row 5 (starting at 0) you simply use textFieldList.get(5).getText().

2) use a JTable with a custom sub class of DefaultTableModel. isCellEditable returns false for colum 0 (the label) and true for column 1 (the text field). Adding a row is simply adding a row to the DefaultTableModel. To get the content of the text field of row 5 (starting at 0) you simply use (String)model.getValueAt(5, 1).

Either way, the parent container of JTable should be put in a JScrollPane to add scrolling functionality.

Option 2 is slightly easier to implement since you don't have to worry about the layout manager but has the drawback that you have to double click on a "text field" before you can start editing. You also cannot use tab to go from one "text field" to the next.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4522
    
    5

Rohit Kedia wrote:Every time I click on a button I need to add a JLabel & Jtextbox

What's a Jtextbox?


luck, db
There are no new questions, but there may be new answers.
Rohit Kedia
Ranch Hand

Joined: Apr 24, 2010
Posts: 79
Sir ,
JTextBox is another TextField Component.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Adding a New JComponent on a Button Click
 
Similar Threads
How do i create dynamic input fields after click a button?
Dynamically adding values to a Drop down menu
java/html how to add fields when we click button
storing dynamic row value to database
how to pass this value