new Scanner(new URL("SOME_URL.txt").openStream(), "UTF-8").useDelimiter("\\A").next();
Using this ^ I get the data from a .txt-File which I save in a String.
For my progress bar, I wondered if it would be possible for jobs like that (or in general for methods etc.) to count (or sth. like that) the time it needed to be finished. So that I can show in real time process time in my bar.
Is this somehow possible?
EDIT:
package app.gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.net.URL;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.io.IOUtils;
public class Updater {
private JFrame frame;
private static String rawG;
private static String versI;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
rawG = new Scanner(new URL("SOME_URL.txt").openStream(), "UTF-8").useDelimiter("\\A").next();
versI = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("version.txt"));
} catch (Exception e) {
System.out.println("error class Updater try/catch raw github");
}
if (Integer.parseInt(rawG.split("\\.")[0]) < Integer.parseInt(versI.split("\\.")[0])) {
System.out.println("Version check failure, update needed");
try {
Updater window = new Updater();
window.frame.setVisible(true);
} catch (Exception e) {
System.out.println("error class Updater try/catch initialize frame");
}
} else {
System.out.println("Version check correct, no update needed");
}
}
});
}
public Updater() {
initialize();
}
private void initialize() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.SOUTH);
panel.setLayout(new BorderLayout(0, 0));
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
panel.add(progressBar, BorderLayout.NORTH);
}
}
Is it possible? Yes. Is it possible when using Scanner.next() to read the contents of the URL? No.
You will need to read the bytes yourself, and count them:
URL url = new URL("SOME_URL.txt");
URLConnection conn = url.openConnection();
ByteBuffer buffer = ByteBuffer.allocate(conn.getContentLength());
EventQueue.invokeLater(() -> progressBar.setMaximum(buffer.limit()));
EventQueue.invokeLater(() -> progressBar.setValue(0));
try (ReadableByteChannel channel = Channels.newChannel(conn.getInputStream())) {
while (channel.read(buffer) >= 0) {
EventQueue.invokeLater(() -> progressBar.setValue(buffer.position()));
}
}
buffer.flip();
String rawG = StandardCharsets.UTF_8.decode(buffer).toString();
Related
Take this code:
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
JProgressBar jpb = new JProgressBar();
frame.add(jpb);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jpb.setMaximum(1000);
for(int i = 0; i < 1000; i++) {
System.out.println("Processing " + i);
jpb.setValue(i);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
and run it. You'll notice the JProgressBar graphic only updates every 5%.
Is this changeable? Can it update with more precise changes like every 1%?
(note: the default UIManager is more precise. Remove the WindowsLookAndFeel code to see).
You're at risk of blocking the Event Dispatching Thread (Thread.sleep) or you are violating the single thread rules of Swing by updating the UI outside of the Event Dispatching Thread
Take a look at Concurrency in Swing for more details
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JProgressBar pb = new JProgressBar();
pb.setStringPainted(true);
SwingWorker worker = new SwingWorker() {
#Override
protected Object doInBackground() throws Exception {
for (int index = 0; index < 1000; index++) {
int progress = Math.round((index / 1000f) * 100f);
setProgress(progress);
Thread.sleep(50);
}
return null;
}
};
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
SwingWorker worker = (SwingWorker) evt.getSource();
if ("progress".equals(evt.getPropertyName())) {
pb.setValue(worker.getProgress());
}
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(pb);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
worker.execute();
}
});
}
}
Updated
So, after digging about the WindowProgressBarUI, it would seem that, that's the way it's designed to work...that is, it paints in chunks/blocks.
You can use setStringPainted as I did in the example, which uses a different painting branch, but this might not suit your requirements
You can have a read through JProgressBar: low values will not be displayed for more details, but essentially, this is how the UI delegate is designed, so as to meet the requirements of the OS look and feel requirements
I would like to add a few lines to JTextPane, such as Joseph Red, Clarita Red, Bob Red, then later I would like to update both the name and color of a particular line, such as, I would like to change Joseph Red to Rudo Blue, or Bob Red to Molly Blue. Is there a way to do so? I wanted to record each line whenever adding a line to JTextPane and reference that particular line to update later on, but could not think of a way.
String color = "Red";
JTextPane textPanel = new JTextPane();
public void addToTextPane(String name) throws BadLocationException //Add each line to JTextPane
{
document = (StyledDocument) textPanel.getDocument();
document.insertString(document.getLength(), name + "" + color, null);
document.insertString(document.getLength(), "\n", null);
}
I am attempting to do something like the following (Update name and color of that a particular line that's already in the JTextPane):
if(...){
status = "Blue";
try
{
addTextPane("Jospeh"); //If I do this, it would not update the already exiting line and
//simply just add a new line with the name 'Joseph' and color 'Blue'
}
catch (BadLocationException e)
{
e.printStackTrace();
}
}
A for-loop in combination with Document#getText, Document#remove Document#insertString should do the trick...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
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 JTextPane textPane;
private String fruit[] = {"Bananas", "Apples", "Oranges", "Kiwis"};
private int index;
public TestPane() {
StringBuilder text = new StringBuilder(64);
text.append("Bananas in pajamas are coming down the stairs\n").
append("Bananas in pajamas are coming down in pairs\n").
append("Bananas in pajamas are chasing teddy bears\n").
append("Cause on tuesdays they try to catch their man-o-wears");
textPane = new JTextPane();
textPane.setText(text.toString());
setLayout(new BorderLayout());
add(new JScrollPane(textPane));
JButton btn = new JButton("Update");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
index++;
String find = fruit[(index - 1) % fruit.length];
String replace = fruit[index % fruit.length];
System.out.println("Find: " + find);
System.out.println("Replace: " + replace);
Document doc = textPane.getDocument();
try {
for (int pos = 0; pos < doc.getLength() - find.length(); pos++) {
String text = doc.getText(pos, find.length());
if (find.equals(text)) {
doc.remove(pos, find.length());
doc.insertString(pos, replace, null);
}
}
} catch (BadLocationException exp) {
exp.printStackTrace();
}
}
});
add(btn, BorderLayout.SOUTH);
}
}
}
The following code opens a JInternalFrame when a button is clicked. But I want this window to be opened once, so if the user clicks that button again it will not open another frame instead it would bring to the front the window whether it is iconified, behind another window, etc. I have tried a couple of ways mainly using a counter, but the problems is once the frame is closed it doesn't open it again either. Is there another easy way to do this, cause I am not able to make it work properly. Thanks in advance.
Below is the code I am working on:
public class About implements ActionListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
int count =0;
MyInternalFrame frame;
public About(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
System.out.println(count);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
count += 1;
if(count == 1){
frame = new MyInternalFrame("SAD Imaging");
count +=1;
try {
in = new BufferedReader(new FileReader("SADInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Tarea = new JTextArea();
//System.out.println(file);
Tarea.setText(file);
Font f = new Font("TimesNewRoman", Font.ROMAN_BASELINE, 16);
Tarea.setFont(f);
Tarea.setBackground(Color.white);
Tarea.setAlignmentX(SwingConstants.CENTER);
Tarea.setEditable(false);
JPanel panel = new JPanel();
panel.add(Tarea);
panel.setBackground(Color.white);
//scroll = new JScrollPane(Tarea);
scroll = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.add(scroll);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
else if(count > 1){
try {
//frame.setIcon(true);
frame.setMaximum(true);
frame.toFront();
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Basically, you just need to check to see if the frame is null or not. If it is, you create an instance, if it's not, you bring it to the front, for example
#Override
public void actionPerformed(ActionEvent arg0) {
if (frame == null || (frame.getParent() == null && !frame.isIconifiable())) {
// Your exitsing code
} else {
frame.setIcon(false);
frame.setSelected(true);
frame.moveToFront();
}
You can also use an InteralFrameListener to the frame so you can detect when the frame is closed, so you null the internal reference, for example...
frame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
frame = null;
}
});
Updated with runnable example
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.beans.PropertyVetoException;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestInternalFrame {
public static void main(String[] args) {
new TestInternalFrame();
}
private JInternalFrame imageFrame;
private JDesktopPane desktop;
public TestInternalFrame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JMenu fileMenu = new JMenu("File");
JMenuItem newMenu = fileMenu.add("Show...");
newMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (imageFrame == null || imageFrame.isClosed()) {
imageFrame = new JInternalFrame("Image");
imageFrame.setIconifiable(true);
imageFrame.setMaximizable(true);
imageFrame.setClosable(true);
imageFrame.setResizable(true);
JLabel label = new JLabel(new ImageIcon("..."));
imageFrame.add(label);
imageFrame.pack();
desktop.add(imageFrame);
imageFrame.setLocation(0, 0);
imageFrame.setVisible(true);
}
try {
imageFrame.setIcon(false);
imageFrame.setSelected(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
imageFrame.moveToFront();
}
});
desktop = new JDesktopPane();
JMenuBar mb = new JMenuBar();
mb.add(fileMenu);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(mb);
frame.add(desktop);
frame.setSize(1200, 900);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I have read this article on the EDT (Event Dispatch Thread) javaworld.com which shows how to correctly setup a Swing GUI on the EDT and put long running tasks which modify the GUI inside Runnables.
It all makes sense however the example program (I pasted below) where the only modification I made is a Thread.sleep(6000) to simulate a long lag makes the interface irresponsive for some seconds.
Am I missing something?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ViewPage
{
public static void main(String[] args)
{
Runnable r;
r = new Runnable()
{
#Override
public void run()
{
final JFrame frame = new JFrame("View Page");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(new JLabel("Enter URL"));
final JTextField txtURL = new JTextField(40);
panel.add(txtURL);
frame.getContentPane().add(panel, BorderLayout.NORTH);
final JTextArea txtHTML = new JTextArea(10, 40);
frame.getContentPane().add(new JScrollPane(txtHTML),
BorderLayout.CENTER);
ActionListener al;
al = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
txtURL.setEnabled(false);
Runnable worker = new Runnable()
{
public void run()
{
InputStream is = null;
try
{
URL url = new URL(txtURL.getText());
is = url.openStream();
final StringBuilder sb;
sb = new StringBuilder();
int b;
while ((b = is.read()) != -1)
{
sb.append((char) b);
}
Runnable r = new Runnable()
{
public void run()
{
try
{
Thread.sleep(6000);
}
catch (InterruptedException ex)
{
Logger.getLogger(ViewPage.class.getName()).log(Level.SEVERE, null, ex);
}
txtHTML.setText(sb.toString());
txtURL.setEnabled(true);
}
};
try
{
EventQueue.invokeAndWait(r);
}
catch (InterruptedException ie)
{
}
catch (InvocationTargetException ite)
{
}
}
catch (final IOException ioe)
{
Runnable r = new Runnable()
{
public void run()
{
txtHTML.setText(ioe.getMessage());
txtURL.setEnabled(true);
}
};
try
{
EventQueue.invokeAndWait(r);
}
catch (InterruptedException ie)
{
}
catch (InvocationTargetException ite)
{
}
}
finally
{
Runnable r = new Runnable()
{
public void run()
{
txtHTML.setCaretPosition(0);
txtURL.setEnabled(true);
}
};
try
{
EventQueue.invokeAndWait(r);
}
catch (InterruptedException ie)
{
}
catch (InvocationTargetException ite)
{
}
if (is != null)
{
try
{
is.close();
}
catch (IOException ioe)
{
}
}
}
}
};
new Thread(worker).start();
}
};
txtURL.addActionListener(al);
frame.pack();
frame.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
Am I missing something?
Yes.
Runnable is just an interface not another thread.
Here with this line you are wrapping the call to execute later in the Event Dispatch Thread.
EventQueue.invokeLater(r); // you can use SwingUtilities.invokeLater(r) too
Then you call
Thread.sleep(6000);
This is executed in EDT and make irresponsive the gui until finish.
For long task you should use another threads or SwingWorker and for short task with some repetitions SwingTimer.
Read about Concurrency in Swing
I am trying to get this SwingWorker to function correctly. However,the variables that need to be accessed seem to be not global. What do I do? I tried adding static but it creates more errors and complications later about accessing static from non static. The variables that are not working in the SwingWorker are the LOCAL_FILE and URL_LOCATION variables.
package professorphysinstall;
//Imports
import com.sun.jmx.snmp.tasks.Task;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import javax.tools.FileObject;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
public class ProfessorPhysInstall {
/**
* #param args the command line arguments
*/
static class Global {
public String location;
}
public static void main(String[] args) {
// TODO code application logic here
//Variables
final JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
final JPanel cards = new JPanel(new CardLayout());
final CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(TextPaneScreen1);
JTextArea TextAreaScreen1 = new JTextArea();
JScrollPane sbrText = new JScrollPane(TextAreaScreen1);
TextAreaScreen1.setRows(15);
TextAreaScreen1.setColumns(40);
TextAreaScreen1.setEditable(false);
TextAreaScreen1.setText("stuff");
TextAreaScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextAreaScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(sbrText);
final JCheckBox Acceptance = new JCheckBox();
Acceptance.setText("I Accept The EULA Agreenment.");
screen1.add(Acceptance);
final JButton NextScreen1 = new JButton();
NextScreen1.setText("Next");
NextScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.next(cards);
}
});
screen1.add(NextScreen1);
JButton CancelScreen1 = new JButton();
CancelScreen1.setText("Cancel");
CancelScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen1.add(CancelScreen1);
cards.add(screen1);
//Screen2
final JPanel screen2 = new JPanel();
JPanel screen3 = new JPanel();
JTextPane TextPaneScreen2 = new JTextPane();
TextPaneScreen2.setEditable(false);
TextPaneScreen2.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher. Professor Phys will be installed there.");
TextPaneScreen2.setSize(358, 48);
TextPaneScreen2.setLocation(0, 0);
TextPaneScreen2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen2.setMargin(new Insets(4,4,4,4));
screen2.add(TextPaneScreen2);
JLabel screen2instructions = new JLabel();
screen2instructions.setText("Launcher Location: ");
screen2.add(screen2instructions);
final JTextField folderlocation = new JTextField(25);
screen2.add(folderlocation);
final JButton Browse = new JButton();
final JLabel filelocation = new JLabel();
final JLabel filename = new JLabel();
Browse.setText("Browse");
Browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Create a file chooser
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(screen2);
folderlocation.setText(fc.getSelectedFile().getAbsolutePath());
filelocation.setText(fc.getCurrentDirectory().getAbsolutePath());
filename.setText(fc.getSelectedFile().getName());
}
});
screen2.add(filelocation);
screen2.add(filename);
screen3.add(filelocation);
filelocation.setVisible(false);
filename.setVisible(false);
screen2.add(Browse);
final JButton BackScreen2 = new JButton();
BackScreen2.setText("Back");
BackScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen2.add(BackScreen2);
final JButton NextScreen2 = new JButton();
NextScreen2.setText("Next");
NextScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Checking Code
String correctname = "Future_Retro_Gaming_Launcher.jar";
if (filename.getText().equals(correctname))
{
cl.next(cards);
}
else
{
JFrame popup = new JFrame();
popup.setBounds(0, 0, 380, 100);
Label error = new Label();
error.setText("Sorry you must select your Future_Retro_Gaming_Launcher.jar");
popup.add(error);
popup.show();
}
}
});
screen2.add(NextScreen2);
JButton CancelScreen2 = new JButton();
CancelScreen2.setText("Cancel");
CancelScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen2.add(CancelScreen2);
cards.add(screen2);
//Screen3
JTextPane TextPaneScreen3 = new JTextPane();
TextPaneScreen3.setEditable(false);
TextPaneScreen3.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen3.setText("Professor Phys will be instaleld in the directory you have chosen. Please make sure\nyour launcher is in that folder or the game will not work.\nClick next to begin the install process.");
TextPaneScreen3.setSize(358, 48);
TextPaneScreen3.setLocation(0, 0);
TextPaneScreen3.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen3.setMargin(new Insets(4,4,4,4));
screen3.add(TextPaneScreen3);
final JButton BackScreen3 = new JButton();
BackScreen3.setText("Back");
BackScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen3.add(BackScreen2);
final JButton NextScreen3 = new JButton();
NextScreen3.setText("Next");
NextScreen3.addActionListener(new ActionListener() {
#Override
#SuppressWarnings({"null", "ConstantConditions"})
public void actionPerformed(ActionEvent ae) {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(filelocation.getText());
String URL_LOCATION = "https://dl.dropboxusercontent.com/u/10429987/Future%20Retro%20Gaming/ProfessorPhys.iso";
String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(LOCAL_FILE+"professorphys.iso", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
});
screen3.add(NextScreen3);
JButton CancelScreen3 = new JButton();
CancelScreen3.setText("Cancel");
CancelScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen3.add(CancelScreen3);
System.out.println("Done");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
screen3.add(progress);
cards.add(screen3);
mainframe.add(cards);
mainframe.setVisible(true);
}
}
class DownloadWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Your program is mostly a huge static main method. You're kind of getting the cart in front of the horse trying to do advanced programming such as with SwingWorker before first creating clean OOP code. In other words -- start over and do it right. Then the connections between classes will be much more natural and it will be much easier to get things to work right. The main method should only concern itself with starting the Swing event thread, creating a GUI object in that thread, and displaying it. Everything else should be in classes that create objects.
Also, on a more practical level, you have yet to tell us what variables are causing you trouble or what errors you might be seeing. Also, where are you trying to create and execute the SwingWorker?
Edit
One tip that will likely help: Give your SwingWorker class a constructor, and pass important parameters into your SwingWorker object via constructor parameters. Then use those parameters to initialize class fields that will be used in the SwingWorker's doInBackground method.
e.g.,
class DownloadWorker extends SwingWorker<Integer, Integer>
{
private String urlLocation;
private String localFile;
public DownLoadWorker(String urlLocation, String localFile) {
this.urlLocation = urlLocation;
this.localFile = localFile;
}
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(urlLocation);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(localFile +"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}