I have this app that runs in eclipse's console and I want it to run in a jframe.
By that I mean that I want it to ask for name, a and b on the JFrame window and then write something on a file.
It works perfectly in the console but I don't know how to run it as a JFrame.
I want it to look something like this(Image made in photoshop):
http://i.imgur.com/rTWko1R.png
And then automaticaly close
Thanks in advance!
some imports...(trying to save space)
public class Test {
public static void main(String[] args) throws FileNotFoundException,IOException {
Scanner s = new Scanner(System.in);
String fileName = new SimpleDateFormat("dd-MM-yyyy_HH-mm'.txt'").format(new Date());
String obs;
String name;
String path = "some path";
int a = 0, b = 0, c = 0, d = 0;
System.out.println("input file name");
name = s.nextLine();
System.out.println("input a");
a = s.nextInt();
System.out.println("input b");
b = s.nextInt();
obs = s.nextLine();
if (a >= 100) {
d = a / 100;
c = a % 100;
b = c;
a = a + d;
}
File file;
if (StringUtils.isBlank(name)) {
file = new File(path + fileName);
} else {
file = new File(path + name + "#" + fileName);
}
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("something");
if (StringUtils.isBlank(obs)) {
writer.write("something");
} else {
writer.write(obs + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
What you'll need to do
separate out your core logic into a separate method that takes String name, int a, int b, ideally in a separate class - then you can reuse from your console version
Create a basic GUI in a frame with a button to kick off the process
listen to the button press and call core logic method
add validation of inputs if necessary
consider using JFileChooser to allow user to pick the file rather than having to type it in
Example
public class ConsoleInFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ConsoleInFrame().showGui();
}
});
}
public void showGui() {
JFrame frame = new JFrame();
JTextField file = new JTextField(20);
JTextField aText = new JTextField(4);
JTextField bText = new JTextField(4);
JButton go = new JButton("Go");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("File"));
panel.add(file);
panel.add(new JLabel("a"));
panel.add(aText);
panel.add(new JLabel("b"));
panel.add(bText);
frame.getContentPane().setLayout(
new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.getContentPane().add(panel);
frame.getContentPane().add(go);
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
process(file.getText(), Integer.parseInt(aText.getText()),
Integer.parseInt(bText.getText()));
}
});
frame.pack();
frame.setVisible(true);
}
public void process(String name, int a, int b) {
String fileName = new SimpleDateFormat("dd-MM-yyyy_HH-mm'.txt'")
.format(new Date());
String obs;
String path = "some path";
int c = 0, d = 0;
if (a >= 100) {
d = a / 100;
c = a % 100;
b = c;
a = a + d;
}
File file;
if (StringUtils.isBlank(name)) {
file = new File(path + fileName);
} else {
file = new File(path + name + "#" + fileName);
}
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("something");
if (StringUtils.isBlank(obs)) {
writer.write("something");
} else {
writer.write(obs + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException ignore) {
}
}
}
}
I think you could do something like this:
To do this you have to use JLabel to display text: https://docs.oracle.com/javase/tutorial/uiswing/components/label.html
Then to get the input use JTextField:
https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html
And if you want you can use a JButton after you write in the JTextField to save everything to the file:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JButton.html
http://www.javamex.com/tutorials/swing/jbutton.shtml
Related
I'm having a problem with my methods for a school assignment which are supposed to load and save String arrays to a file. It seems like it does not save or load properly. For example, I saved a string of "ok" in a file, let's call it x. Then I rerun the app and changed the path to a directory and it read the string "ok" from it even though it wasn't initially saved the directory and the directory shouldn't be allowed anyways. I really don't know how to solve it and I tried to manipulate the code but I do not know what causes it so it's hard to think of a solution.
Some details on my task:
have to use File Output/Input Stream and Object Output/Input Stream
question and answer strings have to be initialized to 0 size if the path is empty/is a dir/ file not found
take answer and question string from textfield, save it to a file and read the existing ones from the file
question and answer string arrays have to be in a separate class
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Arrays;
public class App2 extends JFrame implements ActionListener {
JPanel mpanel, qpanel, apanel, bpanel, upanel;
JTextField tf1, tf2, tf3;
JButton jb;
JLabel jl1, jl2, jl3;
String path;
public static void main(String[] args) {
App2 object = new App2();
System.out.println("app init/ array size:" + QAData.question.length);
}
App2() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(400, 200);
this.setTitle("App2");
mpanel = new JPanel();
this.add(mpanel);
mpanel.setLayout(new GridLayout(4, 1));
qpanel = new JPanel();
mpanel.add(qpanel);
apanel = new JPanel();
mpanel.add(apanel);
upanel = new JPanel();
mpanel.add(upanel);
bpanel = new JPanel();
mpanel.add(bpanel);
jl1 = new JLabel("Question: ");
qpanel.add(jl1);
tf1 = new JTextField(20);
tf1.setHorizontalAlignment(JTextField.LEFT);
qpanel.add(tf1);
tf1.addActionListener(this);
jl2 = new JLabel("Answer: ");
apanel.add(jl2);
tf2 = new JTextField(20);
tf2.setHorizontalAlignment(JTextField.LEFT);
apanel.add(tf2);
tf2.addActionListener(this);
jl3 = new JLabel("Path: ");
upanel.add(jl3);
tf3 = new JTextField(20);
tf3.setHorizontalAlignment(JTextField.LEFT);
upanel.add(tf3);
tf3.addActionListener(this);
jb = new JButton("Update");
jb.setHorizontalAlignment(JButton.CENTER);
bpanel.add(jb);
jb.addActionListener(this);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == tf3)
path = tf3.getText();
if (e.getSource() == jb) {
load();
save();
tf1.setText("");
tf2.setText("");
}
}
void load() {
try {
File file = new File("path");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (!fileIsOk) {
QAData.question = new String[0];
QAData.answer = new String[0];
System.out.println("size 0 applied");
} else {
QAData.question = (String[]) ois.readObject();
QAData.answer = (String[]) ois.readObject();
}
ois.close();
} catch (ClassNotFoundException e) {
System.out.println("No such class found");
e.printStackTrace();
} catch (IOException e) {
System.out.println("I/O exception during the load");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to read has the null value");
e.printStackTrace();
}
}
void save() {
try {
File file = new File("path");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
boolean fileIsOk = file.isFile() && !(tf3.getText().equals("")) && !(file.isDirectory());
if (fileIsOk) {
QAData.question = Arrays.copyOf(QAData.question, QAData.question.length + 1);
QAData.question[(QAData.question.length - 1)] = tf1.getText();
QAData.answer = Arrays.copyOf(QAData.answer, QAData.answer.length + 1);
QAData.answer[(QAData.answer.length - 1)] = tf2.getText();
oos.writeObject(QAData.question);
oos.writeObject(QAData.answer);
}
oos.close();
} catch (IOException e) {
System.out.println("I/O exception during the save");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("The object you are trying to save has the null value");
e.printStackTrace();
}
}
static class QAData implements Serializable {
static String[] question = new String[0];
static String[] answer = new String[0];
}
}
I am developing Swing Application . I create new Tab for new Log Process..Print all console statement inside it . when i place tab in tab component it get mismatched pro1 hold log2 pro2 hold log1 so i dig to much but not figure out code is follow.
ProjectExecute Event Which call to CreateNew TAb Method .
if (e.getSource() == btnExecute) {
createTab();
String s = new StringBuffer().append(ProjectOutPath).toString();
dirr = new File(s);
if (!dirr.exists()) {
}
final File tagFile = new File(dirr, projectName + ".log");
if (!tagFile.exists()) {
try {
tagFile.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
SwingWorker<Boolean, Integer> worker = new SwingWorker<Boolean, Integer>() {
#SuppressWarnings({ "unchecked", "null" })
#Override
protected Boolean doInBackground() throws Exception {
PrintStream printStream = new PrintStream(new CustomOutputStream(logTextArea, tempArea));
System.setOut(printStream);
System.setErr(printStream);
File outFile = new File(tagFile.getAbsolutePath());
FileOutputStream outFileStream = new FileOutputStream(outFile);
PrintWriter outStream = new PrintWriter(outFileStream);
try {
System.out.println("ChooserFile 1 :" + chooserFile1);
MainApp.runApp(chooserFile1);
chooserFile1 = new StringBuilder().append(chooserFile1).append("/raw_data").toString();
outStream.write(logTextArea.getText());
System.out.flush();
Runtime.getRuntime().exec("clear");
outStream.close();
printStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Thread.sleep(1000);
return true;
}
protected void done() {
try {
Component c[] = panel_tree.getComponents();
panel_tree.remove(c.length - 1);
panel_tree.add(ExomDataGUI.getTreeUpdate());
panel_tree.revalidate();
panel_tree.repaint();
scrollPane.getViewport().setView(ExomDataGUI.panel_tree);
} catch (Exception e) {
System.out.println("Exception Occured....!");
}
}
#Override
protected void process(List<Integer> chunks) {
int mostRecentValue = chunks.get(chunks.size() - 1);
countLabel.setText(Integer.toString(mostRecentValue));
}
};
worker.execute();
} else {
}
}
Create TAB method
private static JScrollPane createScroll() {
System.out.println("Creatre Scrollpane Method Called....");
JTextArea ja = new JTextArea();
String S = logTextArea.getText();
ja.setText(S);
JScrollPane JScrolling = new JScrollPane(ja);
logTextArea.setText(null);
return JScrolling;
}
public static void createTab() {
JLabel lblTitle;
if (flag == 1) {
//System.out.println("************Inside If Flag ***********");
tabbedPane1.add("", new JScrollPane(logTextArea));
Demo.add(tabbedPane1);
JTextArea JTA = new JTextArea();
String log = logTextArea.getText();
JTA.setText(log);
logTextArea.setText(null);
lblTitle= new JLabel(projectName);
flag = 0;
} else {
// System.out.println("+++++++++++++++++++Inside If Flag +++++++++++");
JScrollPane JSP = createScroll();
tabbedPane1.add("here", JSP);
lblTitle= new JLabel(projectName);
}
JPanel pnlTab = new JPanel();
pnlTab.setOpaque(false);
//JLabel lblTitle = new JLabel();
JButton btnClose = new JButton();
btnClose.setOpaque(false);
btnClose.setRolloverIcon(CLOSE_TAB_ICON);
btnClose.setRolloverEnabled(true);
btnClose.setIcon(CLOSE_TAB_ICON);
btnClose.setBorder(null);
btnClose.setFocusable(false);
pnlTab.setForeground(Color.white);
pnlTab.setBackground(Color.white);
pnlTab.add(lblTitle);
pnlTab.add(btnClose);
pnlTab.setForeground(Color.white);
tabbedPane1.setTabComponentAt(tabbedPane1.getTabCount() - 1, pnlTab);
Demo.add(tabbedPane1);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int response = JOptionPane.showConfirmDialog(null, "Do You Want To Close Tab ?");
if (response == 0)
tabbedPane1.remove(tabbedPane1.getSelectedComponent());
tabIndex--;
}
};
btnClose.addActionListener(listener);
}
I've created an app with utilities I usually use on my pc (like sending shutdown to cmd.exe) and as some friends asked me to give it to them I was trying to add an update system that checks for updates on a server to make it easier that their version is always updated.
The thing is that I've been over the net searching any solution but all of them just tell to use .close() and my file has it right after stop needing it. When I run it everything works fine and there are no exceptions thrown, so I just dunno what can be wrong.
Whole class:
public class Main_Gui extends JFrame {
private Thread worker;
private final String root = "update/";
private JTextArea outText;
private JButton cancel;
private JButton launch;
private JScrollPane sp;
private JPanel pan1;
private JPanel pan2;
private String zipFile = "Actualización.zip";
private String path = "http://ritsu.hol.es/url.html";
private String TITLE = "RitsUtilities | Actualizador";
public Main_Gui() {
initComponents();
outText.setText("Conectando con el servidor...");
download();
}
private void initComponents() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setTitle(TITLE);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pan1 = new JPanel();
pan1.setLayout(new BorderLayout());
pan2 = new JPanel();
pan2.setLayout(new FlowLayout());
outText = new JTextArea();
sp = new JScrollPane();
sp.setViewportView(outText);
launch = new JButton("Ejecutar RitsUtilities");
launch.setEnabled(false);
launch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] run = { "java", "-jar", "RitsUtilities.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
launch();
}
});
pan2.add(launch);
cancel = new JButton("Salir");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pan2.add(cancel);
pan1.add(sp, BorderLayout.CENTER);
pan1.add(pan2, BorderLayout.SOUTH);
add(pan1);
pack();
setSize(500, 400);
setLocationRelativeTo(null);
}
private void download() {
worker = new Thread(new Runnable() {
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
});
worker.start();
}
private void launch() {
String[] run = { "java", "-jar", "update app.jar" };
try {
Runtime.getRuntime().exec(run);
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
}
private void cleanup() {
outText.setText(outText.getText() + "\nLimpiando archivos temporales...");
remove(new File(root));
new File(root).delete();
}
private void remove(File f) {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
remove(ff);
ff.delete();
} else {
ff.delete();
}
}
}
private void copyFiles(File f, String dir) throws IOException {
File[] files = f.listFiles();
for (File ff : files) {
if (ff.isDirectory()) {
new File(dir + "/" + ff.getName()).mkdir();
copyFiles(ff, dir + "/" + ff.getName());
} else {
copy(ff.getAbsolutePath(), dir + "/" + ff.getName());
}
}
}
public void copy(String srFile, String dtFile) throws FileNotFoundException, IOException {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
private void unzip() throws IOException {
int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(zipFile);
Enumeration e = zipfile.entries();
(new File(root)).mkdir();
while (e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
outText.setText(outText.getText() + "\nExtrayendo: " + entry);
if (entry.isDirectory())
(new File(root + entry.getName())).mkdir();
else {
(new File(root + entry.getName())).createNewFile();
is = new BufferedInputStream(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new FileOutputStream(root + entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
}
}
private void downloadFile(String link) throws MalformedURLException, IOException {
URL url = new URL(link);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
long max = conn.getContentLength();
outText.setText(outText.getText() + "\n" + "Descargando archivo...\nTamaño de la actualización(comprimida): " + max + " Bytes");
BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File(zipFile)));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
int in = 0;
while ((bytesRead = is.read(buffer)) != -1) {
in += bytesRead;
fOut.write(buffer, 0, bytesRead);
}
fOut.flush();
fOut.close();
is.close();
outText.setText(outText.getText() + "\n¡Descarga completada!");
}
private String getDownloadLinkFromHost() throws MalformedURLException, IOException {
URL url = new URL(path);
InputStream html = null;
html = url.openStream();
int c = 0;
StringBuilder buffer = new StringBuilder("");
while (c != -1) {
c = html.read();
buffer.append((char) c);
}
return buffer.substring(buffer.indexOf("[url]") + 5, buffer.indexOf("[/url]"));
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main_Gui().setVisible(true);
}
});
}
}
EDIT: changed private String zipFile = "Actualización.zip"; to private String zipFile = "Update.zip"; but still just deleting temp files/directories but not that "Update.zip" folder that the app downloads.
The File#delete() method you are using doesn't throw an error if the file can't be deleted, it returns false. This is documented in the Javadoc, together with an alternative solution (emphasize mine):
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.
Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.
Finally it's working, just added a forced delete on run() inside download() so now my code looks like
public void run() {
try {
downloadFile(getDownloadLinkFromHost());
unzip();
copyFiles(new File(root), new File("").getAbsolutePath());
cleanup();
launch.setEnabled(true);
+ System.gc();
+ File tmpf = new File(zipFile);
+ tmpf.deleteOnExit();
outText.setText(outText.getText() + "\n¡Actualización completada con éxito!");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Ha ocurrido un error al descargar y descomprimir la actualización.", "Error 1", JOptionPane.WARNING_MESSAGE);
}
}
I'm pretty sure that there are way better ways to do this, but that one seems to work for me.
Thanks to everyone that answered and tried to help me. =D
I would suggest improving your remove(File f) method. Add some checks for the Boolean return value of ff.delete(), that will tell you if the file is actually being deleted or not.
Also, you could add some logs into that method, so you could debug what is actually doing, perhaps it's not seeing the files or something.
One last comment. You should make your code more modular. Create more abstractions and give each of them a simple task. That is the essence of Object Oriented Design. Then, you can program some JUnit tests for each object, and you can run the tests every time you make a change. I reccomend you give a look to this article on Cohesion
once a user selects the button "CLICK HERE TO UPLOAD", the3 file path is stored into a file, and these paths are read into an arraylist, which is shown on the JPanel. the problem is that once a file is selected, it is never updated automatically on the JPanel, unless the application is re runed, before the up to date number of information is displayed. How can this problem be rectified, because i have no clue where i have gone wrong. By the way the arraylists gets updated on runtime but the JPanel never gets updated.
public class Media2 extends JPanel {
private JPanel video_pnl, control_pnl;
private JButton play_btn;
private JLabel loc_lbl;
private int increment;
ArrayList<String> file_location;
ArrayList<JButton> button_lists;
private FileWriter file_writer;
private BufferedWriter buffered_writer;
private JFileChooser filechooser;
private File file;
private JButton btn_upload;
private BufferedReader br;
private FileReader fr;
public Media2(ArrayList<String> file_location) throws IOException {
btn_upload = new JButton("Click here to Upload Video");
String file_path = "C:\\Users\\goldAnthony\\Documents\\NetBeansProjects\\VDMS\\src\\VideoInfos.txt";
file = new File(file_path);
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
add(btn_upload);
Handlers handler = new Handlers();
btn_upload.addActionListener(handler);
this.file_location = file_location;
readFile(file_location, file_path);
}
private void readFile(ArrayList<String> file_location, String file_path) throws FileNotFoundException, IOException {
fr = new FileReader(file_path);
br = new BufferedReader(fr);
String text = "";
String line2;
line2 = br.readLine();
while (line2 != null) {
int i = 0;
file_location.add(i, line2);
line2 = br.readLine();
i++;
}
configurePanel(file_location);
//System.out.print(file_location.size() + "in the read file 1");
}
private void configurePanel(ArrayList<String> file_location) {
increment = 0;
while (increment < file_location.size()) {
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(file_location.get(increment));
control_pnl = new JPanel();
control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
video_pnl.add(loc_lbl);
control_pnl.add(createButton(increment));
video_pnl.add(control_pnl, BorderLayout.SOUTH);
video_pnl.revalidate();
add(video_pnl);
increment++;
}
}
private JButton createButton(final int i) {
play_btn = new JButton("Play");
play_btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// System.out.println(file_location.get(i));
play(i);
}
});
return play_btn;
}
public void play(int i) {
System.out.println(file_location.get(i));
}
private class Handlers implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_upload) {
try { //display the image in jlabel
file = new File("C:\\Users\\goldAnthony\\Documents\\NetBeansProjects\\VDMS\\src\\VideoInfos.txt");
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
buffered_writer = new BufferedWriter(file_writer);
//creating a file chooser
filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your Video");
// //below codes for select the file
int returnval = filechooser.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = filechooser.getSelectedFile();
String filename = file.getAbsolutePath();
buffered_writer.write(filename);
buffered_writer.newLine();
buffered_writer.close();
}
} catch (IOException | HeadlessException ex) {
System.out.println(ex.getMessage());
}
}
}
}
public static void main(String[] args) throws IOException {
//Declare and initialize local variables
ArrayList<String> file_location = new ArrayList<>();
//creates instances of the VlcPlayer object, pass the mediaPath and invokes the method "run"
Media2 mediaplayer = new Media2(file_location);
JFrame ourframe = new JFrame();
ourframe.setContentPane(mediaplayer);
ourframe.setLayout(new GridLayout(5, 1));
ourframe.setSize(300, 560);
ourframe.setVisible(true);
ourframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
When you add components to a visible GUI the basic code is:
panel.add(...);
panel.revalidate();
panel.repaint();
You are revalidating the wrong panel:
video_pnl.revalidate(); // wrong panel
add(video_pnl);
You should be doing:
//video_pnl.revalidate();
add(video_pnl);
revalidate();
repaint();
Your code needs some changes, try:
private void configurePanel(ArrayList<String> file_location) {
increment = 0;
while (increment < file_location.size()) {
addEntry(file_location.get(increment));//--------->New line
increment++;
}
}
private void addEntry(String location) {//--------->New constructor
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(location);
control_pnl = new JPanel();
control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
video_pnl.add(loc_lbl);
control_pnl.add(createButton(increment));
video_pnl.add(control_pnl, BorderLayout.SOUTH);
video_pnl.revalidate();
add(video_pnl);
}
and:
private class Handlers implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn_upload) {
try { //display the image in jlabel
file = new File("C:\\VideoInfos.txt");
if (!file.exists()) {
file.createNewFile();
file_writer = new FileWriter(file.getAbsolutePath());
} else {
file_writer = new FileWriter(file.getAbsolutePath(), true);
}
buffered_writer = new BufferedWriter(file_writer);
//creating a file chooser
filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your Video");
// //below codes for select the file
int returnval = filechooser.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = filechooser.getSelectedFile();
String filename = file.getAbsolutePath();
buffered_writer.newLine();
buffered_writer.write(filename);
buffered_writer.newLine();
buffered_writer.close();
addEntry(filename);//---------------->New Line
validate();//------------>New Line
}
} catch (IOException | HeadlessException ex) {
System.out.println(ex.getMessage());
}
}
}
}
Now it's working. You have to make further changes, of course :)
As you see, I've been researching and tried to set a thread in main.java class. This is the main method:
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new main().setVisible(true);
check ch = new check();
ch.start();
}
});
}
Main method calls a thread called ch , from check.java class.
This is the thread class:
public class check extends Thread {
public JTextArea estado = new JTextArea();
public JTextField updatedVersion = new JTextField();
public JLabel updatedLabel = new JLabel();
public String catchUpdatedVersion;
int UPDATENUMBER;
int CURRENTNUMBER;
public void run() {
String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
String name = "thread.inf";
File file = new File(name);
try {
URLConnection conn = new URL(infURL).openConnection();
conn.connect();
estado.append("Conectando al servidor...");
estado.append(System.getProperty("line.separator"));
estado.append(" -- Buscando actualizaciones... --");
estado.append(System.getProperty("line.separator"));
InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(file);
int b = 0;
while (b != -1) {
b = in.read();
if (b != -1) {
out.write(b);
}
}
out.close();
in.close();
} catch (MalformedURLException ex) {
} catch (IOException ioe) { }
String fileToReadUpdatedVersion = "thread.inf";
try {
BufferedReader br = new BufferedReader(
new FileReader(fileToReadUpdatedVersion));
String brr = br.readLine();
catchUpdatedVersion = brr.substring(34,42);
String catchUpdatedShortVersion = brr.substring(15,16);
UPDATENUMBER = Integer.parseInt(catchUpdatedShortVersion);
String fileToReadCurrentVer = "thread.inf";
BufferedReader brrw = new BufferedReader(
new FileReader(fileToReadCurrentVer));
String brrwREAD = brrw.readLine();
String catchCurrentShortVersion = brrwREAD.substring(15,16);
CURRENTNUMBER = Integer.parseInt(catchCurrentShortVersion);
if (CURRENTNUMBER >= UPDATENUMBER) {
estado.setText("No se han encontrado actualizaciones.");
} else {
updatedVersion.setForeground(new Color(0,102,0));
updatedLabel.setForeground(new Color(0,153,51));
updatedVersion.setText(catchUpdatedVersion);
estado.append("-------------------" +
"NUEVA ACTUALIZACIÓN DISPONIBLE: " +
catchUpdatedVersion + " -------------------");;
estado.append(System.getProperty("line.separator"));
estado.append("Descargando actualizaciones... " +
"Espere por favor, no cierre este " +
"programa hasta que esté completado...");
try {
String updateURL = "https://thread.googlecode.com/" +
"svn/trunk/thread.inf";
String updatedname = (catchUpdatedVersion + ".zip");
File updatedfile = new File(updatedname);
URLConnection conn = new URL(updateURL).openConnection();
conn.connect();
estado.append(System.getProperty("line.separator"));
estado.append(" Archivo actual: " + updatedname);
estado.append(System.getProperty("line.separator"));
estado.append(" Tamaño: " +
conn.getContentLength() / 1000 / 1000 + " MB");
InputStream in = conn.getInputStream();
OutputStream out = new FileOutputStream(updatedfile);
int c = 0;
while (c != -1) {
c = in.read();
if (c != -1) {
out.write(c);
}
}
out.close();
in.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
} catch (IOException ioe) {
System.out.println(ioe);
ioe.printStackTrace();
}
}
}
When I run the program, the thread does not work fine. It is supposed to download a file and then display its progress in a JTextArea in main.java class. It does download the file, but nothing appears in JTextArea.
Where is my mistake?
EDIT: Showing all the code.
Problem #1
The components you are trying to update are not, in any way, connected to the screen...
public JTextArea estado = new JTextArea();
public JTextField updatedVersion = new JTextField();
public JLabel updatedLabel = new JLabel();
That means, anytime you interact with these components, it's doing nothing to what's on the screen...
Problem #2
You're trying to make modifications to the UI from outside the context of the Event Dispatching Thread. This is significant violation of the Swing threading rules.
public class Check extends SwingWorker<String, String> {
private JTextArea estado;
Private JTextField updatedVersion;
private JLabel updatedLabel;
private String catchUpdatedVersion;
int UPDATENUMBER;
int CURRENTNUMBER;
public Check(JTextArea estado, JTextField updatedVersion, JLabel updatedLabel) {
this.estado = estado;
this.updatedVersion = updatedVersion;
this.updatedLabel = updatedLabel;
}
protected void process(List<String> values) {
for (String value : values) {
estado.append(value);
}
}
protected String doInBackground() throws Exception {
String infURL = "https://thread.googlecode.com/svn/trunk/thread.inf";
String name = "thread.inf";
File file = new File(name);
URLConnection conn = new URL(infURL).openConnection();
conn.connect();
publish("Conectando al servidor...");
publish(System.getProperty("line.separator"));
publish(" -- Buscando actualizaciones... --");
publish(System.getProperty("line.separator"));
/*...*/
}
}
IfYou need to do any post-processing, then you also override done which will be called after doInBackground has existed, but is called within the context of the EDT
For more details read through Concurrency in Swing