1

In my Java app i'm having a complex GUI which has certain JPanel (custom control) repeated, lets say, 100 times (in reality it could be more, but i don't wanna make this example too complex). Each of those 100 JPanels contains 4 JTextBox controls that show certain values to the users.

JTextBoxes of one panel may be empty, while in another only one may have a value, in some other all boxes may show some numbers and you get the idea - i don't know upfront which textbox of which panel will contain which data.

Now, in order to reduce memory footprint i started learning about the Flyweight design pattern. It seems like exactly the thing i need but, if i keep one JPanel as a seed, and use it to represent other 99 panels (just changing the JTextBox values accordingly) it means all those panels will share the common reference.

In that case, changing JTextBox values in one of them would also change value in all others, right? How to overcome this problem and still keep the memory footprint of the application low?

Am i missing something?

guest86
  • 2,894
  • 8
  • 49
  • 72
  • Yes, this question is simplified. In my real-world application users must have overview of all possible data they currently have stored – guest86 Jul 27 '17 at 18:04
  • 1
    What is a "JTextBox"? Please be more concrete with your description of your need. Swing already has lightweight renderer type components such as a JTable, but it's hard to know if that would suit your need. – Hovercraft Full Of Eels Jul 27 '17 at 18:07
  • You might want do some research into MVC – MadProgrammer Jul 27 '17 at 21:26
  • Sorry for delay. No, i'm not actually trying to create a spreadsheet. Those panels have some special functions, usually they are shown in group of couple, but in a certain "history" window i have to show actually a full list containing those panels stack one top of each other. – guest86 Jul 27 '17 at 22:34

1 Answers1

2

Many existing Swing components, including JList, JTable and JTree, use the flyweight pattern to render and edit cells. In this JTable example, StatusPanel contains a ButtonGroup with several instances of JRadioButton reflecting the chosen value from enum Status. A single instance of StatusRenderer renders the TableModel status for a given row in the status column. Similarly, a single instance of StatusEditor allows updating the TableModel status for a given row in the status column. In particular, only the TableModel actually stores data between view updates; the renderer and editor are reused for each row.

image

If you can't use an existing flyweight component, this answer outlines the approach, includes a complete example and cites a helpful tutorial.

image

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • See also [`BasicTableUI`](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/javax/swing/plaf/basic/BasicTableUI.java), which uses a `CellRendererPane` in `paintCell()`. – trashgod Jul 29 '17 at 16:01