Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

JComboBox used to update a JLabel

Hi Folks,

I have a Combo box, with a list of contact names... When I select a name from the combo box it currently prints the selected name into my JAva Console. So I know the actionPerfomed and SetActionCommand etc... are all wired up correctly.

What I would like it to do is rather than print the name to the console. I'd like it to update a JLabel. (that is currently, intentionally blank, for this purpose)

Heres some code snippets that I hope help you understand what I have done so far.

**THIS IS FROM MY CONTROLLER CLASS**

public synchronized void actionPerformed (ActionEvent event) {

String command = event.getActionCommand();

JLabel nameFillLabel = new JLabel(); // not sure why put this here

if(command.equals("recipientName")){
JComboBox cb = (JComboBox)event.getSource();
String combName = (String)cb.getSelectedItem();
System.out.println(combName); // prints selected item to console
nameFillLabel.setText(combName); // doesnt actually do anything
}

}

***THIS IS FROM MessagerUI class***

private JComboBox recipientCombo = null;
private JLabel nameFillLabel = null;
...
recipientCombo = new JComboBox(names);
nameFillLabel = new JLabel();
...
recipientCombo = new JComboBox(names);
recipientCombo.setActionCommand("recipientName");
...

public void setActionListener(ActionListener sendActionEventsHere){
recipientCombo.addActionListener(sendActionEventsHere);

}

I'm new to this and I think to problem may have something to do with me trying to update a JLabel thats contained within another class, if so how do I resolve this Issue, Any advice would be greatly appreciated.

Thanks in Advance

Regards

Terry
[1939 byte] By [Tehee2000] at [2007-11-11 7:41:01]
# 1 Re: JComboBox used to update a JLabel
The label should be created prior to the event. If the label and the eventhandler are contained in different classes you can get this done in many ways. I prefer this one:

The class containing the eventhandler gets the pointer to the class containing the label as a contructor parameter (or a setter method) and the class with the label has a public method for setting the label value.

The class with the label

public class AClass {
private JLabel aLabel=new JLabel();
.
(place the label somewhere...)
.
public void setComboLabelValue(String s) {
aLabel.setText(s);
}

}

The eventhandler class' constructor would then be like:

public class ControllerClass {
private AClass ac=null;
public ControllerClass (AClass ac) {
this.ac=ac;
}
.
.
public synchronized void actionPerformed (ActionEvent event) {
String command = event.getActionCommand();
if(command.equals("recipientName")){
JComboBox cb = (JComboBox)event.getSource();
String combName = (String)cb.getSelectedItem();
System.out.println(combName); // prints selected item to console
ac.setComboLabelValue(combName); // voila !

.
.
.
sjalle at 2007-11-11 22:37:36 >