How to change JFrame icon [duplicate] - java

This question already has answers here:
How to set Icon to JFrame
(12 answers)
Closed 6 years ago.
I have a JFrame that displays a Java icon on the title bar (left corner).
I want to change that icon to my custom icon. How should I do it?

Create a new ImageIcon object like this:
ImageIcon img = new ImageIcon(pathToFileOnDisk);
Then set it to your JFrame with setIconImage():
myFrame.setIconImage(img.getImage());
Also checkout setIconImages() which takes a List instead.

Here is an Alternative that worked for me:
yourFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath)));
It's very similar to the accepted Answer.

JFrame.setIconImage(Image image) pretty standard.

Here is how I do it:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.io.File;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class MainFrame implements ActionListener{
/**
*
*/
/**
* #param args
*/
public static void main(String[] args) {
String appdata = System.getenv("APPDATA");
String iconPath = appdata + "\\JAPP_icon.png";
File icon = new File(iconPath);
if(!icon.exists()){
FileDownloaderNEW fd = new FileDownloaderNEW();
fd.download("http://icons.iconarchive.com/icons/artua/mac/512/Setting-icon.png", iconPath, false, false);
}
JFrame frm = new JFrame("Test");
ImageIcon imgicon = new ImageIcon(iconPath);
JButton bttn = new JButton("Kill");
MainFrame frame = new MainFrame();
bttn.addActionListener(frame);
frm.add(bttn);
frm.setIconImage(imgicon.getImage());
frm.setSize(100, 100);
frm.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
and here is the downloader:
import java.awt.GridLayout;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
public class FileDownloaderNEW extends JFrame {
private static final long serialVersionUID = 1L;
public static void download(String a1, String a2, boolean showUI, boolean exit)
throws Exception
{
String site = a1;
String filename = a2;
JFrame frm = new JFrame("Download Progress");
JProgressBar current = new JProgressBar(0, 100);
JProgressBar DownloadProg = new JProgressBar(0, 100);
JLabel downloadSize = new JLabel();
current.setSize(50, 50);
current.setValue(43);
current.setStringPainted(true);
frm.add(downloadSize);
frm.add(current);
frm.add(DownloadProg);
frm.setVisible(showUI);
frm.setLayout(new GridLayout(1, 3, 5, 5));
frm.pack();
frm.setDefaultCloseOperation(3);
try
{
URL url = new URL(site);
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
int filesize = connection.getContentLength();
float totalDataRead = 0.0F;
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int i = 0;
while ((i = in.read(data, 0, 1024)) >= 0)
{
totalDataRead += i;
float prog = 100.0F - totalDataRead * 100.0F / filesize;
DownloadProg.setValue((int)prog);
bout.write(data, 0, i);
float Percent = totalDataRead * 100.0F / filesize;
current.setValue((int)Percent);
double kbSize = filesize / 1000;
String unit = "kb";
double Size;
if (kbSize > 999.0D) {
Size = kbSize / 1000.0D;
unit = "mb";
} else {
Size = kbSize;
}
downloadSize.setText("Filesize: " + Double.toString(Size) + unit);
}
bout.close();
in.close();
System.out.println("Took " + System.nanoTime() / 1000000000L / 10000L + " seconds");
}
catch (Exception e)
{
JOptionPane.showConfirmDialog(
null, e.getMessage(), "Error",
-1);
} finally {
if(exit = true){
System.exit(128);
}
}
}
}

Just add the following code:
setIconImage(new ImageIcon(PathOfFile).getImage());

Unfortunately, the above solution did not work for Jython Fiji plugin. I had to use getProperty to construct the relative path dynamically.
Here's what worked for me:
import java.lang.System.getProperty;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
frame = JFrame("Test")
icon = ImageIcon(getProperty('fiji.dir') + '/path/relative2Fiji/icon.png')
frame.setIconImage(icon.getImage());
frame.setVisible(True)

This did the trick in my case super or this referes to JFrame in my class
URL url = getClass().getResource("gfx/hi_20px.png");
ImageIcon imgicon = new ImageIcon(url);
super.setIconImage(imgicon.getImage());

Add the following code within the constructor like so:
public Calculator() {
initComponents();
//the code to be added this.setIconImage(newImageIcon(getClass().getResource("color.png")).getImage()); }
Change "color.png" to the file name of the picture you want to insert.
Drag and drop this picture onto the package (under Source Packages) of your project.
Run your project.

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.

Using swing GUI to make a progress bar show up while downloading a file [duplicate]

This question already has answers here:
JProgressBar wont update
(3 answers)
Closed 9 years ago.
I currently have a class that should show me a simple form while downloading a file. It is working, but the progress bar is not updating, and I can only see it once the download is finished. Can someone help me?
import java.awt.FlowLayout;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JProgressBar;
public class Downloader {
public Downloader(String site, File file) {
JFrame frm = new JFrame();
JProgressBar current = new JProgressBar(0, 100);
current.setSize(50, 100);
current.setValue(0);
current.setStringPainted(true);
frm.add(current);
frm.setVisible(true);
frm.setLayout(new FlowLayout());
frm.setSize(50, 100);
frm.setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
URL url = new URL(site);
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
int filesize = connection.getContentLength();
float totalDataRead = 0;
try (java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream())) {
java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
try (java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024)) {
byte[] data = new byte[1024];
int i;
while ((i = in.read(data, 0, 1024)) >= 0) {
totalDataRead = totalDataRead + i;
bout.write(data, 0, i);
float Percent = (totalDataRead * 100) / filesize;
current.setValue((int) Percent);
}
}
}
} catch (IOException e) {
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, e.getMessage(), "Error",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
}
Yours is a classic Swing concurrency issue. The solution is as always -- do the long running code in a background thread such as can be found with a SwingWorker.
e.g.,
import java.awt.FlowLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JProgressBar;
public class Downloader {
public Downloader(String site, File file) {
JFrame frm = new JFrame();
final JProgressBar current = new JProgressBar(0, 100);
current.setSize(50, 100);
current.setValue(0);
current.setStringPainted(true);
frm.add(current);
frm.setVisible(true);
frm.setLayout(new FlowLayout());
frm.setSize(50, 100);
frm.setDefaultCloseOperation(EXIT_ON_CLOSE);
final Worker worker = new Worker(site, file);
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if ("progress".equals(pcEvt.getPropertyName())) {
current.setValue((Integer) pcEvt.getNewValue());
} else if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
try {
worker.get();
} catch (InterruptedException | ExecutionException e) {
// handle any errors here
e.printStackTrace();
}
}
}
});
worker.execute();
}
}
class Worker extends SwingWorker<Void, Void> {
private String site;
private File file;
public Worker(String site, File file) {
this.site = site;
this.file = file;
}
#Override
protected Void doInBackground() throws Exception {
URL url = new URL(site);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
int filesize = connection.getContentLength();
int totalDataRead = 0;
try (java.io.BufferedInputStream in = new java.io.BufferedInputStream(
connection.getInputStream())) {
java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
try (java.io.BufferedOutputStream bout = new BufferedOutputStream(
fos, 1024)) {
byte[] data = new byte[1024];
int i;
while ((i = in.read(data, 0, 1024)) >= 0) {
totalDataRead = totalDataRead + i;
bout.write(data, 0, i);
int percent = (totalDataRead * 100) / filesize;
setProgress(percent);
}
}
}
return null;
}
}

Changing an Icon in a JLabel dynamically

I am having a bit of problem with changing and Icon in a JLabel dynamically. First of all, what i am trying to do is basically simulating a screen sharing operation. On the client side, I am taking screenshots every second, sending them to the server. On the server side, I am trying to open these pictures in a simple GUI.
I am able to send the pictures without problem and I am also able to get them without problem as well. However, the GUI code I have written cannot open the pictures. More specifically, If there is a picture, it is able to open it, but it does not open another picture that has come.
What I am doing in the server side is, as soon as a picture gets to the server, I am saving it with a predetermined name. And then I am able to open the picture with Windows' own picture photo viewer. In fact, as soon as a new picture comes, photo viewer updates itself and shows the new screenshot.
However, I am having trouble opening the screenshots in a JFrame. I have written a program to take the screenshots in jpg format, send them to the server and then open them in a GUI. however i am having problems with the opening in the GUI part. From what I have understood, it does not open the files that are coming by from the client.
Below are my codes, any help will be much appreciated.
Server side,
package ScreenCap;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import FileServer.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import test.TsgIcons;
/**
*
* #author busra
*/
public class ScreenCapServer extends Thread{
String filePath;
int portNumber;
FileServer screenCapServer;
ServerSocket getFileServer;
Socket getFile;
InputStream in;
FileOutputStream fileOutputStream;
TsgIcons screenShotIcons;
public ScreenCapServer(String path, int port) {
this.filePath = path;
this.portNumber = port;
this.screenShotIcons = new TsgIcons();
}
public static void waitTime(long millisecond){
long max = millisecond;
for(long i = 0; i < max; i++){
for(long j = 0; j < max; j++){
}
}
}
public void run() {
while(true) {
try {
for(int i = 0; i < 10; i++) {
getFileServer = new ServerSocket(portNumber);
getFile = getFileServer.accept();
in = getFile.getInputStream();
fileOutputStream = new FileOutputStream(filePath + "\\" + i + ".jpg");
byte [] buffer = new byte[64*1024];
int bytesRead = 0;
while ( (bytesRead = in.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
in.close();
fileOutputStream.close();
getFileServer.close();
screenShotIcons.update();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
GUI,
package test;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class TsgIcons extends JFrame implements ActionListener {
protected Timer timer;
protected JLabel viewIcon;
private String[] SMILEY = {"orig_screen"};
private String BUTTON = "Button";
private int timeCount;
private int iconNumber;
private String image;
public TsgIcons() {
this(1, 100);
}
public TsgIcons(int initialTime, int delay) {
super("TSG Smileys");
this.timeCount = initialTime;
this.iconNumber = this.timeCount % this.SMILEY.length;
this.image = "TransferredScreenShots\\" + this.SMILEY[this.iconNumber] + ".jpg";
this.viewIcon = new JLabel();
this.viewIcon.setIcon(new javax.swing.ImageIcon(this.image));
this.timer = new Timer(delay, this);
this.init();
}
protected void init() {
JButton button = new JButton("Start / Stop");
button.setActionCommand(BUTTON);
button.addActionListener(this);
this.viewIcon.setHorizontalAlignment(JLabel.CENTER);
this.getContentPane().add(button, BorderLayout.SOUTH);
this.getContentPane().add(this.viewIcon, BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(250, 250);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if ( BUTTON.equals(e.getActionCommand()) ) { // test if the button clicked
if ( this.timer.isRunning() ) {
this.timer.stop();
} else {
this.timer.start();
}
} else
{ this.timeCount++;
this.iconNumber = this.timeCount % this.SMILEY.length;
this.image = "TransferredScreenShots\\" + this.SMILEY[this.iconNumber] + ".jpg";
this.viewIcon.setIcon(new javax.swing.ImageIcon(this.image));
}
}
public void update() {
this.timeCount++;
this.iconNumber = this.timeCount % this.SMILEY.length;
this.image = "TransferredScreenShots\\" + this.SMILEY[this.iconNumber] + ".jpg";
this.viewIcon.setIcon(new javax.swing.ImageIcon(this.image));
}
public static void main(String argv []) {
new TsgIcons();
}
}

Need to have JProgress bar to measure progress when copying directories and files

I have the below code to copy directories and files but not sure where to measure the progress. Can someone help
as to where can I measure how much has been copied and show it in the JProgress bar
public static void copy(File src, File dest)
throws IOException{
if(src.isDirectory()){
if(!dest.exists()){ //checking whether destination directory exisits
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
String files[] = src.list();
for (String file : files) {
File srcFile = new File(src, file);
File destFile = new File(dest, file);
copyFolder(srcFile,destFile);
}
}else{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
I have just written this utility for you :) (It takes me about 3 hours):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.DefaultCaret;
public class FileCopierUtility extends JFrame implements ActionListener, PropertyChangeListener
{
private static final long serialVersionUID = 1L;
private JTextField txtSource;
private JTextField txtTarget;
private JProgressBar progressAll;
private JProgressBar progressCurrent;
private JTextArea txtDetails;
private JButton btnCopy;
private CopyTask task;
public FileCopierUtility()
{
buildGUI();
}
private void buildGUI()
{
setTitle("File Copier Utility");
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
if(task != null) task.cancel(true);
dispose();
System.exit(0);
}
});
JLabel lblSource = new JLabel("Source Path: ");
JLabel lblTarget = new JLabel("Target Path: ");
txtSource = new JTextField(50);
txtTarget = new JTextField(50);
JLabel lblProgressAll = new JLabel("Overall: ");
JLabel lblProgressCurrent = new JLabel("Current File: ");
progressAll = new JProgressBar(0, 100);
progressAll.setStringPainted(true);
progressCurrent = new JProgressBar(0, 100);
progressCurrent.setStringPainted(true);
txtDetails = new JTextArea(5, 50);
txtDetails.setEditable(false);
DefaultCaret caret = (DefaultCaret) txtDetails.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane scrollPane = new JScrollPane(txtDetails, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
btnCopy = new JButton("Copy");
btnCopy.setFocusPainted(false);
btnCopy.setEnabled(false);
btnCopy.addActionListener(this);
DocumentListener listener = new DocumentListener()
{
#Override
public void removeUpdate(DocumentEvent e)
{
boolean bEnabled = txtSource.getText().length() > 0 && txtTarget.getText().length() > 0;
btnCopy.setEnabled(bEnabled);
}
#Override
public void insertUpdate(DocumentEvent e)
{
boolean bEnabled = txtSource.getText().length() > 0 && txtTarget.getText().length() > 0;
btnCopy.setEnabled(bEnabled);
}
#Override
public void changedUpdate(DocumentEvent e){}
};
txtSource.getDocument().addDocumentListener(listener);
txtTarget.getDocument().addDocumentListener(listener);
JPanel contentPane = (JPanel) getContentPane();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JPanel panInputLabels = new JPanel(new BorderLayout(0, 5));
JPanel panInputFields = new JPanel(new BorderLayout(0, 5));
JPanel panProgressLabels = new JPanel(new BorderLayout(0, 5));
JPanel panProgressBars = new JPanel(new BorderLayout(0, 5));
panInputLabels.add(lblSource, BorderLayout.NORTH);
panInputLabels.add(lblTarget, BorderLayout.CENTER);
panInputFields.add(txtSource, BorderLayout.NORTH);
panInputFields.add(txtTarget, BorderLayout.CENTER);
panProgressLabels.add(lblProgressAll, BorderLayout.NORTH);
panProgressLabels.add(lblProgressCurrent, BorderLayout.CENTER);
panProgressBars.add(progressAll, BorderLayout.NORTH);
panProgressBars.add(progressCurrent, BorderLayout.CENTER);
JPanel panInput = new JPanel(new BorderLayout(0, 5));
panInput.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Input"), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
JPanel panProgress = new JPanel(new BorderLayout(0, 5));
panProgress.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Progress"), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
JPanel panDetails = new JPanel(new BorderLayout());
panDetails.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Details"), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
JPanel panControls = new JPanel(new BorderLayout());
panControls.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
panInput.add(panInputLabels, BorderLayout.LINE_START);
panInput.add(panInputFields, BorderLayout.CENTER);
panProgress.add(panProgressLabels, BorderLayout.LINE_START);
panProgress.add(panProgressBars, BorderLayout.CENTER);
panDetails.add(scrollPane, BorderLayout.CENTER);
panControls.add(btnCopy, BorderLayout.CENTER);
JPanel panUpper = new JPanel(new BorderLayout());
panUpper.add(panInput, BorderLayout.NORTH);
panUpper.add(panProgress, BorderLayout.SOUTH);
contentPane.add(panUpper, BorderLayout.NORTH);
contentPane.add(panDetails, BorderLayout.CENTER);
contentPane.add(panControls, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e)
{
if("Copy".equals(btnCopy.getText()))
{
File source = new File(txtSource.getText());
File target = new File(txtTarget.getText());
if(!source.exists())
{
JOptionPane.showMessageDialog(this, "The source file/directory does not exist!", "ERROR", JOptionPane.ERROR_MESSAGE);
return;
}
if(!target.exists() && source.isDirectory()) target.mkdirs();
else
{
int option = JOptionPane.showConfirmDialog(this, "The target file/directory already exists, do you want to overwrite it?", "Overwrite the target", JOptionPane.YES_NO_OPTION);
if(option != JOptionPane.YES_OPTION) return;
}
task = this.new CopyTask(source, target);
task.addPropertyChangeListener(this);
task.execute();
btnCopy.setText("Cancel");
}
else if("Cancel".equals(btnCopy.getText()))
{
task.cancel(true);
btnCopy.setText("Copy");
}
}
#Override
public void propertyChange(PropertyChangeEvent evt)
{
if("progress".equals(evt.getPropertyName()))
{
int progress = (Integer) evt.getNewValue();
progressAll.setValue(progress);
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new FileCopierUtility().setVisible(true);
}
});
}
class CopyTask extends SwingWorker<Void, Integer>
{
private File source;
private File target;
private long totalBytes = 0L;
private long copiedBytes = 0L;
public CopyTask(File source, File target)
{
this.source = source;
this.target = target;
progressAll.setValue(0);
progressCurrent.setValue(0);
}
#Override
public Void doInBackground() throws Exception
{
txtDetails.append("Retrieving some info ... ");
retrieveTotalBytes(source);
txtDetails.append("Done!\n");
copyFiles(source, target);
return null;
}
#Override
public void process(List<Integer> chunks)
{
for(int i : chunks)
{
progressCurrent.setValue(i);
}
}
#Override
public void done()
{
setProgress(100);
btnCopy.setText("Copy");
}
private void retrieveTotalBytes(File sourceFile)
{
File[] files = sourceFile.listFiles();
for(File file : files)
{
if(file.isDirectory()) retrieveTotalBytes(file);
else totalBytes += file.length();
}
}
private void copyFiles(File sourceFile, File targetFile) throws IOException
{
if(sourceFile.isDirectory())
{
if(!targetFile.exists()) targetFile.mkdirs();
String[] filePaths = sourceFile.list();
for(String filePath : filePaths)
{
File srcFile = new File(sourceFile, filePath);
File destFile = new File(targetFile, filePath);
copyFiles(srcFile, destFile);
}
}
else
{
txtDetails.append("Copying " + sourceFile.getAbsolutePath() + " ... ");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));
long fileBytes = sourceFile.length();
long soFar = 0L;
int theByte;
while((theByte = bis.read()) != -1)
{
bos.write(theByte);
setProgress((int) (copiedBytes++ * 100 / totalBytes));
publish((int) (soFar++ * 100 / fileBytes));
}
bis.close();
bos.close();
publish(100);
txtDetails.append("Done!\n");
}
}
}
}
To accomplish this, you have to figure out the number of copy operations in advance. You did not include your copyFolder method, but I assume that you would like to perform a recursive copy.
If so, you have to traverse the whole directory tree to figure out how many files you are going to copy. This can get nasty for the user when dealing with large directory structures. (This is why modern operation systems often display an annoying "preparing to copy..." - message before the operation starts and progress is displayed)
Showing the progress for a file is rather simple...
long expectedBytes = src.length(); // This is the number of bytes we expected to copy..
byte[] buffer = new byte[1024];
int length;
long totalBytesCopied = 0; // This will track the total number of bytes we've copied
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
totalBytesCopied += length;
int progress = (int)Math.round(((double)totalBytesCopied / (double)expectedBytes) * 100);
setProgress(progress); // From SwingWorker
}
If you want to provide information about the total number of bytes to be copied/has begin copied, it becomes a little more complicated.
You have choices here. You either pre-scan all the folders (I'd be placing the files into some kind of queue) and calculate the total bytes/number of files to be copied. Then start the actual copy process.
Updating the progress for this is as simple as the example before, except you'd be accumulating the total number of bytes you've copied over the whole process instead of a single file.
OR...
You could use a producer/consumer algorithm. The idea would be to start a thread/worker whose sole responsibility was to scan the folders for the files to be copied and place them into a central/shared queue (this is the producer).
You would have a second thread/worker that would pop the next item of this queue (blocking into a new file became available) and would actually copy the file.
The trick here is for the queue to maintain a counter to the total number of files and bytes that has passed through it, this will allow you to adjust the ongoing progress of total job...

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