Code Completion 10.103 Customize greeting with combo box
Your task is to complete the following program so that the user can customize the greeting in the frame.
The user can select a combo box item or type in a new value.
Here is a sample program output:
Complete the following code:
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class HelloFrame extends JFrame { public HelloFrame() { comboBox = new JComboBox(); comboBox.addItem("public"); comboBox.addItem("static"); comboBox.addItem("void"); comboBox.setEditable(true); JPanel panel = new JPanel(); panel.add(comboBox); // add listener label = new JLabel("Hello, World!"); add(panel, BorderLayout.NORTH); add(label, BorderLayout.SOUTH); pack(); } private class ComboBoxListener implements ActionListener { public void actionPerformed(ActionEvent event) { // supply listener code } } private JComboBox comboBox; private JLabel label; }
The following class is used to check your work:
import javax.swing.JFrame; public class HelloViewer { public static void main(String[] args) { HelloFrame frame = new HelloFrame(); frame.setTitle("HelloViewer"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
Expert Answer
* JAVA program to use a combo box to cusyomize a greeting message
*/
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class HelloFrame extends JFrame
{
public HelloFrame()
{
comboBox = new JComboBox();
comboBox.addItem(“public”);
comboBox.addItem(“static”);
comboBox.addItem(“void”);
comboBox.setEditable(true);
JPanel panel = new JPanel();
panel.add(comboBox);
// add listener
comboBox.addActionListener(new ComboBoxListener());
label = new JLabel(“Hello, World!”);
add(panel, BorderLayout.NORTH);
add(label, BorderLayout.SOUTH);
pack();
}
class ComboBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// supply listener code
Object selected=comboBox.getSelectedItem(); //get the selected text from combobox
label.setText(“Hello, “+selected.toString()+” World!”); // change the label to insert selected text
}
}
private JComboBox comboBox;
private JLabel label;
}
/*The following class is used to check your work:*/
import javax.swing.JFrame;
public class HelloViewer
{
public static void main(String[] args)
{
HelloFrame frame = new HelloFrame();
frame.setTitle(“HelloViewer”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//——————————————————————————
output
———————-
on select public
on select void