-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathTextFrame.java
More file actions
101 lines (89 loc) · 2.85 KB
/
Copy pathTextFrame.java
File metadata and controls
101 lines (89 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package progressMonitorInputStream;
import java.awt.event.*;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import javax.swing.*;
/**
* A frame with a menu to load a text file and a text area to display its contents. The text area is
* constructed when the file is loaded and set as the content pane of the frame when the loading is
* complete. That avoids flicker during loading.
*/
public class TextFrame extends JFrame
{
public static final int TEXT_ROWS = 10;
public static final int TEXT_COLUMNS = 40;
private JMenuItem openItem;
private JMenuItem exitItem;
private JTextArea textArea;
private JFileChooser chooser;
public TextFrame()
{
textArea = new JTextArea(TEXT_ROWS, TEXT_COLUMNS);
add(new JScrollPane(textArea));
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
openItem = new JMenuItem("Open");
openItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
openFile();
}
catch (IOException exception)
{
exception.printStackTrace();
}
}
});
fileMenu.add(openItem);
exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
fileMenu.add(exitItem);
pack();
}
/**
* Prompts the user to select a file, loads the file into a text area, and sets it as the content
* pane of the frame.
*/
public void openFile() throws IOException
{
int r = chooser.showOpenDialog(this);
if (r != JFileChooser.APPROVE_OPTION) return;
final File f = chooser.getSelectedFile();
// set up stream and reader filter sequence
InputStream fileIn = Files.newInputStream(f.toPath());
final ProgressMonitorInputStream progressIn = new ProgressMonitorInputStream(
this, "Reading " + f.getName(), fileIn);
textArea.setText("");
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>()
{
protected Void doInBackground() throws Exception
{
try (Scanner in = new Scanner(progressIn))
{
while (in.hasNextLine())
{
String line = in.nextLine();
textArea.append(line);
textArea.append("\n");
}
}
return null;
}
};
worker.execute();
}
}