Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to read a file that changes dynamically and display its contents in jTextArea.
I am using buffered reader for reading.
I have tried to display the contents on console and it works fine, but doesn't work with jTextArea.
I am doing something like
while(true)
{
line = br.readLine();
if(line == null)
Thread.sleep();
else
System.out.println(line);
}
Any help would be appreciated. Thanks
Don't use Thread.sleep(), you will block the EDT. Instead use a javax.swing.Timer if you want to "animate" the results. Just read each line each iteration of the timer, until it reaches the end of the file, then stop the timer
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
String line;
try {
if ((line = reader.readLine()) != null) {
textArea.append(line + "\n");
} else {
((Timer) e.getSource()).stop();
}
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
Test this program out. I think it works the way you want it to.
import java.awt.BorderLayout;
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.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ReadFile {
File file = null;
BufferedReader reader = null;
private Timer timer = null;
private JTextArea textArea;
private JTextField jtfFile;
private String fileName;
private JButton browse;
private JFrame frame;
public ReadFile() {
textArea = new JTextArea(25, 60);
frame = new JFrame("Show Log");
browse = new JButton("Browse");
browse.addActionListener(new ShowLogListener());
jtfFile = new JTextField(25);
jtfFile.addActionListener(new ShowLogListener());
timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
String line;
try {
if ((line = reader.readLine()) != null) {
textArea.append(line + "\n");
} else {
((Timer) e.getSource()).stop();
}
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
JPanel panel = new JPanel();
panel.add(new JLabel("File: "));
panel.add(jtfFile);
panel.add(browse);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(textArea), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class ShowLogListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
fileName = file.getName();
jtfFile.setText(fileName);
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
timer.start();
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new ReadFile();
}
});
}
}
2 points:
Don't call Thread.sleep() in the EDT. This blocks the UI and prevents UI updates
JTextArea has a read method that allows files to be loaded
Example:
JTextArea textArea = new JTextArea();
textArea.read(new FileReader("input.txt"), "blah");
String line;
String textToDisplay = "";
while((line = br.readLine()) != null)
textToDisplay+=line;
textArea.setText(textToDisplay);
I used setText(String) instead of append(String) because it'll replace what is already is in the JTextArea... From your question I felt that's what you wanted to do.
You have to set the text of the text area..try doing so:
{
line = br.readLine();
if(line == null)
Thread.sleep();
else
textArea.append(line + "\n");
}
this will append (put text at end) of the file, meaning that you will not have to worry about text being deleted each time it runs
that should work, hope it helps
Related
===============================================
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.
This JFrame the first time I call it when the application is running, works perfectly. But when I try to open a new file, the progress bar is meant to return to the screen. See the screen grabs to see how it should look at how it looks thereafter.
public ArrayList<Data> handleData(File fileToOpen) throws FileNotFoundException {
ArrayList<Data> handle = new ArrayList<Data>();
//clear the arraylist the second time round
handle.clear();
BufferedReader reader = new BufferedReader(new FileReader(fileToOpen));
//buffer used for scanner
int lines = 0;
//find out the value of lines here
JFrame loader = new JFrame();
JPanel loadPanel = new JPanel();
JProgressBar progressBar = new JProgressBar(0, lines);
JLabel label = new JLabel();
loader.setDefaultCloseOperation(EXIT_ON_CLOSE);
label.setText("Loading Data...");
loadPanel.add(label);
loadPanel.add(progressBar);
loader.add(loadPanel);
loader.pack();
loader.setVisible(true);
//Do a load of stuff which increments the progress bar
loader.setVisible(false);
return handle;
}
This is how the progress bar and JFrame should look:
This Is how the progress bar looks the second time:
All code:
package Default;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class ReadIn extends JFrame {
public File openFile() {
File fileToOpen = null;
JFileChooser fileChooser = new JFileChooser();
int modalToComponent = fileChooser.showOpenDialog(this);
if (modalToComponent == JFileChooser.APPROVE_OPTION) {
fileToOpen = fileChooser.getSelectedFile();
} else if (modalToComponent == JFileChooser.CANCEL_OPTION) {
System.exit(1);
}
return fileToOpen;
}
public ArrayList<Data> handleData(File fileToOpen) throws FileNotFoundException {
ArrayList<Data> handle = new ArrayList<Data>();
handle.clear();
BufferedReader reader = new BufferedReader(new FileReader(fileToOpen));
int lines = 0;
try {
while (reader.readLine() != null)
lines++;
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Scanner sc = new Scanner(fileToOpen);
System.out.println(sc.nextLine());
System.out.println(sc.nextLine());
System.out.println("Reading Data...");
sc.nextLine();
String split = sc.nextLine();
Scanner splitter = new Scanner(split);
JDialog loader = new JDialog();
JPanel loadPanel = new JPanel();
JProgressBar progressBar = new JProgressBar(0, lines);
JLabel label = new JLabel();
loader.setDefaultCloseOperation(HIDE_ON_CLOSE);
label.setText("Loading Data...");
loadPanel.add(label);
loadPanel.add(progressBar);
loader.add(loadPanel);
loader.pack();
loader.setVisible(true);
while (splitter.hasNext()) {
String peek = splitter.next();
if (peek.equals("Timestamp")) {
peek = peek + splitter.next();
}
Data temp = new Data();
temp.setHeading(peek);
handle.add(temp);
}
while (sc.hasNextDouble()) {
progressBar.setValue(progressBar.getValue() + 1);
for (int i = 0; i < handle.size(); i++) {
handle.get(i).getValues().add(sc.nextDouble());
}
}
System.out.println("Data Loaded");
splitter.close();
sc.close();
loader.setVisible(false);
System.out.println("On EDT?: " + SwingUtilities.isEventDispatchThread());
return handle;
}
}
Without your posting a valid minimal example program, it's impossible for us to know with absolute surety the cause of your problem, the image suggests that it's a Swing threading problem, that you've got long-running code, probably here:
//Do a load of stuff which increments the progress bar
that is blocking the Swing event thread, and that this is causing the Swing GUI not to paint itself.
If so, the solution is to improve your code so that it respects the Swing event thread, so that long-running code is run in a background thread such as via a SwingWorker.
Other issues: that window you display looks to be a "dependent" window and not a main application window. If so, it should not be created as a JFrame but rather as a JDialog, either modal or non-modal depending on your needs.
Also -- why does it work the first time? Likely the first time, the code above is not run on the Swing event thread, the EDT, while the second time that code is called, it is in fact run on the EDT. You can test this by calling SwingUtilities.isEventDispatchThread() and printing out the result. e.g.,
System.out.println("On EDT?: " + SwingUtilities.isEventDispatchThread());
For example:
import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
public class UpdateDataEg extends JPanel {
protected static final int MAX_LINES = 200;
public UpdateDataEg() {
setPreferredSize(new Dimension(500, 400));
add(new JButton(new UpdateDataAction("Update Data", KeyEvent.VK_U)));
}
// this must be a void method as you'll get the result from a callback, not
// from this method
public void handleData(final File fileToOpen) {
int lines = 0;
// find out the value of lines here
Window window = SwingUtilities.getWindowAncestor(UpdateDataEg.this);
JDialog loader = new JDialog(window, "Progress", ModalityType.APPLICATION_MODAL);
JPanel loadPanel = new JPanel(new BorderLayout());
final JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setStringPainted(true);
JLabel label = new JLabel();
label.setText("Loading Data...");
loadPanel.add(label, BorderLayout.PAGE_START);
loadPanel.add(progressBar);
loader.add(loadPanel);
loader.pack();
loader.setLocationRelativeTo(window);
final SwingWorker<ArrayList<Data>, Void> myWorker = new SwingWorker<ArrayList<Data>, Void>() {
#Override
protected ArrayList<Data> doInBackground() throws Exception {
ArrayList<Data> handle = new ArrayList<Data>();
// clear the arraylist the second time round
handle.clear();
int lines = 0;
// !! BufferedReader reader = new BufferedReader(new FileReader(fileToOpen));
// !! long code here to do calculations and place into ArrayList<Data>
// emulated by Thread.sleep
// !! set progress property here so that listener can update
while (lines < MAX_LINES) {
lines += (int) (10 * Math.random());
int myProgress = (int) ((lines * 100) / MAX_LINES);
myProgress = Math.min(100, myProgress);
setProgress(myProgress);
Thread.sleep(200);
}
return handle;
}
};
// our callback
myWorker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (pcEvt.getPropertyName().equals("progress")) {
int progress = myWorker.getProgress();
progressBar.setValue(progress);
} else if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
// if the worker has finished
loader.setVisible(false);
try {
ArrayList<Data> data = myWorker.get();
// use data here
} catch (InterruptedException | ExecutionException e) {
// TODO handle the exceptions
e.printStackTrace();
}
}
}
});
myWorker.execute();
// if the dialog is modal, this must be last
loader.setVisible(true);
// delete this call as this would be done from the callback
// loader.setVisible(false);
// delete this as this is obtained in the callback
// return handle;
}
private class UpdateDataAction extends AbstractAction {
public UpdateDataAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
handleData(new File("Foobar.txt"));
}
}
private static void createAndShowGui() {
UpdateDataEg mainPanel = new UpdateDataEg();
JFrame frame = new JFrame("UpdateDataEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Data {
}
Hey I need some help with my code..
I want it to say 'logged on' when the 'Pass' and 'getPass' is the same.
and if its not its says 'logged off'.. but it says that all the time even if its correct. :/. Can Someone Help Me :(
p.s
sorry For My Bad English xd
package ca.sidez.main;
import java.awt.EventQueue;
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.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private static JTextField txtName;
private static JTextField txtPass;
public static String Pass;
public static String Pass2;
public static String getPass;
public static String getName;
public static String File;
public Main() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e1) {
e1.printStackTrace();
}
setResizable(false);
setTitle("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(380, 380);
setLocation(100, 100);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtName = new JTextField();
txtName.setBounds(67, 50, 165, 28);
contentPane.add(txtName);
txtName.setColumns(10);
txtPass = new JTextField();
txtPass.setBounds(67, 100, 165, 28);
contentPane.add(txtPass);
txtPass.setColumns(20);
JLabel lblName = new JLabel("Login");
lblName.setBounds(127, 20, 100, 30);
contentPane.add(lblName);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File = txtName.getText();
Share();
}
});
btnLogin.setBounds(60, 311, 117, 29);
contentPane.add(btnLogin);
}
public static void Share() {
try {
//Checks if The Username Exists.
File file = new File(File + ".txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
Pass = stringBuffer.toString();
getPass = txtPass.getText();
getName = txtName.getText();
System.out.println("Clients Password: " + getPass + " For Acc '" + getName + "' ");
System.out.println("The Correct Password For Acc: " + getName + " Is: " + Pass);
if(Pass == getPass) {
System.out.println("Logged In");
} else {
System.out.println("Logged Out");
}
} catch (IOException e) {
System.out.println("Wrong Username Or Password");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
There are probably many issues with the code you have posted but one of them, and perhaps this is why it is not working as you think it should, is the adding of a newline to the stringbuffer:
stringBuffer.append(line);
stringBuffer.append("\n");
This would make the password in the file "mySecretPassword\n" which will not evaluate to true when compared to "mySecretPassword" using Equals (assuming that is the password in the file and what the user entered in the password field).
Your code would also not work if there is more than one line in the password file. If the assumption is that there will be only one line in the file and it is the password to verify against, then read only one line.
if(Pass == getPass)
Should really be:
if(Pass.compareTo(getPass) == 0)
or
if(Pass.equals(getPass))
Are how you actually compare the content of the string.
if(Pass == getPass)
Is how you compare to see if they are both references to the same object.
Another Problem
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
Pass = stringBuffer.toString();
Adds a new line to the end of Pass
You just want
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
fileReader.close();
Pass = stringBuffer.toString();
I'm having an issue using a JTextArea within a scrollpane. I can read from a textfile, but the contents are all showing up on one line. I have tried various methods using append and trying to break the line, but with no success.
import java.awt.Dimension;
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.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class SplashScreen extends JFrame implements ActionListener
{
JButton mobile;
JButton browser;
JLabel welc;
JPanel home;
File file = new File("C:\\Users\\Jimbob\\Desktop\\DisWorkspace\\TrustWizard\\welcometwo.txt");
BufferedReader reader = null;
int lines = 10;
public String read()
{
String savetext = "";
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while((text = reader.readLine()) != null)
{
savetext += text;
}
}
catch(IOException jim)
{
jim.printStackTrace();
}
return savetext;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals(mobile))
{
MobileHome openB = new MobileHome();
this.dispose();
}
if(e.getSource().equals(browser))
{
BrowserHome openB = new BrowserHome();
this.dispose();
}
}
public SplashScreen()
{
super("Trust Wizard");
JTextArea homeText = new JTextArea(25, 30);
homeText.setText(read());
JScrollPane homeScroll = new JScrollPane(homeText);
welc = new JLabel("Welcome To The Trust Wizard");
home = new JPanel();
mobile = new JButton("Mobile Wizard");
browser = new JButton("Browser Wizard");
home.add(welc);
home.add(homeScroll);
home.add(mobile);
home.add(browser);
ImageIcon img = new ImageIcon("hand.jpg");
setIconImage(img.getImage());
mobile.addActionListener(this);
browser.addActionListener(this);
getContentPane().add(home);
home.repaint();
setSize(450, 530);
setVisible(true);
}
public static void main(String args[])
{
SplashScreen test = new SplashScreen();
}
}
Don't write your own method to load data into a JTextArea.
//homeText.setText(read());
Instead, just use the read() method provided by the JTextArea API:
FileReader reader = new FileReader( your file name here );
BufferedReader br = new BufferedReader(reader);
homeText.read( br, null );
br.close();
Instead of appending just text, try appending text + "\n"
public String read() {
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String text = null;
while((text = reader.readLine()) != null) {
builder.append(text + "\n");
}
} catch(IOException jim) {
jim.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return builder.toString();
}
Also added a finally block to close the BufferedReader (and with it the rest of the stream)
homeText.setLineWrap(true); should do the trick for you.
Put that line right after the where you create the homeText variable and then your text will wrap to the size of your JTextArea.
Also put a StringBuilder in your while loop instead of using String concatenation which has a lot of overhead.
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.