everytime i click on a JList item, i need to clear + refresh my current panel & load another panel, returned via method 'populateWithButtons()'. temp is an int variable that stores what was clicked at the JList. How do i rectify the following?
list_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
//refresh + populate JPanel
Food food = new Food();
JPanel panel2 = new JPanel();
JPanel pane11 = new JPanel();
panel2.add(panel1);
panel1.validate();
panel1.repaint();
panel1.setBounds(153, 74, 281, 269);
panel1.add(food.populateWithButtons(temp));
contentPane.add(panel2);
}
move
validate()
andrepaint()
after adding tocontentPane
as in that point it will be redrawed.Use correct architecture pattern - like MVC. Basic usage example you have here.
MouseAdapter
will update variable of selected item inmodel
and refresh view withrepaint()
method (instead working directly on GUI).JPanel
with overridepaint()
method that shows content according to selected element in model.You will thank me later. ;) In your approach you will lose flexibility and come back with another problem soon.
Bad way (but will work)
MouseAdapter
(or other listener) hold reference to that view.mouseClicked()
method create a new panel and then override old with setter.don't to use NullLayout
add ListSelectionListener to JList instead of MouseListener, otherwise you would need to convert point from mouse to Item in JList
use CardLayout instead of add, remove JPanels on runtime, then selection from
ListSelectionListener
(ListSelectionModel
toSINGLE
...) to switch prepared card (JPanel
with some contents)EDIT
.
.