Forum Stats

  • 3,837,196 Users
  • 2,262,234 Discussions
  • 7,900,219 Comments

Discussions

Create a JDialog with with changeable number of components

807569
807569 Member Posts: 34,691
edited May 15, 2006 10:35AM in Java Programming
Hi,

I want to create a JDialog with a list of JTextField's in it. There will be two buttons on also. One plus (+) button and one minus (-) button. When pressed, the window should repaint with one JTextField more or less. There will be also othe componets on the JDialog, all in a GridBagLayout. For the moment, I have something like this:
private int number;

public Test() {
    number = 4;
    initializeComponent();
    pack();
}

private void initializeComponent() {
    GridBagLayout gbl = new GridBagLayout();
    setLayout(gbl);
    GridBagConstraints gbc = new GridBagConstraints();
    // ...
    for(int i = 0; i <= number; i++) {
        gbc.gridy = i;
        gbc.gridx = 1;
        JTextField temp = new JTextField(1);
        gbl.setConstraints(temp, gbc);
        add(temp);
    }
    //....
}

// called when one of the buttons is pressed
private void changeNr(boolean plus) {
   if(plus) {
        number++;
    } else if(number > 1) {
        number--;
    }
    btn_min.setEnabled(nr > 1);

    // DOESN'T SEEM TO WORK ?!
    repaint();        
}

Comments

  • 807569
    807569 Member Posts: 34,691
    I think you're misunderstanding the notion of repainting. Repainting will not cause it to call your initializeComponent() method, it will simply repaint the window which is already displaying.

    To add a new button at runtime, you need to do something like...
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridy = i;
    gbc.gridx = 1;
    JTextField temp = new JTextField(1);
    add(temp, gbc);
    pack();
    That should work in theory, but no guarantees that it's bugless. Removing a text field is similar but you have to know what you're removing. Keep a List of all these JTextFields, so that you can remove them later.
This discussion has been closed.