Linking Swing Components - java

My GUI
I need some kind of foreach loop to go through all of the components in the content pane and add the values into a map.
HashMap<String, String> items = new HashMap<String, String>();
The String from the Drop Down box will be the Key and the value will be the contents of the Day and Week JTextField components (maybe with a ';' so I can split later).
So far I can't figure out how to link the components together or if that is even possible (even if there is a hacky way around it).

Assuming that all your components are inside JPanel you can try this:
for(Component comp : jPanel1.getComponents()){
if(comp instanceof JComboBox){
JComboBox cb = (JComboBox)comp;
System.out.println("cb.getName() = "+cb.getName());
System.out.println("cb.getSelectedItem() = "+cb.getSelectedItem());
}
}

Related

How to set the text of a swing label, using a string variable as the name of the label?

I have a string such as:
String labelName = "lblColaStock";
Which is also the name of a Swing label. I would like to setText() on this label. Something like:
labelName.setText("some text");
However, the labels and strings can be different each execution. One time it may be:
String labelName = "lblColaDietStock";
And now the label I want to change is called lblColaDietStock.
How can I change a label's text, using a string variable as the label name?
As i can understand your question you need to create mapping where keys are numbers and values are labels.
Code will be like that:
JLabel label = //label variable
Map<Integer, JLabel> map = new HashMap<>();
map.put(1, label);
map.get(1).setText("label text");
In your code you have 2 mistakes, first is you missed up keys and values in map declaration, even if you did not do it you get String from map and try to invoke method setText() on it. myMap.get(1).setText("some text"); this is second mistake.
Probably you mean something like this:
Jlabel jLabel = new JLabel();
String labelName = "lblColaStock";
HashMap<String,JLabel> myMap = new HashMap();
myMap.put(labelName,jLabel);
myMap.get(labelName).setText("some text");

Is there another way to remove all items of a JComboBox then removeAllItems()?

Is there another way to remove all items of a JComboBox then removeAllItems()? I use 2 JComboBoxes in mij app and when you select an item from the first combobox the related items should then be shown in the second combobox. When I do this, the items just keep appending after the ones that were already there. When I then first try to clear the combobox by using removeAllItems(), the second combobox is empty and stays empty whenever I change the first combobox... The first combobox keeps all its values... Does anyone see my problem?
festival is the JComboBox:
private JComboBox festival;
private JComboBox zone;
...
public void fillFestivalList(){
festival.removeAllItems();
List festivals = OP.fillFestivalList();
for(Object fest: festivals)
festival.addItem(fest.toString());
}
public void fillZoneList(String festival){
zone.removeAllItems();
List zones = OP.fillZoneList(festival);
for(Object zoneItem: zones)
zone.addItem(zoneItem.toString());
}
Regarding,
Is there another way to remove all items of a JComboBox then removeAllItems()?
Simply give the JComboBox a new model.
I would create a new DefaultComboBoxModel<T>, fill it with the newest entries, and then call setModel(...) on my JComboBox, passing in the new model when desired.
You can also Remove all the items in this way ,
but better to Give JCombobox a new DefaultComboBoxModel like the way #Hovercraft Full Of Eels said
int itemCount = combo.getItemCount();
for(int i=0;i<itemCount;i++){
combo.removeItemAt(0);
}

How to select multiple JCheckBoxe into ButtonGroup?

I have three JCheckBox like following:
final JCheckBox c1 = new JCheckBox("A");
final JCheckBox c2 = new JCheckBox("B");
final JCheckBox c3 = new JCheckBox("C");
I make a group by ButtonGroup for this checkboxes like following:
final ButtonGroup bg = new ButtonGroup();
bg.add(c1);
bg.add(c2);
bg.add(c3);
I have a Button to display selected items into a label like following:
String SelectedItem="";
Enumeration<AbstractButton> items= bg.getElements();
while (items.hasMoreElements()) {
AbstractButton btn = items.nextElement();
if(btn.isSelected())
{
SelectedItem+=btn.getText()+",";
}
}
lblA.setText(SelectedItem);
this work fine , but i cann't select multiple check boxes in run time.
The purpose of ButtonGroup is multiple-exclusive selection. Do not create ButtonGroup only if you want to have a collection of your buttons. Instead of ButtonGroup use a standard collection like ArrayList.
List<JCheckBox> buttons = new ArrayList<>();
buttons.add(c1);
buttons.add(c2);
buttons.add(c3);
...
for ( JCheckbox checkbox : buttons ) {
if( checkbox.isSelected() )
{
SelectedItem += btn.getText() + ",";
}
}
Further notices: do updates (.setText) in Swing event thread (invokelater), remeber that it is better to create StringBuilder in such concatenation, but with UI component quantities like this, performance impact propably will be not noticeable.
From documentation:
Class ButtonGroup
This class is used to create a multiple-exclusion scope for a set of
buttons. Creating a set of buttons with the same ButtonGroup object
means that turning "on" one of those buttons turns off all other
buttons in the group.
That said, you probably are using the wrong class to do what you need, if you want to GROUP those checkboxes, put them in a panel, than you can work visibility, position and all other attributes with the panel instead of each checkbox.
Here is the link to documentation: Link

Java modify vector items

I am using a vector to add my JList items to like below
public void addToList() {
Icon pingImage = new javax.swing.ImageIcon(getClass().getResource("/resources/icnNew.png"));
JLabel pingLabel = new JLabel("ID #231231", pingImage, JLabel.LEFT);
JPanel pingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
pingPanel.add(pingLabel);
v.add(pingPanel);
menuList.setListData(v);
}
My Requirement is to update items within the vector depending on their ID. For example : On the above, i would like to change the ImageIcon for the ID #231231.
How could this be done?
As already said in the comments to your question, a Vector is the wrong data structure. Doing updates based on an identifier is asking for a Map. I would recommend against iterating through a list, looking for matching labels, since its an O(n) instead of O(log n) operation.

JTable doesn't add header row

I try to add header row to my JTable and next put table on panel.
This is my sample code :
Map <String, Float> tmpCart = new HashMap<String , Float>();
MainPanel.removeAll();
MainPanel.repaint();
tmpCart = cart.GetMap();
DefaultTableModel tab = new DefaultTableModel();
tab.setColumnIdentifiers(new String[] {"Name", "Price"});
for (String key : tmpCart.keySet())
tab.addRow(new Object[] {key, tmpCart.get(key)});
JTable jTab = new JTable(tab);
jTab.setBounds(10, 10, 200, 200);
jTab.setBackground(Color.orange);
jTab.setRowHeight(25);
JScrollPane pan =new JScrollPane(jTab);
MainPanel.add(pan);
// MainPanel.add(jTab);
// pan.repaint();
How do I write it properly?
//answer
I try create JTable dynamically, after push button, I want get data from Hashtable, create table and put this table on panel.
First step is remove all components from panel, and next create JTable using data from Hashmap`
full function:
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {
Map <String, Float> tmpCart = new HashMap<String , Float>();
MainPanel.removeAll();
MainPanel.repaint();
tmpCart = cart.GetMap();
DefaultTableModel tab = new DefaultTableModel();
tab.setColumnIdentifiers(new String[] {"Name", "Price"});
for (String key : tmpCart.keySet())
tab.addRow(new Object[] {key, tmpCart.get(key)});
JTable jTab = new JTable(tab);
jTab.setBounds(10, 10, 200, 200);
jTab.setBackground(Color.orange);
jTab.setRowHeight(25);
// MainPanel.add(pan);
MainPanel.add(jTab);
}
This code works, create table and put it on panel, but doesn't set first row with column names ( text : "Names" and "Price").
Can't tell exactly what you are doing from the code sample.
If you are trying to dynamically update a table on a visible GUI, then there is not need to create a new table, just reset the TableModel.
table.setModel( model );
If you need more help then post your SSCCE that demonstrates the problem.
Edit:
First step is remove all components from panel,
Why are your removing components from the panel?
If you need to "swap" panels, then use a CardLayout.
If you need to "refresh" existing components, then just reset the model as explained above.
// MainPanel.add(pan);
MainPanel.add(jTab);
The scrollPane should be added to the GUI, not the table.
The table header is another component that only gets added automatically when the table is inside a JScrollPane. Your best bet is to create a JScrollPane via
new JScrollPane(table)
and add that to your MainPanel.
The other option is to added the header directly wherever you want it, and for that you can do:
panel.add(table.getTableHeader())
Try putting it into a JScrollPane.

Categories