• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding a New JComponent on a Button Click

 
Rohit Kedia
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Darryl Burke
Bartender
Posts: 5125
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rohit Kedia wrote:Every time I click on a button I need to add a JLabel & Jtextbox

What's a Jtextbox?
 
Rohit Kedia
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sir ,
JTextBox is another TextField Component.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic