Search code examples
javaswingactionlistenerjtextfieldjcombobox

Is there an way to remove a JTextFiled if a certain item in JComboBox is selected in java?


I have a registration panel where if student, instructor, and course administrator can register so if student is selected it should show something like this when Student is selected:

https://i.sstatic.net/cKrdf.png

and should show like this if other two are selected like this when any of other two are selected:

https://i.sstatic.net/Tpi1D.png

I tried using if condition on the selected item in where I have added those text fields but it seems it only works at the beginning of the program when I run it on the basis of what is pre-selected and does not change when I select other items in JComboBox. Is there a solution to this?


Solution

  • You can achieve this in different ways. One of such ways is to use Action Listeners. A JComboBox object generates an action event when a selection is made (see Handling Events on a Combo Box).

    In your case, you need to trigger an event based on the selection made in a combo box. This action should change the visibility of components in your panel, which are simply changing the visible attribute from true to false (or vice versa) depending on the selection made.