SlideShare a Scribd company logo
1 of 6
Download to read offline
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

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

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
sotlsoc
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdf
adinathassociates
 
How do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfHow do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdf
forwardcom41
 
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdfimport java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
venkt12345
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
I hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdfI hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdf
apexelectronices01
 
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
mohammedfootwear
 
Android Studio Assignment HelpCan someone who is familiar with And.pdf
Android Studio Assignment HelpCan someone who is familiar with And.pdfAndroid Studio Assignment HelpCan someone who is familiar with And.pdf
Android Studio Assignment HelpCan someone who is familiar with And.pdf
feelinggift
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
Jussi Pohjolainen
 

Similar to Convert the following program so that it uses JList instead of JComb.pdf (20)

JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Using database in android
Using database in androidUsing database in android
Using database in android
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 
Java căn bản - Chapter12
Java căn bản - Chapter12Java căn bản - Chapter12
Java căn bản - Chapter12
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdf
 
How do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdfHow do I make my JTable non editableimport java.awt.; import j.pdf
How do I make my JTable non editableimport java.awt.; import j.pdf
 
GUI Programming with Java
GUI Programming with JavaGUI Programming with Java
GUI Programming with Java
 
Teste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrityTeste de Integração com DbUnit e jIntegrity
Teste de Integração com DbUnit e jIntegrity
 
Notepad
NotepadNotepad
Notepad
 
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdfimport java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
import java.awt.Color;import java.awt.Insets;import java.awt.Con.pdf
 
Java awt
Java awtJava awt
Java awt
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Maze
MazeMaze
Maze
 
I hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdfI hope the below code is helpful to you, please give me rewards.im.pdf
I hope the below code is helpful to you, please give me rewards.im.pdf
 
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdfPLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
PLEASE HELP ME !!IT IS Due Tonight ;(!i have to submit it before.pdf
 
Java Assignment Help
Java Assignment HelpJava Assignment Help
Java Assignment Help
 
Android Studio Assignment HelpCan someone who is familiar with And.pdf
Android Studio Assignment HelpCan someone who is familiar with And.pdfAndroid Studio Assignment HelpCan someone who is familiar with And.pdf
Android Studio Assignment HelpCan someone who is familiar with And.pdf
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
 

More from bermanbeancolungak45

Write a program that randomly generates a maze in javaSolution.pdf
Write a program that randomly generates a maze in javaSolution.pdfWrite a program that randomly generates a maze in javaSolution.pdf
Write a program that randomly generates a maze in javaSolution.pdf
bermanbeancolungak45
 
why is the idea of a standard network protocol such as the OSI refer.pdf
why is the idea of a standard network protocol such as the OSI refer.pdfwhy is the idea of a standard network protocol such as the OSI refer.pdf
why is the idea of a standard network protocol such as the OSI refer.pdf
bermanbeancolungak45
 
What is the purpose of database administration2. What is the purp.pdf
What is the purpose of database administration2. What is the purp.pdfWhat is the purpose of database administration2. What is the purp.pdf
What is the purpose of database administration2. What is the purp.pdf
bermanbeancolungak45
 
what is code to draw sun and earth and the moon in java OpenGLS.pdf
what is code to draw sun and earth and the moon in java OpenGLS.pdfwhat is code to draw sun and earth and the moon in java OpenGLS.pdf
what is code to draw sun and earth and the moon in java OpenGLS.pdf
bermanbeancolungak45
 
What factors do you think make them excellent project reports write.pdf
What factors do you think make them excellent project reports write.pdfWhat factors do you think make them excellent project reports write.pdf
What factors do you think make them excellent project reports write.pdf
bermanbeancolungak45
 
What aspects of todays information economy have influenced the imp.pdf
What aspects of todays information economy have influenced the imp.pdfWhat aspects of todays information economy have influenced the imp.pdf
What aspects of todays information economy have influenced the imp.pdf
bermanbeancolungak45
 
This week, we are going to work together as a class to assist the Lon.pdf
This week, we are going to work together as a class to assist the Lon.pdfThis week, we are going to work together as a class to assist the Lon.pdf
This week, we are going to work together as a class to assist the Lon.pdf
bermanbeancolungak45
 
Take a position on this statement The media represent realistic ima.pdf
Take a position on this statement The media represent realistic ima.pdfTake a position on this statement The media represent realistic ima.pdf
Take a position on this statement The media represent realistic ima.pdf
bermanbeancolungak45
 
Relate selected early morphological developments in the ancestors of.pdf
Relate selected early morphological developments in the ancestors of.pdfRelate selected early morphological developments in the ancestors of.pdf
Relate selected early morphological developments in the ancestors of.pdf
bermanbeancolungak45
 
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdfQuestion VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
Question VI. In 1976, Hozumi and Tonegawa published an elegant paper.pdf
bermanbeancolungak45
 
question - Jurassic Park (book and movie) proposed the concept of.pdf
question - Jurassic Park (book and movie) proposed the concept of.pdfquestion - Jurassic Park (book and movie) proposed the concept of.pdf
question - Jurassic Park (book and movie) proposed the concept of.pdf
bermanbeancolungak45
 
Prior to the development of anti-retroviral drugs, HIV infected pati.pdf
Prior to the development of anti-retroviral drugs, HIV infected pati.pdfPrior to the development of anti-retroviral drugs, HIV infected pati.pdf
Prior to the development of anti-retroviral drugs, HIV infected pati.pdf
bermanbeancolungak45
 
Please this is my second time posting. I really need the right answe.pdf
Please this is my second time posting. I really need the right answe.pdfPlease this is my second time posting. I really need the right answe.pdf
Please this is my second time posting. I really need the right answe.pdf
bermanbeancolungak45
 

More from bermanbeancolungak45 (20)

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

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Recently uploaded (20)

Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 

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(); } }); } }