-2

I have been looking into the JFileChooser of Java. I used Oracles FileChooserDemo as a base template. I have made some slight modifications to Oracles demo. My problem is, when I run the program, the JFrame is really small. Even if I use setSize or setPreferredSize, the JFrame stays the same. The demo uses the pack method. I thought this was limiting the size of the frame but by removing that line, when I run the program, the window appears but only with the minimize, maximize, and close buttons at the top. Here is my complete code:

import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.awt.*;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.interactive.form.*;

public class Swing_Main_Menu extends JFrame implements ActionListener
{
public static final  int WIDTH=900;
public static final  int HEIGHT=600;

public static void main(String[] args)
{
    Swing_Main_Menu gui = new Swing_Main_Menu();
    gui.setVisible(true);       
}

public Swing_Main_Menu()
{
    super();
    setSize(WIDTH, HEIGHT);
    setLayout(new GridLayout(2,2));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton readPDF = new JButton("Read PDF");
    readPDF.setFont(new Font("Arial",Font.PLAIN, 30));
    readPDF.setBackground(Color.LIGHT_GRAY);
    readPDF.addActionListener(new PDFExtraction());

    JButton view = new JButton("View");
    view.setFont(new Font("Arial",Font.PLAIN, 30));
    view.setBackground(Color.LIGHT_GRAY);
    view.addActionListener(this);

    JButton dashboard = new JButton("Dashboard");
    dashboard.setFont(new Font("Arial",Font.PLAIN, 30));
    dashboard.setBackground(Color.LIGHT_GRAY);
    dashboard.addActionListener(this);

    JButton upload = new JButton("Batch Upload");
    upload.setFont(new Font("Arial",Font.PLAIN, 30));
    upload.setBackground(Color.LIGHT_GRAY);
    upload.addActionListener(this);

    add(readPDF);
    add(view);
    add(dashboard);
    add(upload);
}

private class PDFExtraction implements ActionListener
{
    private void readFields(PDDocument doc) throws Exception
    {
        PDDocumentCatalog catalog = doc.getDocumentCatalog();
        PDAcroForm form = catalog.getAcroForm();
        List<PDField> fields = form.getFields();
        ArrayList <String> allFields= new ArrayList<>(1);
        for(PDField field: fields)
        {
            String name = field.getFullyQualifiedName();
            if (field instanceof PDTextField || field instanceof PDComboBox)
            {
                 String value = field.getValueAsString();
                 allFields.add(value);
            }
            else if (field instanceof PDPushButton)
                ;
            else
            {
                if (field instanceof PDRadioButton)
                {
                    PDRadioButton radioButton = (PDRadioButton)form.getField(name);
                    String value=radioButton.getValue();
                    allFields.add(value);
                }
                else if (field instanceof PDCheckBox)
                {
                    PDButton box = (PDButton)field;
                    String value = box.getValue();
                    allFields.add(value);
                }

            }
        }
        int count = 1;
        for (String element : allFields)
        {
            System.out.println(count + ": " + element );
            count++;
        }
    }

    private void readFile() throws Exception {
        FileChooserForRead fc = new FileChooserForRead();
        fc.chooseFile();
    }

    public void actionPerformed (ActionEvent e)
    {
            try
            {
                readFile();
            }

            catch (Exception except)
            {
                System.exit(0);
            }
    }
}

public void actionPerformed (ActionEvent e)
{
    String buttonString = e.getActionCommand();
    if (buttonString.equals("View"))
    {
        //JFrame newMenu = new JFrame();
        //newMenu.setSize(WIDTH, HEIGHT);
        //newMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           
        FileChooser pickFile = new FileChooser();
        pickFile.chooseFile();      
    }
    else if (buttonString.equals("Dashboard"))
    {
        System.exit(0);
    }
    else if(buttonString.equals("Batch Upload"))
    {
        System.exit(0);
    }
    else
    {
        System.exit(0);
    }

}

public class FileChooser extends JPanel
implements ActionListener 
{
static private final String newline = "\n";
JButton openButton;
JTextArea log;
JFileChooser fc;

public FileChooser() {
    super(new BorderLayout());
    log = new JTextArea(5,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);

    fc = new JFileChooser();
    //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    openButton = new JButton("Open a File...");
    //openButton.setPreferredSize(new Dimension(100, 50));
    //openButton.setFont(new Font("Arial",Font.PLAIN, 30));
    openButton.addActionListener(this);

    JPanel buttonPanel = new JPanel(); //use FlowLayout
    buttonPanel.add(openButton);

    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e)
{
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(FileChooser.this);

    if (returnVal == JFileChooser.APPROVE_OPTION) 
    {
        File file = fc.getSelectedFile();
        log.append("Opening: " + file.getName() + "." + newline);
        try
        {
            Desktop.getDesktop().open(file);
        }
        catch (IOException ex)
        {
            System.exit(0);
        }
    }
    else {
        log.append("Open command cancelled by user." + newline);
    }
    log.setCaretPosition(log.getDocument().getLength());
    }
}

/**
* Create the GUI and show it.  For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FileChooser");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

//Add content to the window.
frame.add(new FileChooser());

//Display the window.
//frame.setPreferredSize(new Dimension(WIDTH, HEIGHT));
frame.setSize(WIDTH,HEIGHT);
frame.pack();
frame.setVisible(true);
}

public void chooseFile () {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
  UIManager.put("swing.boldMetal", Boolean.FALSE); 
  createAndShowGUI();
}
});
}
}

public class FileChooserForRead extends JPanel implements ActionListener 
{
    static private final String newline = "\n";
    JButton openButton;
    JTextArea log;
    JFileChooser fc;

    public FileChooserForRead() {
        super(new BorderLayout());
        log = new JTextArea(5,20);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(log);

        fc = new JFileChooser();
        //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        openButton = new JButton("Open a File...");
        //openButton.setPreferredSize(new Dimension(100, 50));
        //openButton.setFont(new Font("Arial",Font.PLAIN, 30));
        openButton.addActionListener(this);

        JPanel buttonPanel = new JPanel(); //use FlowLayout
        buttonPanel.add(openButton);

        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == openButton) {
            int returnVal = fc.showOpenDialog(FileChooserForRead.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) 
        {
            File file = fc.getSelectedFile();
            log.append("Opening: " + file.getName() + "." + newline);
            try
            {
                PDDocument doc = PDDocument.load(file);
                PDFExtraction reader = new PDFExtraction();
                reader.readFields(doc);
            }
            catch (Exception ex)
            {
                System.exit(0);
            }
        }
        else {
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
        }           
    }

    private void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("FileChooser");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        //Add content to the window.
        frame.add(new FileChooserForRead());

        //Display the window.
        //frame.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        frame.pack();
        frame.setVisible(true);
        }

        public void chooseFile () 
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run() 
                {
                    UIManager.put("swing.boldMetal", Boolean.FALSE); 
                    createAndShowGUI();
                }
            });
        }
    }

}

Thank you in advance for helping me. This is the Oracle example I based my JFileChooser off of:

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;

public class FileChooserDemo extends JPanel
                         implements ActionListener {
    static private final String newline = "\n";
    JButton openButton, saveButton;
    JTextArea log;
    JFileChooser fc;

public FileChooserDemo() {
    super(new BorderLayout());

    //Create the log first, because the action listeners
    //need to refer to it.
    log = new JTextArea(5,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);

    //Create a file chooser
    fc = new JFileChooser();

    //Uncomment one of the following lines to try a different
    //file selection mode.  The first allows just directories
    //to be selected (and, at least in the Java look and feel,
    //shown).  The second allows both files and directories
    //to be selected.  If you leave these lines commented out,
    //then the default mode (FILES_ONLY) will be used.
    //
    //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    //Create the open button.  We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    openButton = new JButton("Open a File...",
                             createImageIcon("images/Open16.gif"));
    openButton.addActionListener(this);

    //Create the save button.  We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton("Save a File...",
                             createImageIcon("images/Save16.gif"));
    saveButton.addActionListener(this);

    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel(); //use FlowLayout
    buttonPanel.add(openButton);
    buttonPanel.add(saveButton);

    //Add the buttons and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(FileChooserDemo.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);
        } else {
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

    //Handle save button action.
    } else if (e.getSource() == saveButton) {
        int returnVal = fc.showSaveDialog(FileChooserDemo.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would save the file.
            log.append("Saving: " + file.getName() + "." + newline);
        } else {
            log.append("Save command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
    }
}

/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = FileChooserDemo.class.getResource(path);
    if (imgURL != null) {
        return new ImageIcon(imgURL);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }
}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event dispatch thread.
 */
private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("FileChooserDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add content to the window.
    frame.add(new FileChooserDemo());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            //Turn off metal's use of bold fonts
            UIManager.put("swing.boldMetal", Boolean.FALSE); 
            createAndShowGUI();
        }
    });
  }
}
DemonSlayer730
  • 19
  • 1
  • 1
  • 4
  • 1
    The posted code won't compile (even with imports added). For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Jul 09 '18 at 16:08

1 Answers1

0

It's very simple. Either you use setSize method or pack(), but never both together.

private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("FileChooser");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add content to the window.
    frame.add(new FileChooser());

    //Display the window.

    //frame.setPreferredSize(new Dimension(WIDTH, HEIGHT));
    frame.setSize(1024, 768);
    //frame.pack();
    frame.setVisible(true);
}
Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48
  • Can you explain why or give a reference why not to use pack() & setSize()? – PaulEdison Jul 09 '18 at 18:37
  • @PaulEdison Because they do the same thing: changing of the frame size. `pack` set the window size according to the size of the content pane (which is determined by the `LayoutManager`). `setSize` sets the fixed size for the window. – Sergiy Medvynskyy Jul 10 '18 at 05:51
  • @SergiyMedvynskyy I know I should not use both but if I take out the pack(), the window disappears except the close, minimize and maximize buttons of the window. When I take out the pack() and setSize(WIDTH, HEIGHT), the window is still gone except for the three window buttons. – DemonSlayer730 Jul 10 '18 at 16:06
  • @SergiyMedvynskyy I have added all of my code as well as the Oracle example that does not have the problem of being unable to change the JFrame window size. – DemonSlayer730 Jul 13 '18 at 16:08
  • @PaulEdison I still cannot understand your problem. I've run the code you've posted and all works fine for me (at least with the my version of method `createAndShowGUI`). – Sergiy Medvynskyy Jul 15 '18 at 07:36
  • @SergiyMedvynskyy Here is a link to a dropbox that shows what happens when I run the program with setSize() and not pack(): https://www.dropbox.com/s/0thobs6mghccxo7/Screenshot%20%281%29.png?dl=0 – DemonSlayer730 Jul 16 '18 at 16:04
  • @DemonSlayer730 if you want to get help please provide a [mcve] so I can better understand what you do. Don't post the entire code here, but create a small UI with your layout. Please also specify, what is the desired behavior. – Sergiy Medvynskyy Jul 16 '18 at 16:13