Reputation: 1496
I have two ArrayLists called keys and values.
keys = {"cat", "dog", "mouse"}
values = {"furry;white", "greyhound;beast", "little;rat"}
I would like to have them printed in a JTextArea (since I want them to be editable) or any other GUI component like this:
------------------
cat | furry
| white
-------------------
dog | greyhound
| beast
-------------------
mouse | little
| rat
Should I create a new TextArea dynamically for each entry? If so how do I do that? Is that the right approach?
I have already tried using JTable but the issue with that is the cell height is fixed and text wrapping is a mess.
Upvotes: 0
Views: 714
Reputation: 7730
You can use GridLayout
Map<String,String> map=new HashMap<String,String>(); //key-Value pair
map.put("cat",""furry\n white"); // \n So that you will get a new line character in text area
map.put("dog","greyhound \n beast");
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(rows,columns));//In your case (map.size,2)
frame.setSize(300, 300);
//Now You need to Iterate through the Map.
for(Map.Entry<String,String>entry:map.entrySet()){
JTextArea left=JTextArea(entry.getKey());
JTextArea right=JTextArea(entry.getValue());
frame.add(left); //Adding each key to the Frame on left side
frame.add(right); //This is the value you want in side of key
}
frame.setVisible(true);
You will get something like this but in editable format
I have two ArrayLists called keys and values.
keys = {"cat", "dog", "mouse"} values = {"furry;white", "greyhound;beast", "little;rat"}
As you can see you are maintaining the List of keys and value seperately which is a bad practice , you can have Map (just read this link, it wil be helpfull) which stores the key
and it's corresponding value
in a single record ,
Now A little Suggestion
If you want to use multiple values
against one key
I suggest you to use MultiMap which maintains multiple values against one single key , It's very usefull library .
Upvotes: 2
Reputation: 27956
I would suggest having separate JTextField
instances for each editable field and then lay them out using a GridLayout
. Your code would end up something like this method to create a panel with the fields in it.
public JPanel createPanelForStringMap(Map<String, String> map) {
JPanel panel = new JPanel(new GridLayout(map.size(), 2));
for (Map.Entry entry: map.entrySet()) {
panel.add(new JTextField(entry.getKey()));
panel.add(new JTextField(entry.getValue()));
}
return panel;
}
Naturally you'd need to add code to do something with the values once they've been edited.
Upvotes: 2