SlideShare a Scribd company logo
Convert the following program so that it uses JList instead of JComboBox.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import javax.swing.*;
public class ShoppingList extends JFrame {
private static final long myShoppingList = 1L;
// Constants for window width and height
private final int WINDOW_WIDTH = 700;
private final int WINDOW_HEIGHT = 250;
private JTextField shoppingList;
// Buttons for Save, Add, Remove, and Load features.
private JButton Save;
private JButton Add;
private JButton Remove;
private JButton Load;
// Panels for the button groups
private JPanel textfieldPanel;
private JPanel buttonPanel;
private JComboBox itemList;
/**
* CONSTRUCTOR
*/
public ShoppingList() {
// Window title
setTitle("Shopping List");
// Set size
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
// Default close operation
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Calling buildPanel method
buildPanels();
// Grid Layout
setLayout(new FlowLayout());
// Adding the panel to JFrame
add(textfieldPanel);
add(buttonPanel);
// Visibility
setVisible(true);
}
// Building the Panels,
private void buildPanels() {
// Initializing the Textfield
shoppingList = new JTextField(20);
// Initializing the Buttons
Save = new JButton("Save");
Add = new JButton("Add");
Remove = new JButton("Remove");
Load = new JButton("Load");
// Associating action listener
Add.addActionListener(new AddButtonListener());
Save.addActionListener(new SaveButtonListener());
Remove.addActionListener(new RemoveButtonListener());
Load.addActionListener(new LoadButtonListener());
try {
itemList = new JComboBox<>(fileToArray());
} catch (IOException e) {
itemList = new JComboBox<>();
}
itemList.setPreferredSize(new Dimension(10,20));
// Initializing the panels
textfieldPanel = new JPanel();
buttonPanel = new JPanel();
// Seting borders of the panels
textfieldPanel.setBorder(BorderFactory
.createTitledBorder("Shopping List"));
buttonPanel.setBorder(BorderFactory.createTitledBorder("Process"));
// Adding the objecs to the respective panels
textfieldPanel.setLayout(new BoxLayout(textfieldPanel, BoxLayout.Y_AXIS));
textfieldPanel.add(shoppingList);
textfieldPanel.add(itemList);
buttonPanel.add(Save);
buttonPanel.add(Add);
buttonPanel.add(Remove);
buttonPanel.add(Load);
}// End buildPanels
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent addaction) {
if (!shoppingList.getText().trim().equals(""))
itemList.addItem(shoppingList.getText().trim().toLowerCase());
}
}//end listener
private class RemoveButtonListener implements ActionListener {
public void actionPerformed(ActionEvent removeaction) {
if (itemList.getItemCount() > 0)
itemList.removeItemAt(itemList.getSelectedIndex());
else {
JOptionPane.showMessageDialog(null, "Please select an item to delete!");
}
}
}//end listener
private class SaveButtonListener implements ActionListener {
public void actionPerformed(ActionEvent saveaction) {
try {
writeToFile();
}
catch (Exception n) {
System.out.println("File not created!");
}
}
}//end listener
private void writeToFile() throws FileNotFoundException, IOException {
PrintWriter inFile = new PrintWriter(new File("list.txt"));
FileWriter writer = (new FileWriter("list.txt", true));
writer.write(shoppingList.getText().trim().toLowerCase());
writer.write(" ");
writer.close();
inFile.close();
}
private class LoadButtonListener implements ActionListener {
public void actionPerformed(ActionEvent loadaction) {
try {
for (String item : fileToArray()) {
itemList.addItem(item);
}
}
catch (Exception o)
{
JOptionPane.showMessageDialog(null, "Error opening data file");
}
}
}//end listener
private String[] fileToArray() throws IOException {
Path filePath = new File("list.txt").toPath();
Charset charset = Charset.defaultCharset();
List stringList = Files.readAllLines(filePath, charset);
return stringList.toArray(new String[] {});
}
public static void main(String[] args) throws IOException {
new ShoppingList();
}
}// end main
Solution
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JPanel implements ActionListener
{
private JComboBox mainComboBox;
private JComboBox subComboBox;
private Hashtable subItems = new Hashtable();
public ComboBoxTwo()
{
String[] items = { "Select Item", "Color", "Shape", "Fruit" };
mainComboBox = new JComboBox( items );
mainComboBox.addActionListener( this );
// prevent action events from being fired when the up/down arrow keys are used
mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
add( mainComboBox );
// Create sub combo box with multiple models
subComboBox = new JComboBox();
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
add( subComboBox );
String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
subItems.put(items[1], subItems1);
String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
subItems.put(items[2], subItems2);
String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
subItems.put(items[3], subItems3);
}
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new ComboBoxTwo() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}

public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

More Related Content

PDF
This is a java lab assignment. I have added the first part java re.pdf
PDF
Develop an inventory management system for an electronics store. The .pdf
PDF
import javaawt import javaxswing import javaxswing.pdf
PDF
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
DOCX
Final_Project
DOCX
c++main.cpp#include iostream#include store.h#includ.docx
PDF
AnswerNote programming specifications and the printing statement.pdf
DOCX
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx
This is a java lab assignment. I have added the first part java re.pdf
Develop an inventory management system for an electronics store. The .pdf
import javaawt import javaxswing import javaxswing.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!How can I make the add but.pdf
Final_Project
c++main.cpp#include iostream#include store.h#includ.docx
AnswerNote programming specifications and the printing statement.pdf
codeComprehensionorders.txtwomens sandals 1011 6 78.00 red 12.docx

More from bermanbeancolungak45 (20)

PDF
Write a program that randomly generates a maze in javaSolution.pdf
PDF
why is the idea of a standard network protocol such as the OSI refer.pdf
PDF
Which of the following potential problems need not be considered whe.pdf
PDF
Which of the following is true of mutations They are very common T.pdf
PDF
What type of security vulnerability are developers most likely to in.pdf
PDF
What is the purpose of database administration2. What is the purp.pdf
PDF
what is code to draw sun and earth and the moon in java OpenGLS.pdf
PDF
What factors do you think make them excellent project reports write.pdf
PDF
What aspects of todays information economy have influenced the imp.pdf
PDF
This week, we are going to work together as a class to assist the Lon.pdf
PDF
The phylogenetic species concept looks at environmental adaptations a.pdf
PDF
The percentage of high school students who drink and drive was 17.5.pdf
PDF
Take a position on this statement The media represent realistic ima.pdf
PDF
Suppose 60 different survey organizations visit eastern Tennessee to.pdf
PDF
Relate selected early morphological developments in the ancestors of.pdf
PDF
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
PDF
question - Jurassic Park (book and movie) proposed the concept of.pdf
PDF
Python programming question Assume that a file containing a serie.pdf
PDF
Prior to the development of anti-retroviral drugs, HIV infected pati.pdf
PDF
Please this is my second time posting. I really need the right answe.pdf
Write a program that randomly generates a maze in javaSolution.pdf
why is the idea of a standard network protocol such as the OSI refer.pdf
Which of the following potential problems need not be considered whe.pdf
Which of the following is true of mutations They are very common T.pdf
What type of security vulnerability are developers most likely to in.pdf
What is the purpose of database administration2. What is the purp.pdf
what is code to draw sun and earth and the moon in java OpenGLS.pdf
What factors do you think make them excellent project reports write.pdf
What aspects of todays information economy have influenced the imp.pdf
This week, we are going to work together as a class to assist the Lon.pdf
The phylogenetic species concept looks at environmental adaptations a.pdf
The percentage of high school students who drink and drive was 17.5.pdf
Take a position on this statement The media represent realistic ima.pdf
Suppose 60 different survey organizations visit eastern Tennessee to.pdf
Relate selected early morphological developments in the ancestors of.pdf
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
question - Jurassic Park (book and movie) proposed the concept of.pdf
Python programming question Assume that a file containing a serie.pdf
Prior to the development of anti-retroviral drugs, HIV infected pati.pdf
Please this is my second time posting. I really need the right answe.pdf
Ad

Recently uploaded (20)

PDF
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
PPTX
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
master seminar digital applications in india
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PDF
Classroom Observation Tools for Teachers
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
ChatGPT for Dummies - Pam Baker Ccesa007.pdf
UV-Visible spectroscopy..pptx UV-Visible Spectroscopy – Electronic Transition...
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
master seminar digital applications in india
UNIT III MENTAL HEALTH NURSING ASSESSMENT
Classroom Observation Tools for Teachers
Yogi Goddess Pres Conference Studio Updates
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Anesthesia in Laparoscopic Surgery in India
Weekly quiz Compilation Jan -July 25.pdf
01-Introduction-to-Information-Management.pdf
2.FourierTransform-ShortQuestionswithAnswers.pdf
Final Presentation General Medicine 03-08-2024.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
RMMM.pdf make it easy to upload and study
LDMMIA Reiki Yoga Finals Review Spring Summer
Ad

Convert the following program so that it uses JList instead of JComb.pdf

  • 1. Convert the following program so that it uses JList instead of JComboBox. import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import javax.swing.*; public class ShoppingList extends JFrame { private static final long myShoppingList = 1L; // Constants for window width and height private final int WINDOW_WIDTH = 700; private final int WINDOW_HEIGHT = 250; private JTextField shoppingList; // Buttons for Save, Add, Remove, and Load features. private JButton Save; private JButton Add; private JButton Remove; private JButton Load; // Panels for the button groups private JPanel textfieldPanel; private JPanel buttonPanel; private JComboBox itemList; /** * CONSTRUCTOR */ public ShoppingList() { // Window title setTitle("Shopping List"); // Set size setSize(WINDOW_WIDTH, WINDOW_HEIGHT); // Default close operation
  • 2. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Calling buildPanel method buildPanels(); // Grid Layout setLayout(new FlowLayout()); // Adding the panel to JFrame add(textfieldPanel); add(buttonPanel); // Visibility setVisible(true); } // Building the Panels, private void buildPanels() { // Initializing the Textfield shoppingList = new JTextField(20); // Initializing the Buttons Save = new JButton("Save"); Add = new JButton("Add"); Remove = new JButton("Remove"); Load = new JButton("Load"); // Associating action listener Add.addActionListener(new AddButtonListener()); Save.addActionListener(new SaveButtonListener()); Remove.addActionListener(new RemoveButtonListener()); Load.addActionListener(new LoadButtonListener()); try { itemList = new JComboBox<>(fileToArray()); } catch (IOException e) { itemList = new JComboBox<>(); } itemList.setPreferredSize(new Dimension(10,20)); // Initializing the panels textfieldPanel = new JPanel(); buttonPanel = new JPanel();
  • 3. // Seting borders of the panels textfieldPanel.setBorder(BorderFactory .createTitledBorder("Shopping List")); buttonPanel.setBorder(BorderFactory.createTitledBorder("Process")); // Adding the objecs to the respective panels textfieldPanel.setLayout(new BoxLayout(textfieldPanel, BoxLayout.Y_AXIS)); textfieldPanel.add(shoppingList); textfieldPanel.add(itemList); buttonPanel.add(Save); buttonPanel.add(Add); buttonPanel.add(Remove); buttonPanel.add(Load); }// End buildPanels private class AddButtonListener implements ActionListener { public void actionPerformed(ActionEvent addaction) { if (!shoppingList.getText().trim().equals("")) itemList.addItem(shoppingList.getText().trim().toLowerCase()); } }//end listener private class RemoveButtonListener implements ActionListener { public void actionPerformed(ActionEvent removeaction) { if (itemList.getItemCount() > 0) itemList.removeItemAt(itemList.getSelectedIndex()); else { JOptionPane.showMessageDialog(null, "Please select an item to delete!"); } } }//end listener private class SaveButtonListener implements ActionListener { public void actionPerformed(ActionEvent saveaction) { try { writeToFile(); } catch (Exception n) { System.out.println("File not created!");
  • 4. } } }//end listener private void writeToFile() throws FileNotFoundException, IOException { PrintWriter inFile = new PrintWriter(new File("list.txt")); FileWriter writer = (new FileWriter("list.txt", true)); writer.write(shoppingList.getText().trim().toLowerCase()); writer.write(" "); writer.close(); inFile.close(); } private class LoadButtonListener implements ActionListener { public void actionPerformed(ActionEvent loadaction) { try { for (String item : fileToArray()) { itemList.addItem(item); } } catch (Exception o) { JOptionPane.showMessageDialog(null, "Error opening data file"); } } }//end listener private String[] fileToArray() throws IOException { Path filePath = new File("list.txt").toPath(); Charset charset = Charset.defaultCharset(); List stringList = Files.readAllLines(filePath, charset); return stringList.toArray(new String[] {}); } public static void main(String[] args) throws IOException { new ShoppingList(); } }// end main Solution
  • 5. import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class ComboBoxTwo extends JPanel implements ActionListener { private JComboBox mainComboBox; private JComboBox subComboBox; private Hashtable subItems = new Hashtable(); public ComboBoxTwo() { String[] items = { "Select Item", "Color", "Shape", "Fruit" }; mainComboBox = new JComboBox( items ); mainComboBox.addActionListener( this ); // prevent action events from being fired when the up/down arrow keys are used mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); add( mainComboBox ); // Create sub combo box with multiple models subComboBox = new JComboBox(); subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4 add( subComboBox ); String[] subItems1 = { "Select Color", "Red", "Blue", "Green" }; subItems.put(items[1], subItems1); String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" }; subItems.put(items[2], subItems2); String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" }; subItems.put(items[3], subItems3); } public void actionPerformed(ActionEvent e) { String item = (String)mainComboBox.getSelectedItem(); Object o = subItems.get( item ); if (o == null) { subComboBox.setModel( new DefaultComboBoxModel() );
  • 6. } else { subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) ); } } private static void createAndShowUI() { JFrame frame = new JFrame("SSCCE"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add( new ComboBoxTwo() ); frame.setLocationByPlatform( true ); frame.pack(); frame.setVisible( true ); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } }