-2

I'm trying to make a image viewer in java. What my program does is that it takes two inputs from the user, in input 1 the user enters a path for the folder in which he wants to view the images and in input 2 also the user enter a path for another folder in which he wants to view images and then press the run button. On pressing the run button, the first image from both the user's entered folders is visible in the image viewer parallel to each other and then the user can view the next and previous images on pressing the different buttons. My code for the above program is shown below:-

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class Main extends JFrame {

private JPanel contentPane;
public JTextField textField;
public JTextField textField_1;
public JLabel label;
public JLabel label_1;
int pos = 0;
int pos1 = 0;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Main frame = new Main();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 693, 421);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblInput = new JLabel("Input 1");
    lblInput.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblInput.setBounds(43, 26, 71, 29);
    contentPane.add(lblInput);

    textField = new JTextField();
    textField.setBounds(124, 26, 312, 29);
    contentPane.add(textField);
    textField.setColumns(10);



    JLabel lblExePath = new JLabel("Input 2");
    lblExePath.setFont(new Font("Tahoma", Font.PLAIN, 14));
    lblExePath.setBounds(43, 90, 71, 29);
    contentPane.add(lblExePath);

    textField_1 = new JTextField();
    textField_1.setColumns(10);
    textField_1.setBounds(124, 90, 312, 29);
    contentPane.add(textField_1);

    JButton btnRun = new JButton("Run");
    btnRun.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            showImage(0);
            showImages(0);

        }
    });
    btnRun.setBounds(505, 95, 89, 23);
    contentPane.add(btnRun);

    label = new JLabel("");
    label.setBounds(43, 151, 262, 176);
    contentPane.add(label);

    label_1 = new JLabel("");
    label_1.setBounds(332, 151, 262, 176);
    contentPane.add(label_1);

    JButton btnPrevious = new JButton("Previous");
    btnPrevious.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            pos = pos-1;
            if (pos < 0) {
                pos = 0;
            }
            showImage(pos);

            pos1 = pos1-1;
            if (pos1 < 0) {
                pos1 = 0;
            }
            showImages(pos1);
        }
    });
    btnPrevious.setBounds(124, 349, 89, 23);
    contentPane.add(btnPrevious);

    JButton btnNext = new JButton("Next");
    btnNext.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            pos = pos+1;
            if (pos >= getImage().length) {
                pos = getImage().length - 1;
            }
            showImage(pos);

            pos1 = pos1+1;
            if (pos1 >= getImages().length) {
                pos1 = getImages().length - 1;
            }
            showImage(pos1);
        }
    });
    btnNext.setBounds(331, 349, 89, 23);
    contentPane.add(btnNext);

}


public String[] getImage() {
    File file = new File(textField.getText());
    String[] imagesList = file.list();
    return imagesList;
} 

public void showImage(int index) {
    String[] imagesList = getImage();
    String imageName = imagesList[index];
    ImageIcon icon = new ImageIcon(imageName);
    Image image = icon.getImage().getScaledInstance(label.getWidth(), 
    label.getHeight(), Image.SCALE_SMOOTH);
    label.setIcon(new ImageIcon(image));
}

public String[] getImages() {
    File file = new File(textField_1.getText());
    String[] imagesList = file.list();
    return imagesList;
} 

public void showImages(int index) {
    String[] imagesList = getImages();
    String imageName = imagesList[index];
    ImageIcon icon = new ImageIcon(imageName);
    Image image = icon.getImage().getScaledInstance(label_1.getWidth(), 
    label_1.getHeight(), Image.SCALE_SMOOTH);
    label_1.setIcon(new ImageIcon(image));
 }

}

Now, the problem i'm facing with this is that everything's been working fine , I'm able to convert the user's entered folder's files to an array list in the getimage() method and able to convert them to a different array but I'm not able to traverse that array properly in showimage() method and not able to make the image appear on screen. And if there any other issues in this code also then please guide because I'm a newbie to programming.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 2
    1) `contentPane.setLayout(null);` Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). – Andrew Thompson Jun 11 '18 at 15:15
  • 1
    3) *"What my program does is that it takes two inputs from the user, in input 1 the user enters a path for the folder"* Oh, for the love of the user, offer them a `JFileChooser`. A text field is sooo 1970s. – Andrew Thompson Jun 11 '18 at 15:18
  • I'm able to make a program same as this using 'JFileChooser' but now I want to do the same by this method. So, I need your help on the same thing with no changes in how things work. – Deepanshu Mourya Jun 11 '18 at 15:21
  • 1
    *"So, I need your help on the same thing with no changes.."* For my help you'll need to use example images as I mentioned in point (2) to make a [mcve]. I will not bother compiling the code seen above, let alone helping beyond that. Simplify the problem down. You don't have to change the actual program, but (for my help) you need to change the example code. Once we've solved the problem you should then be able to adapt the changes into whatever broken ass (e.g. no layout) code you like. – Andrew Thompson Jun 11 '18 at 15:24
  • @AndrewThompson Still not able to get the desired result on removing contentPane.setLayout(null) statement. – Deepanshu Mourya Jun 11 '18 at 15:26
  • Write the **correct code** and guide me then @AndrewThompson – Deepanshu Mourya Jun 11 '18 at 15:32

1 Answers1

0

If you print the filenames you’re using, you’ll see that they are base filenames, with no directory. That means they are relative file names, and whether they exist depends entirely on the current directory of the Java process itself.

java.io.File is an obsolete class. You should avoid using it. Instead, use the java.nio.file package, which will not only return full file paths, but will also provide you with useful information if your attempt to list the files fails. Replace both occurrences of this:

String[] imagesList = file.list();

with this:

String[] imagesList;
try (DirectoryStream<Path> dir = Files.newDirectoryStream(file.toPath())) {
    Collection<String> paths = new ArrayList<>();
    for (Path path : dir) {
        paths.add(path.toString());
    }
    imagesList = paths.toArray(new String[0]);
} catch (IOException e) {
    throw new RuntimeException("Cannot list files in " + file, e);
}
VGR
  • 40,506
  • 4
  • 48
  • 63