SlideShare a Scribd company logo
Java Program: Photo Viewer
1. Write an app called viewer that will have a Label at the top saying "My Viewer" (or
something like that)
2. Will have JButtons at the bottom that will do Next, Previous, and Quit
3. Have the whole middle be a JLabel in which you will display Images stored in a directory.
4. The directory can be named Resource.
5. When you run the program (java viewer) it will read all the names in the Resource Directory.
Then, when you click Next or Previous it will display an Image.
6. Note: you will need to find a java method that exists for reading a whole directory of
filenames. You can store all those names in a String Array when run the program.
7. You will use a counter or index that is an int an when you click Next it will increment the
counter until it reach some maximum value and then you will set it to 0. Previous will decrement
the counter until it goes negative and then it will set the counter to the Maximum index ( which
is how many filenames you have in the Image names array)
8. Submit the program viewer.java I should be able to use it with my own Resource directory.
Solution
Please refer this code for your application :
--------------------------------------------------------------------------------------------------------------------
--------------
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class ImageViewer extends javax.swing.JFrame {
public ImageViewer() {
initComponents();
listFiles(Path); //Lists all the files in the directory on window opening
setLabelIcon(Path,filenames[position]); //sets the label to display the first
//image in the directory on window opening.
PreviousButton.setEnabled(false);
}
/**
*Initialize components
*/
private void initComponents() {
setTitle("Image Viewer");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new java.awt.BorderLayout());// The layout is BorderLayout
//setBorder(javax.swing.BorderFactory.createEtchedBorder());
setBackground(java.awt.Color.GRAY);
picLabel = new javax.swing.JLabel(); //Create the Label to display the picture
picLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
picLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
PreviousButton = new javax.swing.JButton();
PreviousButton.setText("Previous");
PreviousButton.setIconTextGap(10); //Distance between the icon and text is 10
PreviousButton.addActionListener(new java.awt.event.ActionListener() { //Register an
actionListener for the PreviousButton
public void actionPerformed(java.awt.event.ActionEvent evt) {
PreviousButtonActionPerformed(evt);
}
});
NextButton = new javax.swing.JButton();
NextButton.setPreferredSize(PreviousButton.getPreferredSize());
NextButton.setText("Next");
NextButton.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
NextButton.setIconTextGap(10); //Distance between the icon and text is 10
NextButton.addActionListener(new java.awt.event.ActionListener() { //Registers an
actionListener for the NextButton
public void actionPerformed(java.awt.event.ActionEvent evt) {
NextButtonActionPerformed(evt);
}
});
javax.swing.Box vbox = javax.swing.Box.createVerticalBox(); //VerticalBox to hold the
pictureLabel and the buttons
vbox.add(javax.swing.Box.createVerticalStrut(30));
vbox.add(picLabel);
vbox.add(javax.swing.Box.createVerticalStrut(50));
javax.swing.JPanel prev_next_pane = new javax.swing.JPanel(); //Panel to hold the Previous and
Next buttons.
java.awt.FlowLayout flow = new java.awt.FlowLayout(java.awt.FlowLayout.CENTER);
flow.setHgap(30);
prev_next_pane.setLayout(flow);
prev_next_pane.add(PreviousButton);
prev_next_pane.add(NextButton);
prev_next_pane.setOpaque(false);
vbox.add(prev_next_pane); //Add the panel to the verticalBox
add(vbox);
java.awt.Toolkit theKit = getToolkit();
java.awt.Dimension size = theKit.getScreenSize();
setLocation(size.width/5,size.height/10);
setMinimumSize(new java.awt.Dimension(900,600));
//setMaximumSize(new Dimension(size.width/4 + 50,size.height/4));
}//END:initComponents
/**
*Handler for previous button
*/
private void PreviousButtonActionPerformed(java.awt.event.ActionEvent evt) {
position--; //Decrement the index position of the array of filenames by one on buttonPressed
if(!NextButton.isEnabled()){ //if NextButton is
NextButton.setEnabled(true); //disabled, enable it
}
if(position == 0){ //If we are viewing the first Picture in
PreviousButton.setEnabled(false); //the directory, disable previous button
}
setLabelIcon(Path,filenames[position]);
}//End of PreviousButton handler
/**
*Handler for NextButton
*/
private void NextButtonActionPerformed(java.awt.event.ActionEvent evt) {
position++; //Increment the index position of the array of filenames by one on buttonPressed
if(!PreviousButton.isEnabled()){
listFiles(Path);
PreviousButton.setEnabled(true);
}
if(position == filenames.length){
NextButton.setEnabled(false);
position --;
return;
}
setLabelIcon(Path,filenames[position]);
}//End of NextButton handler
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
}
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ImageViewer().setVisible(true);
}
});
}
/**Method to list all the files in the directory
*And store their names in an array
*/
private void listFiles(String Path){
File file = new File(Path);
filenames = file.list(); //store the file names in the array of strings.
for(String names : filenames){
System.out.println(names); //Print the filenames to the console just so you can see
}
}
//Method to set the picture on the label
private void setLabelIcon(String Path,String name){
File file = new File(Path+""+name);
java.awt.image.BufferedImage image = null;
try{
image = ImageIO.read(file); //Reas the image from the file.
}catch(IOException ie){
javax.swing.JOptionPane.showMessageDialog(this,"Error reading image file","Error",
javax.swing.JOptionPane.ERROR_MESSAGE);
}
ImageIcon icon = new ImageIcon(image);
int width = 600;
int height = 400;
Image img =
icon.getImage().getScaledInstance(width,height,java.awt.Image.SCALE_SMOOTH); //Images
produced will remain a fixed size, 600 * 400
ImageIcon newIcon = new ImageIcon(img); //Create a new imageicon from an image object.
//Now we want to create a caption for the pictures using their file names
String pictureName = file.getName();
int pos = pictureName.lastIndexOf("."); //This removes the extensions
String caption = pictureName.substring(0,pos); //from the file names. e.g .gif, .jpg, .png
picLabel.setIcon(newIcon); //Set the imageIcon on the Label
picLabel.setText(caption); //Set the caption
picLabel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); //Caption appears
below the image
}
//Variables declaration
int position = 0; //Initial position is 0
String[] filenames; //Array to hold the file names
final String Path = System.getProperty("user.home") +"User_Namepictures"; //path
to your images
private javax.swing.JButton NextButton;
private javax.swing.JButton PreviousButton;
private javax.swing.JLabel picLabel;
// End of variables declaration//GEN-END:variables
}//End of class
--------------------------------------------------------------------------------------------------------------------
--------------
feel free to reach out to me if you have any doubts in understanding this code. Keep learning :)

More Related Content

Similar to Java Program Photo Viewer1. Write an app called viewer that will .pdf

College management system.pptx
College management system.pptxCollege management system.pptx
College management system.pptx
ManujArora3
 
Program imageviewer
Program imageviewerProgram imageviewer
Program imageviewer
Fajar Baskoro
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-entechbed
 
Java Programming In this programming assignment, you need to impl.pdf
Java Programming In this programming assignment, you need to impl.pdfJava Programming In this programming assignment, you need to impl.pdf
Java Programming In this programming assignment, you need to impl.pdf
sanjeevbansal1970
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
briancrawford30935
 
Awt, Swing, Layout managers
Awt, Swing, Layout managersAwt, Swing, Layout managers
Awt, Swing, Layout managers
swapnac12
 
Struts database access
Struts database accessStruts database access
Struts database access
Abass Ndiaye
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
Abdul Malik Ikhsan
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
Brockhaus Consulting GmbH
 
I am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdfI am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdf
seamusschwaabl99557
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
Conint29
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsAhsanul Karim
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
Bhushan Nagaraj
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfUNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
SakkaravarthiS1
 
APPlause - DemoCamp Munich
APPlause - DemoCamp MunichAPPlause - DemoCamp Munich
APPlause - DemoCamp Munich
Peter Friese
 
Desenvolva um game para android ou iPhone
Desenvolva um game para android ou iPhoneDesenvolva um game para android ou iPhone
Desenvolva um game para android ou iPhoneTiago Oliveira
 

Similar to Java Program Photo Viewer1. Write an app called viewer that will .pdf (20)

College management system.pptx
College management system.pptxCollege management system.pptx
College management system.pptx
 
Program imageviewer
Program imageviewerProgram imageviewer
Program imageviewer
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-en
 
Java Programming In this programming assignment, you need to impl.pdf
Java Programming In this programming assignment, you need to impl.pdfJava Programming In this programming assignment, you need to impl.pdf
Java Programming In this programming assignment, you need to impl.pdf
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
 
Awt, Swing, Layout managers
Awt, Swing, Layout managersAwt, Swing, Layout managers
Awt, Swing, Layout managers
 
Struts database access
Struts database accessStruts database access
Struts database access
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 
Arquillian in a nutshell
Arquillian in a nutshellArquillian in a nutshell
Arquillian in a nutshell
 
I am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdfI am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdf
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
 
Class 1
Class 1Class 1
Class 1
 
Class 1
Class 1Class 1
Class 1
 
Class 1 blog
Class 1 blogClass 1 blog
Class 1 blog
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfUNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
 
APPlause - DemoCamp Munich
APPlause - DemoCamp MunichAPPlause - DemoCamp Munich
APPlause - DemoCamp Munich
 
Desenvolva um game para android ou iPhone
Desenvolva um game para android ou iPhoneDesenvolva um game para android ou iPhone
Desenvolva um game para android ou iPhone
 

More from bhim1213

In 1998, Congress passed legislation concerning shifting the burden .pdf
In 1998, Congress passed legislation concerning shifting the burden .pdfIn 1998, Congress passed legislation concerning shifting the burden .pdf
In 1998, Congress passed legislation concerning shifting the burden .pdf
bhim1213
 
If A denotes some event, what does A denote If P(A)equals=0.997, wh.pdf
If A denotes some event, what does A denote If P(A)equals=0.997, wh.pdfIf A denotes some event, what does A denote If P(A)equals=0.997, wh.pdf
If A denotes some event, what does A denote If P(A)equals=0.997, wh.pdf
bhim1213
 
How do neutrophils find and get to an infectionSolutionNeutro.pdf
How do neutrophils find and get to an infectionSolutionNeutro.pdfHow do neutrophils find and get to an infectionSolutionNeutro.pdf
How do neutrophils find and get to an infectionSolutionNeutro.pdf
bhim1213
 
How many times will the following code print Welcome to Java in.pdf
How many times will the following code print Welcome to Java  in.pdfHow many times will the following code print Welcome to Java  in.pdf
How many times will the following code print Welcome to Java in.pdf
bhim1213
 
From your own words not copy past from internet please Talked about.pdf
From your own words not copy past from internet please Talked about.pdfFrom your own words not copy past from internet please Talked about.pdf
From your own words not copy past from internet please Talked about.pdf
bhim1213
 
Forms an important part of the subunits of the ribosome. The _ are sp.pdf
Forms an important part of the subunits of the ribosome. The _ are sp.pdfForms an important part of the subunits of the ribosome. The _ are sp.pdf
Forms an important part of the subunits of the ribosome. The _ are sp.pdf
bhim1213
 
During DNA replication, a series of steps are required to ensure tha.pdf
During DNA replication, a series of steps are required to ensure tha.pdfDuring DNA replication, a series of steps are required to ensure tha.pdf
During DNA replication, a series of steps are required to ensure tha.pdf
bhim1213
 
Disease X occurs when someone has the xx genotype. However, only 20 .pdf
Disease X occurs when someone has the xx genotype. However, only 20 .pdfDisease X occurs when someone has the xx genotype. However, only 20 .pdf
Disease X occurs when someone has the xx genotype. However, only 20 .pdf
bhim1213
 
Darwins Theory had five main tenets (or components), what are they.pdf
Darwins Theory had five main tenets (or components), what are they.pdfDarwins Theory had five main tenets (or components), what are they.pdf
Darwins Theory had five main tenets (or components), what are they.pdf
bhim1213
 
Define toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdf
Define toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdfDefine toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdf
Define toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdf
bhim1213
 
A system was set up in parallel with two components, A and B. The pr.pdf
A system was set up in parallel with two components, A and B. The pr.pdfA system was set up in parallel with two components, A and B. The pr.pdf
A system was set up in parallel with two components, A and B. The pr.pdf
bhim1213
 
All content is made permanent for future use. All content will be lo.pdf
All content is made permanent for future use.  All content will be lo.pdfAll content is made permanent for future use.  All content will be lo.pdf
All content is made permanent for future use. All content will be lo.pdf
bhim1213
 
a. A waitress is serving 5 people at a table. She has the 5 dishes t.pdf
a. A waitress is serving 5 people at a table. She has the 5 dishes t.pdfa. A waitress is serving 5 people at a table. She has the 5 dishes t.pdf
a. A waitress is serving 5 people at a table. She has the 5 dishes t.pdf
bhim1213
 
Biochemistry homework Focus concept ripening fruit and the activity.pdf
Biochemistry homework Focus concept ripening fruit and the activity.pdfBiochemistry homework Focus concept ripening fruit and the activity.pdf
Biochemistry homework Focus concept ripening fruit and the activity.pdf
bhim1213
 
A process that has its representative PCB in a device queue is in th.pdf
A process that has its representative PCB in a device queue is in th.pdfA process that has its representative PCB in a device queue is in th.pdf
A process that has its representative PCB in a device queue is in th.pdf
bhim1213
 
Which of the following statements is (are) trueI Cash flow is a.pdf
Which of the following statements is (are) trueI  Cash flow is a.pdfWhich of the following statements is (are) trueI  Cash flow is a.pdf
Which of the following statements is (are) trueI Cash flow is a.pdf
bhim1213
 
What is the relationship of the epithelium of the epidermis to the co.pdf
What is the relationship of the epithelium of the epidermis to the co.pdfWhat is the relationship of the epithelium of the epidermis to the co.pdf
What is the relationship of the epithelium of the epidermis to the co.pdf
bhim1213
 
What is a linked listWhat is a linked lists general syntaxCan .pdf
What is a linked listWhat is a linked lists general syntaxCan .pdfWhat is a linked listWhat is a linked lists general syntaxCan .pdf
What is a linked listWhat is a linked lists general syntaxCan .pdf
bhim1213
 
What is the output of running class GenericMethodDemo of the followi.pdf
What is the output of running class GenericMethodDemo of the followi.pdfWhat is the output of running class GenericMethodDemo of the followi.pdf
What is the output of running class GenericMethodDemo of the followi.pdf
bhim1213
 
What do you think are the roles of professional societies in contemp.pdf
What do you think are the roles of professional societies in contemp.pdfWhat do you think are the roles of professional societies in contemp.pdf
What do you think are the roles of professional societies in contemp.pdf
bhim1213
 

More from bhim1213 (20)

In 1998, Congress passed legislation concerning shifting the burden .pdf
In 1998, Congress passed legislation concerning shifting the burden .pdfIn 1998, Congress passed legislation concerning shifting the burden .pdf
In 1998, Congress passed legislation concerning shifting the burden .pdf
 
If A denotes some event, what does A denote If P(A)equals=0.997, wh.pdf
If A denotes some event, what does A denote If P(A)equals=0.997, wh.pdfIf A denotes some event, what does A denote If P(A)equals=0.997, wh.pdf
If A denotes some event, what does A denote If P(A)equals=0.997, wh.pdf
 
How do neutrophils find and get to an infectionSolutionNeutro.pdf
How do neutrophils find and get to an infectionSolutionNeutro.pdfHow do neutrophils find and get to an infectionSolutionNeutro.pdf
How do neutrophils find and get to an infectionSolutionNeutro.pdf
 
How many times will the following code print Welcome to Java in.pdf
How many times will the following code print Welcome to Java  in.pdfHow many times will the following code print Welcome to Java  in.pdf
How many times will the following code print Welcome to Java in.pdf
 
From your own words not copy past from internet please Talked about.pdf
From your own words not copy past from internet please Talked about.pdfFrom your own words not copy past from internet please Talked about.pdf
From your own words not copy past from internet please Talked about.pdf
 
Forms an important part of the subunits of the ribosome. The _ are sp.pdf
Forms an important part of the subunits of the ribosome. The _ are sp.pdfForms an important part of the subunits of the ribosome. The _ are sp.pdf
Forms an important part of the subunits of the ribosome. The _ are sp.pdf
 
During DNA replication, a series of steps are required to ensure tha.pdf
During DNA replication, a series of steps are required to ensure tha.pdfDuring DNA replication, a series of steps are required to ensure tha.pdf
During DNA replication, a series of steps are required to ensure tha.pdf
 
Disease X occurs when someone has the xx genotype. However, only 20 .pdf
Disease X occurs when someone has the xx genotype. However, only 20 .pdfDisease X occurs when someone has the xx genotype. However, only 20 .pdf
Disease X occurs when someone has the xx genotype. However, only 20 .pdf
 
Darwins Theory had five main tenets (or components), what are they.pdf
Darwins Theory had five main tenets (or components), what are they.pdfDarwins Theory had five main tenets (or components), what are they.pdf
Darwins Theory had five main tenets (or components), what are they.pdf
 
Define toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdf
Define toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdfDefine toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdf
Define toxic shock syndrome (TSS) impetigo MRSASolutionAnswer.pdf
 
A system was set up in parallel with two components, A and B. The pr.pdf
A system was set up in parallel with two components, A and B. The pr.pdfA system was set up in parallel with two components, A and B. The pr.pdf
A system was set up in parallel with two components, A and B. The pr.pdf
 
All content is made permanent for future use. All content will be lo.pdf
All content is made permanent for future use.  All content will be lo.pdfAll content is made permanent for future use.  All content will be lo.pdf
All content is made permanent for future use. All content will be lo.pdf
 
a. A waitress is serving 5 people at a table. She has the 5 dishes t.pdf
a. A waitress is serving 5 people at a table. She has the 5 dishes t.pdfa. A waitress is serving 5 people at a table. She has the 5 dishes t.pdf
a. A waitress is serving 5 people at a table. She has the 5 dishes t.pdf
 
Biochemistry homework Focus concept ripening fruit and the activity.pdf
Biochemistry homework Focus concept ripening fruit and the activity.pdfBiochemistry homework Focus concept ripening fruit and the activity.pdf
Biochemistry homework Focus concept ripening fruit and the activity.pdf
 
A process that has its representative PCB in a device queue is in th.pdf
A process that has its representative PCB in a device queue is in th.pdfA process that has its representative PCB in a device queue is in th.pdf
A process that has its representative PCB in a device queue is in th.pdf
 
Which of the following statements is (are) trueI Cash flow is a.pdf
Which of the following statements is (are) trueI  Cash flow is a.pdfWhich of the following statements is (are) trueI  Cash flow is a.pdf
Which of the following statements is (are) trueI Cash flow is a.pdf
 
What is the relationship of the epithelium of the epidermis to the co.pdf
What is the relationship of the epithelium of the epidermis to the co.pdfWhat is the relationship of the epithelium of the epidermis to the co.pdf
What is the relationship of the epithelium of the epidermis to the co.pdf
 
What is a linked listWhat is a linked lists general syntaxCan .pdf
What is a linked listWhat is a linked lists general syntaxCan .pdfWhat is a linked listWhat is a linked lists general syntaxCan .pdf
What is a linked listWhat is a linked lists general syntaxCan .pdf
 
What is the output of running class GenericMethodDemo of the followi.pdf
What is the output of running class GenericMethodDemo of the followi.pdfWhat is the output of running class GenericMethodDemo of the followi.pdf
What is the output of running class GenericMethodDemo of the followi.pdf
 
What do you think are the roles of professional societies in contemp.pdf
What do you think are the roles of professional societies in contemp.pdfWhat do you think are the roles of professional societies in contemp.pdf
What do you think are the roles of professional societies in contemp.pdf
 

Recently uploaded

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 

Java Program Photo Viewer1. Write an app called viewer that will .pdf

  • 1. Java Program: Photo Viewer 1. Write an app called viewer that will have a Label at the top saying "My Viewer" (or something like that) 2. Will have JButtons at the bottom that will do Next, Previous, and Quit 3. Have the whole middle be a JLabel in which you will display Images stored in a directory. 4. The directory can be named Resource. 5. When you run the program (java viewer) it will read all the names in the Resource Directory. Then, when you click Next or Previous it will display an Image. 6. Note: you will need to find a java method that exists for reading a whole directory of filenames. You can store all those names in a String Array when run the program. 7. You will use a counter or index that is an int an when you click Next it will increment the counter until it reach some maximum value and then you will set it to 0. Previous will decrement the counter until it goes negative and then it will set the counter to the Maximum index ( which is how many filenames you have in the Image names array) 8. Submit the program viewer.java I should be able to use it with my own Resource directory. Solution Please refer this code for your application : -------------------------------------------------------------------------------------------------------------------- -------------- import java.awt.Image; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; public class ImageViewer extends javax.swing.JFrame { public ImageViewer() { initComponents(); listFiles(Path); //Lists all the files in the directory on window opening setLabelIcon(Path,filenames[position]); //sets the label to display the first //image in the directory on window opening. PreviousButton.setEnabled(false);
  • 2. } /** *Initialize components */ private void initComponents() { setTitle("Image Viewer"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new java.awt.BorderLayout());// The layout is BorderLayout //setBorder(javax.swing.BorderFactory.createEtchedBorder()); setBackground(java.awt.Color.GRAY); picLabel = new javax.swing.JLabel(); //Create the Label to display the picture picLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); picLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); PreviousButton = new javax.swing.JButton(); PreviousButton.setText("Previous"); PreviousButton.setIconTextGap(10); //Distance between the icon and text is 10 PreviousButton.addActionListener(new java.awt.event.ActionListener() { //Register an actionListener for the PreviousButton public void actionPerformed(java.awt.event.ActionEvent evt) { PreviousButtonActionPerformed(evt); } }); NextButton = new javax.swing.JButton(); NextButton.setPreferredSize(PreviousButton.getPreferredSize()); NextButton.setText("Next"); NextButton.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); NextButton.setIconTextGap(10); //Distance between the icon and text is 10 NextButton.addActionListener(new java.awt.event.ActionListener() { //Registers an actionListener for the NextButton public void actionPerformed(java.awt.event.ActionEvent evt) { NextButtonActionPerformed(evt); } }); javax.swing.Box vbox = javax.swing.Box.createVerticalBox(); //VerticalBox to hold the pictureLabel and the buttons vbox.add(javax.swing.Box.createVerticalStrut(30));
  • 3. vbox.add(picLabel); vbox.add(javax.swing.Box.createVerticalStrut(50)); javax.swing.JPanel prev_next_pane = new javax.swing.JPanel(); //Panel to hold the Previous and Next buttons. java.awt.FlowLayout flow = new java.awt.FlowLayout(java.awt.FlowLayout.CENTER); flow.setHgap(30); prev_next_pane.setLayout(flow); prev_next_pane.add(PreviousButton); prev_next_pane.add(NextButton); prev_next_pane.setOpaque(false); vbox.add(prev_next_pane); //Add the panel to the verticalBox add(vbox); java.awt.Toolkit theKit = getToolkit(); java.awt.Dimension size = theKit.getScreenSize(); setLocation(size.width/5,size.height/10); setMinimumSize(new java.awt.Dimension(900,600)); //setMaximumSize(new Dimension(size.width/4 + 50,size.height/4)); }//END:initComponents /** *Handler for previous button */ private void PreviousButtonActionPerformed(java.awt.event.ActionEvent evt) { position--; //Decrement the index position of the array of filenames by one on buttonPressed if(!NextButton.isEnabled()){ //if NextButton is NextButton.setEnabled(true); //disabled, enable it } if(position == 0){ //If we are viewing the first Picture in PreviousButton.setEnabled(false); //the directory, disable previous button } setLabelIcon(Path,filenames[position]); }//End of PreviousButton handler /** *Handler for NextButton */ private void NextButtonActionPerformed(java.awt.event.ActionEvent evt) {
  • 4. position++; //Increment the index position of the array of filenames by one on buttonPressed if(!PreviousButton.isEnabled()){ listFiles(Path); PreviousButton.setEnabled(true); } if(position == filenames.length){ NextButton.setEnabled(false); position --; return; } setLabelIcon(Path,filenames[position]); }//End of NextButton handler public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ImageViewer.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); }
  • 5. /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ImageViewer().setVisible(true); } }); } /**Method to list all the files in the directory *And store their names in an array */ private void listFiles(String Path){ File file = new File(Path); filenames = file.list(); //store the file names in the array of strings. for(String names : filenames){ System.out.println(names); //Print the filenames to the console just so you can see } } //Method to set the picture on the label private void setLabelIcon(String Path,String name){ File file = new File(Path+""+name); java.awt.image.BufferedImage image = null; try{ image = ImageIO.read(file); //Reas the image from the file. }catch(IOException ie){ javax.swing.JOptionPane.showMessageDialog(this,"Error reading image file","Error", javax.swing.JOptionPane.ERROR_MESSAGE); } ImageIcon icon = new ImageIcon(image); int width = 600; int height = 400; Image img = icon.getImage().getScaledInstance(width,height,java.awt.Image.SCALE_SMOOTH); //Images produced will remain a fixed size, 600 * 400
  • 6. ImageIcon newIcon = new ImageIcon(img); //Create a new imageicon from an image object. //Now we want to create a caption for the pictures using their file names String pictureName = file.getName(); int pos = pictureName.lastIndexOf("."); //This removes the extensions String caption = pictureName.substring(0,pos); //from the file names. e.g .gif, .jpg, .png picLabel.setIcon(newIcon); //Set the imageIcon on the Label picLabel.setText(caption); //Set the caption picLabel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); //Caption appears below the image } //Variables declaration int position = 0; //Initial position is 0 String[] filenames; //Array to hold the file names final String Path = System.getProperty("user.home") +"User_Namepictures"; //path to your images private javax.swing.JButton NextButton; private javax.swing.JButton PreviousButton; private javax.swing.JLabel picLabel; // End of variables declaration//GEN-END:variables }//End of class -------------------------------------------------------------------------------------------------------------------- -------------- feel free to reach out to me if you have any doubts in understanding this code. Keep learning :)