In Attempt to Create a JFileChooser--public variables? - java

In my previous question, I've stated I'm somewhat new to Java's JFrame features.
I'm trying to create a JFileChooser that will get a directory in which a file named setup.exe will be saved. That's irrelevant, though.
I'm receiving this error:
C:\Users\b\Downloads\files\thankyousanta>javac UpdateMechanism.java
UpdateMechanism.java:31: error: <identifier> expected
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
^
UpdateMechanism.java:31: error: <identifier> expected
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
^
UpdateMechanism.java:33: error: <identifier> expected
openButton.addActionListener(openButton);
^
UpdateMechanism.java:33: error: <identifier> expected
openButton.addActionListener(openButton);
^
4 errors
...for this code:
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
import javax.swing.filechooser.*;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFileChooser;
import javax.swing.BoxLayout;
import javax.Swing.SwingUtilities;
import javax.swing.BorderFactory;
import javax.swing.border.EmptyBorder;
import javax.imageio.ImageIO;
public class definitiveVoid extends JFileChooser implements ActionListener {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
JButton openButton = new JButton("The update is waiting on you.");
openButton.addActionListener(openButton);
}
public class UpdateMechanism extends JPanel
implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(UpdateMechanism.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
} else {
// operation cancelled
}
} else {
// destroy life
}
}
private static String readURL(String targetURL) {
String returnish = "";
try {
URL tempURL = new URL(targetURL);
Scanner s = new Scanner(tempURL.openStream());
while (s.hasNextLine()) {
returnish = returnish+s.nextLine();
}
} catch (IOException e) {
System.out.println(e);
}
return returnish;
}
private static String readFile(String targetFile) {
String returnString = "";
try {
File tempFile = new File(targetFile);
Scanner s = new Scanner(tempFile);
while (s.hasNextLine()) {
returnString = returnString + s.nextLine();
}
} catch(IOException e) {
// !
System.out.println(e);
}
return returnString;
}
private static void showGUI() {
JFrame frame = new JFrame("The Neverhood Restoration Project");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(1024, 600));
frame.setExtendedState(frame.MAXIMIZED_BOTH);
frame.getContentPane().setBackground(new Color(0xA64343));
File fileCheck = new File("C:/Program Files (x86)");
String returnString = null;
String rootDirectory = null;
if (fileCheck.exists()) {
rootDirectory = "C:/Program Files (x86)/DreamWorks Interactive";
String checkFile = rootDirectory+"/Neverhood/version.txt";
File tempFile = new File(checkFile);
if (tempFile.exists()) {
returnString = readFile(checkFile);
} else {
returnString = "It appears you do not have the Neverhood Restoration Project installed, or you are using an earlier version.";
}
} else {
rootDirectory = "C:/Program Files/DreamWorks Interactive";
String checkFile = rootDirectory+"/Neverhood/version.txt";
File tempFile = new File(checkFile);
if (tempFile.exists()) {
returnString = readFile(checkFile);
} else {
returnString = "It appears you do not have the Neverhood Restoration Project installed, or you are using an earlier version.";
}
}
if (returnString.equals(readURL("http://theneverhood.sourceforge.net/version.txt"))) {
returnString = "You are updated to the recent version!";
} else {
returnString = "It appears you're not updated.";
}
JLabel headerLabel = new JLabel("The Neverhood Restoration Project");
headerLabel.setHorizontalAlignment(JLabel.CENTER);
JPanel heapPanel = new JPanel();
heapPanel.setLayout(new BoxLayout(heapPanel, BoxLayout.PAGE_AXIS));
heapPanel.setPreferredSize(new Dimension(500, heapPanel.getPreferredSize().height));
JTextArea heapLabel = new JTextArea(50, 50);
heapLabel.setLineWrap(true);
heapLabel.setWrapStyleWord(true);
heapLabel.setEditable(false);
heapLabel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
heapLabel.setFont(new Font("Serif", Font.PLAIN, 14));
heapLabel.append("Current version: "+readURL("http://theneverhood.sourceforge.net/prettyversion.txt")+".\nInstalled version: "+readFile(rootDirectory+"/Neverhood/prettyversion.txt")+".\n"+returnString+"\n" +
"You can read the full version of the document to the left at http://theneverhood.sourceforge.net."
+ "\nBelow is the download button. Just click, choose your directory to save setup.exe in and enjoy!");
heapPanel.add(heapLabel);
try {
Font sFont = Font.createFont(Font.TRUETYPE_FONT, new File("DUGFB___.TTF"));
sFont = sFont.deriveFont(Font.PLAIN, 48);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(sFont);
headerLabel.setFont(sFont);
} catch (FontFormatException | IOException e) {
System.out.println(e);
}
BufferedImage icoImage = null;
try {
icoImage = ImageIO.read(
frame.getClass().getResource("/nhood.bmp"));
} catch (IOException e) {
System.out.println(e);
}
frame.setIconImage(icoImage);
JEditorPane updateLog = new JEditorPane();
JScrollPane scrollPane = new JScrollPane(updateLog);
updateLog.setEditable(false);
try {
updateLog.setPage("http://theneverhood.sourceforge.net/");
} catch (IOException e) {
updateLog.setContentType("text/html");
updateLog.setText("<html>The application could not load the webpage.</html>");
}
frame.add(headerLabel, BorderLayout.NORTH);
frame.add(scrollPane);
frame.add(heapPanel, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI();
}
});
}
}

In Java, public classes must be defined in their own file, having the same name (with a .java suffix) as the class name.
You defined a public class named definitiveVoid in the file UpdateMechanism.java. And you tried to put code directly in this class, outside of any method. That isn't valid Java.
Swing is hard and complex. Don't try to use it before knowing the basics of Java.
Moreover, classes, by convention, start with an uppercase letter in Java.

Related

Why is JFrame blank in one case but not the other? (Simple SwingWorker example)

===============================================
Adding this here since it's too long for a comment:
I can see I was unclear. When running MaintTest/main, the JFrame with Test button is not the problem. The JFrame which gets displayed when you click the test button is the problem.
Commenting out the FileUtils.copyURLToFile try block makes the 2nd JFrame display so briefly it's not clear whether it shows the label and progbar or not. (The initial JFrame with the Test button appears normally, when I click the Test button, the 2nd JFrame appears for an instant and goes away. The JFrame with the Test button remains, as expected. I don't reproduce "a Test button 6 times in a row". That sounds like things are set up wrong maybe?)
Yes copyURLToFile is blocking, but I start the concurrent display of the 2nd JFrame before I call copyURLToFile, so shouldn't it run in a separate thread anyway? I have a reason to know trhat it does. In the original application from which this code is derived, the 2nd JFrame displays as desired sometimes.
JFrame displaying sometimes is always answered by saying setVisible has to be called last, but that does not address my situation. This appears to have something to do with concurrency and Swing that I don't understand.
===============================================
Usually I can find the answers via google (more often than not at SO). I must be missing something here.
I've whittled this down to a small portion of my actual code and am still not enlightened. Sorry if it's still a little large, but it's hard to condense it further.
There are 3 java files. This references commons-io-2.5.jar. I'm coding/running in Eclipse Neon.
If I run ProgressBar/main() I see the JFrame contents. If I run MainTest/main() I don't. Here are the 3 files (please excuse some indentation anomalies -- the SO UI and I didn't agree on such things):
MainTest
public class MainTest {
public static void main(String[] args) {
MainFrame mainFrame = new MainFrame();
}
}
MainFrame
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.commons.io.FileUtils;
public class MainFrame extends JFrame implements ActionListener {
JButton jButton = new JButton();
public MainFrame() {
// Set up the content pane.
Container contentPane = this.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
jButton.setAlignmentX(Component.CENTER_ALIGNMENT);
jButton.setText("Test");
jButton.setActionCommand("Test");
jButton.addActionListener(this);
contentPane.add(jButton);
setup();
}
private void setup() {
Toolkit tk;
Dimension screenDims;
tk = Toolkit.getDefaultToolkit();
screenDims = tk.getScreenSize();
this.setLocation((screenDims.width - this.getWidth()) / 2, (screenDims.height - this.getHeight()) / 2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void downloadExecutable(String str) {
URL url = null;
try {
url = new URL("http://pegr-converter.com/download/test.jpg");
} catch (MalformedURLException exc) {
JOptionPane.showMessageDialog(null, "Unexpected exception: " + exc.getMessage());
return;
}
if (url != null) {
String[] options = { "OK", "Change", "Cancel" };
int response = JOptionPane.NO_OPTION;
File selectedFolder = new File(getDownloadDir());
File selectedLocation = new File(selectedFolder, str + ".jpg");
while (response == JOptionPane.NO_OPTION) {
selectedLocation = new File(selectedFolder, str + ".jpg");
String msgStr = str + ".jpg will be downloaded to the following location:\n"
+ selectedLocation.toPath();
response = JOptionPane.showOptionDialog(null, msgStr, "Pegr input needed",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (response == JOptionPane.NO_OPTION) {
// Prompt for file selection.
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setCurrentDirectory(selectedFolder);
fileChooser.showOpenDialog(null);
selectedFolder = fileChooser.getSelectedFile();
}
}
if (response == JOptionPane.YES_OPTION) {
int size = 0;
URLConnection conn;
try {
conn = url.openConnection();
size = conn.getContentLength();
} catch (IOException exc) {
System.out.println(exc.getMessage());
}
File destination = new File(selectedFolder, str + ".jpg");
ProgressBar status = new ProgressBar("Downloading " + str + ".jpg", destination, size);
try {
FileUtils.copyURLToFile(url, destination, 10000, 300000);
} catch (IOException exc) {
JOptionPane.showMessageDialog(null, "Download failed.");
return;
}
status.close();
}
}
}
public static String getDownloadDir() {
String home = System.getProperty("user.home");
File downloadDir = new File(home + "/Downloads/");
if (downloadDir.exists() && !downloadDir.isDirectory()) {
return home;
} else {
downloadDir = new File(downloadDir + "/");
if ((downloadDir.exists() && downloadDir.isDirectory()) || downloadDir.mkdirs()) {
return downloadDir.getPath();
} else {
return home;
}
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
downloadExecutable("test");
}
}
ProgressBar
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import org.apache.commons.io.FileUtils;
public class ProgressBar {
private String title;
private File outputFile;
private int size;
private ProgressTimerTask task;
JFrame frame;
JLabel jLabelProgressTitle;
JProgressBar jProgressBarProportion;
public ProgressBar(String title, File output, int size) {
this.title = title;
this.outputFile = output;
this.size = size;
frame = new JFrame("BoxLayoutDemo");
jProgressBarProportion = new JProgressBar();
jProgressBarProportion.setPreferredSize(new Dimension(300, 50));
jLabelProgressTitle = new JLabel();
jLabelProgressTitle.setHorizontalAlignment(SwingConstants.CENTER);
jLabelProgressTitle.setText("Progress");
jLabelProgressTitle.setPreferredSize(new Dimension(300, 50));
//Set up the content pane.
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
jLabelProgressTitle.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(jLabelProgressTitle);
jProgressBarProportion.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(jProgressBarProportion);
setup();
task = new ProgressTimerTask(this, outputFile, size);
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 500);
}
private void setup() {
Toolkit tk;
Dimension screenDims;
frame.setTitle("Test");
tk = Toolkit.getDefaultToolkit();
screenDims = tk.getScreenSize();
frame.setLocation((screenDims.width - frame.getWidth()) / 2, (screenDims.height - frame.getHeight()) / 2);
jLabelProgressTitle.setText(title);
jProgressBarProportion.setVisible(true);
jProgressBarProportion.setMinimum(0);
jProgressBarProportion.setMaximum(size);
jProgressBarProportion.setValue((int) outputFile.length());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void close() {
task.cancel();
frame.dispose();
}
public static void main(String[] args) throws InterruptedException {
ProgressBar progBar = new ProgressBar("Test Title", new File(MainFrame.getDownloadDir() + "test.jpg"), 30000);
Thread.sleep(3000);
progBar.close();
}
}
class ProgressTimerTask extends TimerTask {
ProgressBar frame;
File outputFile;
int size;
public ProgressTimerTask(ProgressBar progressBar, File outputFile, int size) {
this.frame = progressBar;
this.outputFile = outputFile;
this.size = size;
}
public void run() {
frame.jProgressBarProportion.setValue((int) outputFile.length());
System.out.println("Running");
}
}
Thanks to #MadProgrammer for this comment:
I can tell you, that you probably won't see the ProgressBar frame because the FileUtils.copyURLToFile will block until it's finished, in that case, you really should be using a SwingWorker
I read up about SwingWorker at the tutorial https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html and subsequently modified my MainFrame.java module to look like this:
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.apache.commons.io.FileUtils;
public class MainFrame extends JFrame implements ActionListener {
JButton jButton = new JButton();
static ProgressBar status;
static URL url;
public MainFrame() {
// Set up the content pane.
Container contentPane = this.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
jButton.setAlignmentX(Component.CENTER_ALIGNMENT);
jButton.setText("Test");
jButton.setActionCommand("Test");
jButton.addActionListener(this);
contentPane.add(jButton);
setup();
}
private void setup() {
Toolkit tk;
Dimension screenDims;
tk = Toolkit.getDefaultToolkit();
screenDims = tk.getScreenSize();
this.setLocation((screenDims.width - this.getWidth()) / 2, (screenDims.height - this.getHeight()) / 2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void downloadExecutable(String str) {
url = null;
try {
url = new URL("http://pegr-converter.com/download/test.jpg");
} catch (MalformedURLException exc) {
JOptionPane.showMessageDialog(null, "Unexpected exception: " + exc.getMessage());
return;
}
if (url != null) {
String[] options = { "OK", "Change", "Cancel" };
int response = JOptionPane.NO_OPTION;
File selectedFolder = new File(getDownloadDir());
File selectedLocation = new File(selectedFolder, str + ".jpg");
while (response == JOptionPane.NO_OPTION) {
selectedLocation = new File(selectedFolder, str + ".jpg");
String msgStr = str + ".jpg will be downloaded to the following location:\n"
+ selectedLocation.toPath();
response = JOptionPane.showOptionDialog(null, msgStr, "Pegr input needed",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (response == JOptionPane.NO_OPTION) {
// Prompt for file selection.
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setCurrentDirectory(selectedFolder);
fileChooser.showOpenDialog(null);
selectedFolder = fileChooser.getSelectedFile();
}
}
if (response == JOptionPane.YES_OPTION) {
int size = 0;
URLConnection conn;
try {
conn = url.openConnection();
size = conn.getContentLength();
} catch (IOException exc) {
System.out.println(exc.getMessage());
}
//System.out.println("javax.swing.SwingUtilities.isEventDispatchThread=" + javax.swing.SwingUtilities.isEventDispatchThread());
File destination = new File(selectedFolder, str + ".jpg");
status = new ProgressBar("Downloading " + str + ".jpg", destination, size);
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
try {
FileUtils.copyURLToFile(url, destination, 10000, 300000);
} catch (IOException exc) {
JOptionPane.showMessageDialog(null, "Download failed.");
}
return null;
}
public void done() {
status.close();
}
};
worker.execute();
}
}
}
public static String getDownloadDir() {
String home = System.getProperty("user.home");
File downloadDir = new File(home + "/Downloads/");
if (downloadDir.exists() && !downloadDir.isDirectory()) {
return home;
} else {
downloadDir = new File(downloadDir + "/");
if ((downloadDir.exists() && downloadDir.isDirectory()) || downloadDir.mkdirs()) {
return downloadDir.getPath();
} else {
return home;
}
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
downloadExecutable("test");
}
}
This worked beautifully.

Choosing a txt file with JFileChooser and making it appear on a JTextField just won't work

When I press open another window appears with JFileChooser to select the file again, and when I try to select the file again it just gives me "open command canceled by user" message. The program stops working and ends with an unknown exception.
Here is my code:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileC extends JFrame {
File file;
JFileChooser chooser = new JFileChooser();
JTextArea TArea = new JTextArea();
public FileC()
{
super.setLayout(new FlowLayout());
super.add(chooser);
super.add(TArea);
FileNameExtensionFilter filter = new FileNameExtensionFilter ( "text files " , "txt");
chooser.setFileFilter(filter);
ActionHandler handler = new ActionHandler ();
chooser.addActionListener(handler);
}
private class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent e) {
int returnVal = chooser.showOpenDialog(FileC.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null,"Open command cancelled by user.");
}
try {
BufferedReader in = new BufferedReader ( new FileReader (file));
String s = in.readLine();
while (s != null)
{
TArea.append(s);
s = in.readLine();
}
}catch (FileNotFoundException z){ JOptionPane.showMessageDialog(null, "file not found"); }
catch (IOException z) { z.printStackTrace(); }
}
}
}
the new codes
public class FileC extends JFrame {
File file;
JFileChooser chooser = new JFileChooser();
JTextArea TArea = new JTextArea();
JButton b = new JButton("open");
public FileC()
{
TArea.setRows(10);
TArea.setColumns(20);
super.setLayout(new FlowLayout());
super.add(TArea);
super.add(b);
FileNameExtensionFilter filter = new FileNameExtensionFilter ( "text files " , "txt");
chooser.setFileFilter(filter);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
chooser.showOpenDialog(FileC.this);
}
});
chooser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int returnVal = chooser.showOpenDialog(FileC.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null,"Open command cancelled by user.");
}
try {
BufferedReader in = new BufferedReader ( new FileReader (file));
String s = in.readLine();
while (s != null)
{
TArea.append(s);
s = in.readLine();
}
in.close();
}catch (FileNotFoundException z){ JOptionPane.showMessageDialog(null, "file not found"); }
catch (IOException z) { z.printStackTrace(); }
}
});
}
}
As an example...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;
public class FileChooserExample {
public static void main(String[] args) {
new FileChooserExample();
}
public FileChooserExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton open;
private JTextArea textArea;
private JFileChooser chooser;
public TestPane() {
setLayout(new BorderLayout());
open = new JButton("Open");
textArea = new JTextArea(20, 40);
add(new JScrollPane(textArea));
add(open, BorderLayout.SOUTH);
open.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (chooser == null) {
chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
chooser.addChoosableFileFilter(new FileFilter() {
#Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
}
#Override
public String getDescription() {
return "Text Files (*.txt)";
}
});
}
switch (chooser.showOpenDialog(TestPane.this)) {
case JFileChooser.APPROVE_OPTION:
try (BufferedReader br = new BufferedReader(new FileReader(chooser.getSelectedFile()))) {
textArea.setText(null);
String text = null;
while ((text = br.readLine()) != null) {
textArea.append(text);
textArea.append("\n");
}
textArea.setCaretPosition(0);
} catch (IOException exp) {
exp.printStackTrace();
JOptionPane.showMessageDialog(TestPane.this, "Failed to read file", "Error", JOptionPane.ERROR_MESSAGE);
}
break;
}
}
});
}
}
}
Take a look at How to use file choosers for more details

Trying to read a text file into a JTextArea

I'm trying to open a text file and add its value into a String variable to then set in a JTextArea. No matter what I do it always returns nothing in the textarea.
I want it change the text like it does when you hit the clear button, but I want to change it to what's in the Test.txt file it makes.
package texteditor;
import java.awt.FlowLayout;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class GUI extends JFrame {
//GUI Variables
private JButton save;
private JButton clear;
private JButton copy;
private JButton paste;
private JButton open;
private JTextArea textField;
private StringSelection stringSelection;
private Clipboard clipboard;
String textFieldWritable;
public GUI() {
super("Text Editor");
//Sets Layout
setLayout(new FlowLayout());
save = new JButton("Save");
add(save);
clear = new JButton("Clear");
add(clear);
open = new JButton("Open");
add(open);
textField = new JTextArea(10, 35);
add(textField);
handler handle = new handler();
save.addActionListener(handle);
clear.addActionListener(handle);
}
private class handler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == save) {
textFieldWritable = String.format("%s", textField.getText());
try {
FileWriter fileWrite = new FileWriter("Text.txt");
PrintWriter printWrite = new PrintWriter(fileWrite);
printWrite.println(textFieldWritable);
printWrite.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Error, File Already Exists!", "Error",
JOptionPane.ERROR_MESSAGE);
}
} else if (event.getSource() == clear) {
textField.setText("");
} else if (event.getSource() == open) {
try {
FileReader fileReader = new FileReader("Text.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputFile = "";
String textFieldReadable = bufferedReader.readLine();
while (textFieldReadable != null) {
inputFile += textFieldReadable;
textFieldReadable = bufferedReader.readLine();
}
System.out.println("inputFile");
} catch (FileNotFoundException ex) {
System.out.println("no such file exists");
} catch (IOException ex) {
System.out.println("unkownerror");
}
}
}
}
}
To me, it looks like you never set the text you've read to the text area.
try {
FileReader fileReader = new FileReader("Text.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputFile = "";
String textFieldReadable = bufferedReader.readLine();
while (textFieldReadable != null){
inputFile += textFieldReadable;
textFieldReadable = bufferedReader.readLine();
}
System.out.println("inputFile");
// Opps //
textField.setText(inputFile);
}
catch (FileNotFoundException ex) {
System.out.println("no such file exists");
}
catch (IOException ex) {
System.out.println("unkownerror");
}
Personally, I'd just use the functionality provide by JTextComponent and pass it a Reader and allow it to read itself.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TextAreaReadTest {
public static void main(String[] args) {
new TextAreaReadTest();
}
public TextAreaReadTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
public TestPane() {
setLayout(new BorderLayout());
textArea = new JTextArea(10, 80);
add(new JScrollPane(textArea));
JButton read = new JButton("Read");
read.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Reader reader = null;
try {
reader = new FileReader(new File("D:/SWANH.txt"));
textArea.read(reader, "The force is strong with this one");
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception exp) {
}
}
}
});
add(read, BorderLayout.SOUTH);
}
}
}
This Code Worked for me
public DisplayText() throws IOException {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textArea.setBounds(15, 13, 424, 210);
textArea.setEditable(false);
contentPane.add(textArea);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setBounds(12, 12, 424, 185);
contentPane.add(scrollPane);
JButton btnPatchDetails = new JButton("Details");
btnPatchDetails.setBounds(135, 234, 137, 25);
contentPane.add(btnPatchDetails);
btnPatchDetails.addActionListener(this);
btnPatchDetails.setActionCommand("Patch Details");
JButton btnNext = new JButton("Next");
btnNext.setBounds(314, 234, 107, 25);
contentPane.add(btnNext);
JLabel lblDependancyPatchAvailable = new JLabel("Dependancy Patch Available : ");
lblDependancyPatchAvailable.setBounds(22, 209, 220, 15);
contentPane.add(lblDependancyPatchAvailable);
lblAvailability.setBounds(254, 209, 61, 15);
contentPane.add(lblAvailability);
}
public void actionPerformed(ActionEvent e) {
if ("Patch Details".equals(e.getActionCommand())) {
BufferedReader reader = null;
JarFile jarFile = null;
try {
String inputFile = "readMe/tempReadme.txt";
String write;
jarFile = new JarFile(inputJar);
JarEntry entry = jarFile.getJarEntry(inputFile);
reader = new BufferedReader(new InputStreamReader(jarFile.getInputStream(entry)));
String line,searchStr = "Patch Details",endStr = "Problem:";
boolean readFlag = false;
boolean writeFlag = false;
while ((line = reader.readLine()) != null) {
if (line.trim().contains(searchStr)) {
readFlag = true;
}
if (line.trim().equals(endStr)) {
break;
}
if (readFlag) {
StringTokenizer tempTokenizer = new StringTokenizer(line,"");
while (tempTokenizer.hasMoreElements()) {
write = tempTokenizer.nextToken();
textArea.append(write + "\n");
}
}
writeFlag = true;
}
if(writeFlag){
lblAvailability.setText("YES");
} else {
lblAvailability.setText("");
}
lblAvailability.getText();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
jarFile.close();
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

Can't access variables for SwingWorker

I am trying to get this SwingWorker to function correctly. However,the variables that need to be accessed seem to be not global. What do I do? I tried adding static but it creates more errors and complications later about accessing static from non static. The variables that are not working in the SwingWorker are the LOCAL_FILE and URL_LOCATION variables.
package professorphysinstall;
//Imports
import com.sun.jmx.snmp.tasks.Task;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import javax.tools.FileObject;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
public class ProfessorPhysInstall {
/**
* #param args the command line arguments
*/
static class Global {
public String location;
}
public static void main(String[] args) {
// TODO code application logic here
//Variables
final JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
final JPanel cards = new JPanel(new CardLayout());
final CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(TextPaneScreen1);
JTextArea TextAreaScreen1 = new JTextArea();
JScrollPane sbrText = new JScrollPane(TextAreaScreen1);
TextAreaScreen1.setRows(15);
TextAreaScreen1.setColumns(40);
TextAreaScreen1.setEditable(false);
TextAreaScreen1.setText("stuff");
TextAreaScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextAreaScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(sbrText);
final JCheckBox Acceptance = new JCheckBox();
Acceptance.setText("I Accept The EULA Agreenment.");
screen1.add(Acceptance);
final JButton NextScreen1 = new JButton();
NextScreen1.setText("Next");
NextScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.next(cards);
}
});
screen1.add(NextScreen1);
JButton CancelScreen1 = new JButton();
CancelScreen1.setText("Cancel");
CancelScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen1.add(CancelScreen1);
cards.add(screen1);
//Screen2
final JPanel screen2 = new JPanel();
JPanel screen3 = new JPanel();
JTextPane TextPaneScreen2 = new JTextPane();
TextPaneScreen2.setEditable(false);
TextPaneScreen2.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher. Professor Phys will be installed there.");
TextPaneScreen2.setSize(358, 48);
TextPaneScreen2.setLocation(0, 0);
TextPaneScreen2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen2.setMargin(new Insets(4,4,4,4));
screen2.add(TextPaneScreen2);
JLabel screen2instructions = new JLabel();
screen2instructions.setText("Launcher Location: ");
screen2.add(screen2instructions);
final JTextField folderlocation = new JTextField(25);
screen2.add(folderlocation);
final JButton Browse = new JButton();
final JLabel filelocation = new JLabel();
final JLabel filename = new JLabel();
Browse.setText("Browse");
Browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Create a file chooser
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(screen2);
folderlocation.setText(fc.getSelectedFile().getAbsolutePath());
filelocation.setText(fc.getCurrentDirectory().getAbsolutePath());
filename.setText(fc.getSelectedFile().getName());
}
});
screen2.add(filelocation);
screen2.add(filename);
screen3.add(filelocation);
filelocation.setVisible(false);
filename.setVisible(false);
screen2.add(Browse);
final JButton BackScreen2 = new JButton();
BackScreen2.setText("Back");
BackScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen2.add(BackScreen2);
final JButton NextScreen2 = new JButton();
NextScreen2.setText("Next");
NextScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Checking Code
String correctname = "Future_Retro_Gaming_Launcher.jar";
if (filename.getText().equals(correctname))
{
cl.next(cards);
}
else
{
JFrame popup = new JFrame();
popup.setBounds(0, 0, 380, 100);
Label error = new Label();
error.setText("Sorry you must select your Future_Retro_Gaming_Launcher.jar");
popup.add(error);
popup.show();
}
}
});
screen2.add(NextScreen2);
JButton CancelScreen2 = new JButton();
CancelScreen2.setText("Cancel");
CancelScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen2.add(CancelScreen2);
cards.add(screen2);
//Screen3
JTextPane TextPaneScreen3 = new JTextPane();
TextPaneScreen3.setEditable(false);
TextPaneScreen3.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen3.setText("Professor Phys will be instaleld in the directory you have chosen. Please make sure\nyour launcher is in that folder or the game will not work.\nClick next to begin the install process.");
TextPaneScreen3.setSize(358, 48);
TextPaneScreen3.setLocation(0, 0);
TextPaneScreen3.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen3.setMargin(new Insets(4,4,4,4));
screen3.add(TextPaneScreen3);
final JButton BackScreen3 = new JButton();
BackScreen3.setText("Back");
BackScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen3.add(BackScreen2);
final JButton NextScreen3 = new JButton();
NextScreen3.setText("Next");
NextScreen3.addActionListener(new ActionListener() {
#Override
#SuppressWarnings({"null", "ConstantConditions"})
public void actionPerformed(ActionEvent ae) {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(filelocation.getText());
String URL_LOCATION = "https://dl.dropboxusercontent.com/u/10429987/Future%20Retro%20Gaming/ProfessorPhys.iso";
String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(LOCAL_FILE+"professorphys.iso", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
});
screen3.add(NextScreen3);
JButton CancelScreen3 = new JButton();
CancelScreen3.setText("Cancel");
CancelScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen3.add(CancelScreen3);
System.out.println("Done");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
screen3.add(progress);
cards.add(screen3);
mainframe.add(cards);
mainframe.setVisible(true);
}
}
class DownloadWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Your program is mostly a huge static main method. You're kind of getting the cart in front of the horse trying to do advanced programming such as with SwingWorker before first creating clean OOP code. In other words -- start over and do it right. Then the connections between classes will be much more natural and it will be much easier to get things to work right. The main method should only concern itself with starting the Swing event thread, creating a GUI object in that thread, and displaying it. Everything else should be in classes that create objects.
Also, on a more practical level, you have yet to tell us what variables are causing you trouble or what errors you might be seeing. Also, where are you trying to create and execute the SwingWorker?
Edit
One tip that will likely help: Give your SwingWorker class a constructor, and pass important parameters into your SwingWorker object via constructor parameters. Then use those parameters to initialize class fields that will be used in the SwingWorker's doInBackground method.
e.g.,
class DownloadWorker extends SwingWorker<Integer, Integer>
{
private String urlLocation;
private String localFile;
public DownLoadWorker(String urlLocation, String localFile) {
this.urlLocation = urlLocation;
this.localFile = localFile;
}
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(urlLocation);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(localFile +"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Read from a file containing integers - java

I am trying to read from a file that contains three numbers. The file looks like this:
45
20
32
My code is below:
import java.awt.Color;
import java.awt.Desktop.Action;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.Timer;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JSlider;
import javax.swing.border.TitledBorder;
public class practise implements ActionListener {
int menuCount = 0;
int [] fileValues = new int[3];
JFrame frame1 = new JFrame();
JPanel[] panels = new JPanel[3];
JMenuItem menuitemMyDialog1 = new JMenuItem( "Open File" );
JMenuItem menuitemMyDialog2 = new JMenuItem( "EXIT" );
JMenuBar menuBar = new JMenuBar( );
JMenu menuData = new JMenu( "Menu" );
Label label = new Label();
JSlider slider = new JSlider( JSlider.VERTICAL,0,100,20);;
Timer timer = new Timer(1000,new TimerAction());
void go(){
frame1.setTitle("Referred Coursework");
frame1.setSize(600, 300);
frame1.setVisible(true);
buildGUI();
menuitemMyDialog1.addActionListener( this );
menuData.add( menuitemMyDialog1 );
//buildGUI();
menuitemMyDialog2.addActionListener( this );
menuData.add( menuitemMyDialog2 );
menuBar.add( menuData );
frame1.setJMenuBar( menuBar );
}
int b = 0;
class TimerAction implements ActionListener{
public void actionPerformed(ActionEvent e){
if(b == 3){ timer.stop(); }
slider.setValue(fileValues[b]);
b++;
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource() == menuitemMyDialog1){
menuCount = 1;
String inputValue = JOptionPane.showInputDialog("File Open dialog box");
label.setSize(80,80);
label.setText(inputValue);
label.setLocation(40,160);
//fileValues[1] = 27; fileValues[0] = 2; fileValues[2] = 62;
try {
FileReader file = new FileReader("temperature.txt");
BufferedReader buf = new BufferedReader(file);
int i = 0;
String s = null;
while((s = buf.readLine()) != null){
fileValues[i] = Integer.parseInt(s);
i++;
}
}catch (Exception e){e.printStackTrace();}
Arrays.sort(fileValues);
for (int i : fileValues){
System.out.println(i);
}
timer.start();
}
if(arg0.getSource() == menuitemMyDialog2){
frame1.dispose();
System.exit(0);
}
}
public void buildGUI(){
layoutComponents();
}
public void layoutComponents(){
JLabel label1 = new JLabel();
JSlider slider2,slider3;
//JProgressBar bar = new JProgressBar( JProgressBar.VERTICAL,1000, 1020 );
panels[0] = new JPanel();
panels[1] = new JPanel();
panels[2] = new JPanel();
panels[1].setBorder( new TitledBorder( "Temperature" ) );
slider.setMajorTickSpacing(20);
slider.setPaintTicks( true );
slider.setPaintLabels( true );
slider.setMinorTickSpacing(10);
panels[1].add( slider );
panels[1].setBackground(Color.orange);
frame1.setLayout( new GridLayout( 1,2 ) );
for ( int i = 0; i < panels.length;i++ ){
frame1.add( panels[i] );
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
practise obj = new practise();
obj.go();
}
}
The program compiles alright and gives no errors. But when I output the contents of the array fileValues I get:
0
0
0
Any help would be appreciated. Thanks!
Update I reviewed the exception for FileReader and now it is showing a FileNotFoundException. This is strange as the file exists in the project folder. Any suggestions??
You need to provide the full path for "temperature.txt".
You ignore the exceptions sent by your I/O operations:
try {
FileReader file = new FileReader("temperature.txt");
BufferedReader buf = new BufferedReader(file);
int i = 0;
String s = null;
while ((s = buf.readLine()) != null) {
fileValues[i] = Integer.parseInt(s);
i++;
}
} catch (Exception e) {
}
If you replace the catch block by something like:
} catch (Exception e) {
System.out.println(e.getMessage());
}
You should get a self explanatory message.

Categories