Tag Archives: Swing

Determining the selected file in the JFileChooser

Introduction

The JFileChooser is a Swing component to choose files from the FileSystem. After you chose a file (or Directory you need to get the selected file back in your code. This example shows how it’s done.

JFileChooser
JFileChooser
JFileChooser chooser = new JFileChooser();

// Set the current directory to the 
// application's current directory
try {
    // Create a File object containing the
    // canonical path of the
    // desired file
    File f = new File(new File("filename.txt").getCanonicalPath());

    // Set the selected file
    chooser.setSelectedFile(f);
} catch (IOException e) {
}

// Show the dialog; wait until dialog is closed
chooser.showOpenDialog(frame);

// Get the currently selected file
File curFile = chooser.getSelectedFile();

 

Enumerating the parameters in the Swing JTextPane

Introduction

JPanel
JPanel

The java.swing.jpanel is a generic lightweight container. For examples and task-oriented documentation for JPanel, see How to Use Panels, a section in The Java Tutorial. The example below shows how to enumerate over the paragraphs in the JTextPane.

JTextPane
JTextPane

 

 

 

 

// Create a text pane
JTextPane textPane = new JTextPane();

// Get section element 
Element section = textPane.getDocument().getDefaultRootElement();

// Get number of paragraphs.
// In a text pane, a span of characters
// terminated by single
// newline is typically called a paragraph.
int paraCount = section.getElementCount();

// Get index ranges for each paragraph
for (int i=0; i<paraCount; i++) {
    Element e = section.getElement(i);
    int rangeStart = e.getStartOffset();
    int rangeEnd = e.getEndOffset();
    try {
        String para = textPane.getText(rangeStart, rangeEnd-rangeStart);
    } catch (BadLocationException ex) {
    }
}

See also the Swing UITutorial.