I'm writing code that implements ActionListener, so in my actionPerformed() function (which is necessary when implementing ActionListener) I have used event.getSource() in each of my if/else clauses to find which JComponent was triggered (because I have multiple JComponents in my code). But for some reason only the first if statement is triggered by its JComponent. Code is below. Thanks in advance for any help.
This is the code my question is focused on:
public void actionPerformed(ActionEvent event) {
if (event.getSource() == newProj || event.getSource() == newFlick) {
String nameProj = JOptionPane.showInputDialog("Name of your Flick:");
int option = 0;
JFileChooser dirChooser = new JFileChooser();
if (nameProj != null) {
dirChooser.setCurrentDirectory(new File("~"));
dirChooser.setDialogTitle("Choose Directory");
dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
dirChooser.setAcceptAllFileFilterUsed(false);
option = dirChooser.showOpenDialog(this);
}
if (option == JFileChooser.APPROVE_OPTION) {
File dir = dirChooser.getSelectedFile();
String dirPath = dir.getAbsolutePath();
String newDirPath = dirPath + "\\" + nameProj;
new File(newDirPath).mkdir();
File config = null;
try {
config = new File(newDirPath + "\\.flick.flick");
if (!config.exists()) {
config.createNewFile();
}
PrintWriter writer = new PrintWriter(config);
writer.append("*WARNING - TAMPERING WITH THIS DATA COULD LEAD TO PROBLEMS IN YOUR FLICK.* \n");
writer.append("Project Name: " + nameProj + "\n");
writer.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Error: " + e, null, JOptionPane.ERROR_MESSAGE);
} catch (UnsupportedEncodingException e) {
JOptionPane.showMessageDialog(null, "Error: " + e, null, JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error: " + e, null, JOptionPane.ERROR_MESSAGE);
}
dispose();
new Flick(nameProj);
} else if (event.getSource() == loadProj || event.getSource() == loadFlick) {
JOptionPane.showMessageDialog(null, "Loaded");
option = 0;
dirChooser = new JFileChooser();
dirChooser.setCurrentDirectory(new File("~"));
dirChooser.setDialogTitle("Load Flick Directory");
dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
dirChooser.setAcceptAllFileFilterUsed(false);
option = dirChooser.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
File dir = dirChooser.getSelectedFile();
File config = new File(dir + "\\.flick");
if (config.exists()) {
dispose();
new Flick(config.getName());
} else {
JOptionPane.showMessageDialog(null, "Error: Not A Flick Directory", null, JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}
Here is the rest of the code that came before the previous code:
package com.shreypandya.flickstudios;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Home extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JLabel title = new JLabel("Welcome to FlickStudios!");
MenuBar menuBar = new MenuBar();
Menu file = new Menu("File");
MenuItem newProj = new MenuItem("New Flick");
MenuItem loadProj = new MenuItem("Load Flick");
JButton newFlick = new JButton("New Flick");
JButton loadFlick = new JButton("Load Flick");
Panel panel = new Panel();
public Home() throws FontFormatException, IOException {
super("FlickStudios");
InputStream myStream = new BufferedInputStream(new FileInputStream("Resources/OpenSans.ttf"));
Font ttf = Font.createFont(Font.TRUETYPE_FONT, myStream);
Font openSans = ttf.deriveFont(Font.PLAIN, 16);
add(panel);
panel.setLayout(new BorderLayout());
panel.add(title, BorderLayout.PAGE_START);
title.setFont(openSans.deriveFont(Font.PLAIN, 36));
panel.add(newFlick, BorderLayout.LINE_START);
newFlick.setFont(openSans);
newFlick.setFocusPainted(false);
newFlick.addActionListener(this);
panel.add(loadFlick, BorderLayout.LINE_END);
loadFlick.setFont(openSans);
loadFlick.setFocusPainted(false);
loadFlick.addActionListener(this);
setMenuBar(menuBar);
menuBar.add(file);
file.add(newProj);
newProj.addActionListener(this);
newProj.setShortcut(new MenuShortcut(KeyEvent.VK_N, false));
file.add(loadProj);
loadProj.addActionListener(this);
loadProj.setShortcut(new MenuShortcut(KeyEvent.VK_L, false));
setExtendedState(JFrame.MAXIMIZED_BOTH);
setVisible(true);
setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
}
The first if encapsulates your entire function:
public void actionPerformed(ActionEvent event) {
if (event.getSource() == newProj || event.getSource() == newFlick) {
if (nameProj != null) {
}
if (option == JFileChooser.APPROVE_OPTION) {
} else if (event.getSource() == loadProj || event.getSource() == loadFlick) {
if (option == JFileChooser.APPROVE_OPTION) {
if (config.exists()) {
} else {
}
}
}
}
}
I don't think this is as you intend, and would certainly explain why no inner blocks are being reached when the first if evaluates to false.
Your braces are mismatched.
This if (event.getSource() == newProj || event.getSource() == newFlick) { does not end until:
} else {
JOptionPane.showMessageDialog(null, "Error: Not A Flick Directory", null, JOptionPane.ERROR_MESSAGE);
}
}
}
}//HERE
Therefore, if the first if statement fails, your function ends, and never checks the other conditions.
Related
I am trying to get information from inside a void actionEvent so I can use it for JUnit test ( first time trying to use JUnit ). But i am not sure how to do this. If anyone can throw some guidance, i would appreciate it.
Here is my code below. (this code it just to use with test with JUnit, i know its garbage sauce.
import java.awt.Container;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.UnknownHostException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class frameIt extends JFrame implements ActionListener {
Container cont = getContentPane();
JLabel uL = new JLabel("USER");
JLabel pL = new JLabel("PASS");
JTextField userT1 = new JTextField();
JPasswordField pass1 = new JPasswordField();
JButton logButt = new JButton("LOGIN");
JButton reButt = new JButton("RESET");
frameIt() {
cont.setLayout(null);
uL.setBounds(20, 50, 50, 20);
pL.setBounds(20, 80, 50, 20);
userT1.setBounds(70, 50, 100, 30);
pass1.setBounds(70, 80, 100, 30);
logButt.setBounds(70, 100, 100, 30);
reButt.setBounds(70, 130, 100, 30);
cont.add(logButt);
cont.add(reButt);
cont.add(uL);
cont.add(pL);
cont.add(userT1);
cont.add(pass1);
logButt.addActionListener(this);
reButt.addActionListener(this);
}
//auditing
public String theLog(String user, String eventType) throws UnknownHostException {
//UTC date and time string
OffsetDateTime dateTimeUTC = OffsetDateTime.now(ZoneOffset.UTC);
// create date and time string
Date dateTimeLocal = Date.from(dateTimeUTC.toInstant());
// create filewriter, bufferedwriter, and printwriter
FileWriter FWrite = null;
BufferedWriter buffWrite = null;
PrintWriter printerWrite = null;
// try block
try {
// create file
File logFile = new File("Log.log");
// check if file already exists
// if file does not exist then create it
if (!logFile.exists()) {
logFile.createNewFile();
}
//filewriter, bufferedwriter, and printwriter
FWrite = new FileWriter(logFile, true);
buffWrite = new BufferedWriter(FWrite);
printerWrite = new PrintWriter(buffWrite);
//printwriter
printerWrite.println("----------------------");
printerWrite.println("UTC Date/Time: " + dateTimeUTC);
printerWrite.println("Local Date/Time: " + dateTimeLocal);
printerWrite.println("User name: " + user);
printerWrite.println("Event type: " + eventType);
printerWrite.println("----------------------");
printerWrite.println("");
}
// catch block
catch (IOException e) {
System.out.println("Sorry, there was an error.");
} finally {
// printwriter
printerWrite.close();
}
return null;
}
public void actionPerformed(ActionEvent aE) {
if (aE.getSource() == reButt) {
userT1.setText("");
pass1.setText("");
}
if (aE.getSource() == logButt) {
String userText = userT1.getText();
String pwdText = String.valueOf(pass1.getPassword());
try {
if (userText.equals("admin") && pwdText.equals("admin")) {
theLog(userText, "Good Login");
JOptionPane.showMessageDialog(this, "Login Correct");
} else {
JOptionPane.showMessageDialog(this, "try again");
theLog(userText, "Failed Login");
}
}
catch (IOException ex) {
Logger.getLogger(frameIt.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) {
//calling frameIt.java
frameIt frame = new frameIt();
//title
frame.setTitle("Sign on Forever");
//Want to see it? this is how!
frame.setVisible(true);
//Window size
frame.setBounds(15, 15, 300, 300);
//exits
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You ca see this article here: https://examples.javacodegeeks.com/core-java/junit/junit-test-void-method-example/
I found instead of trying to do this, its easier to cast the ActionEvent's from the button click to the auth. Such as this.
btnLogout.setOnAction((ActionEvent e) -> {
doLogin();
});
and put everything else in the doLogin.
#Spindoctor s answer is good though and should be counted.
===============================================
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.
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
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.
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.