Hey Everyone,
I'm not sure why but I can't seem to get my head around making comboboxes work. Everything works up to when I try to transfer a selected item from the combobox to the text field. What am I not doing?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestStore extends JFrame implements ActionListener
{
//Declare the textfield, textarea, and combobox
public JTextField jtfName;
public JTextArea jtaArea;
public JComboBox jcboBox;
public JButton jbtStore;
//Main Method
public static void main(
String[] args)
{
TestStore frame = new TestStore();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(500,300);
}
//Constructor
public TestStore()
{
setTitle("Test Store Button");
setBackground(Color.yellow);
setForeground(Color.white);
//Create panel p1 for textfield, area and combobox
JPanel p1 = new JPanel();
jcboBox = new JComboBox();
p1.setLayout(new FlowLayout());
p1.add(jtfName = new JTextField(15));
p1.add(jtaArea = new JTextArea(15, 15));
p1.add(jcboBox);
jtfName.setEditable(true);
//Create panel p2 for Store button
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jbtStore = new JButton("Store"));
//Set Panels in frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p1,BorderLayout.CENTER);
getContentPane().add(p2,BorderLayout.SOUTH);
//Register Listeners
jbtStore.addActionListener(this);
jcboBox.addActionListener(this);
}
//Transfer text from Field to Area and Combobox
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == jbtStore)
{
String name = (jtfName.getText());
//Set text in Area and Combobox
jtaArea.append(name + "\n");
jcboBox.addItem(name);
}
else if(e.getSource() == jcboBox);
{
String name = (String) jcboBox.getSelectedItem();
jtfName.add(name);
}
}
}
Thanks!
Marie