Question

Im making a inventory class where buttons are added to a jpanel inside a scroll pane, and using GridBagConstarints the buttons are automatically alligned. The buttons m adding, and basically just one single class titled ranodomButton that extends JButton. The size, color, text, etc. is defined in this class. Then in the main class i use:

randomButton b = new randomButton();

I then use:

panelName.add(b, gridBagConstrainntsName);

I basically want to run this line of code multiple times, but the problem is it deletes the previous button, im guessing due to it being the same thing, that being the same "Instance"? of randomButton. I can simply make many buttons, and add then and its fine, but if i try to add 2 of the same i get an error. Ive tried setting b = to another JButton, and it still only uses one. Any solutions?

Was it helpful?

Solution

Any solutions?

As you have already stated, "I can simply make many buttons". This is probably the easiest solution (without knowing your exact requirment) and there is no reason you can't do this as you can always share an ActionListener between all buttons so you don't have to create multiple listeners.

Or for something completely different you can create a JTable to display your data in a grid. A JTable uses a renderer to paint buttons, so you just add the data to the TableModel. Read the section from the Swing tutorial on How to Use Tables for more information. But this brings in additional complexity in terms of handling the color and size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top