I want to read a word document with the help of microsoft word but that would be limited to my java form . The document will be opened in java form with the help of microsoft word .
Like the following picture , I want to develop something :
User can edit the doc according to their need . But when they want to save the document , the document will be saved in a remote machine .
I can open the word document with the help of microsoft word by the following code :
try {
/* if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(new File("E:\\finger.docx"));
}*/
Process p = Runtime.getRuntime()
.exec("rundll32 url.dll,FileProtocolHandler E:\\finger.docx");
p.waitFor();
System.out.println("Done.");
} catch (IOException ioe) {
ioe.printStackTrace();
}
catch (InterruptedException ex) {
Logger.getLogger(JavaFromWord.class.getName()).log(Level.SEVERE, null, ex);
}
But I do not know how can I embed the word viewer in JForm . Please help me .
I have succeeded to do this job . The following code helps me a lot to do it .
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleClientSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import com.connect.DBConnectionHandler;
public class SWTMenuExample {
static OleClientSite clientSite;
static OleFrame frame;
static File file;
static Shell shell;
static KeyListener keyListener;
static Display display;
public static void main(final String[] args) {
display = new Display();
shell = new Shell(display);
shell.setSize(800, 600);
shell.setText("Word Example");
shell.setLayout(new FillLayout());
try {
frame = new OleFrame(shell, SWT.NONE);
// esto abre un documento existente
// clientSite = new OleClientSite(frame, SWT.NONE, new
// File("Doc1.doc"));
// esto abre un documento en blanco
// clientSite = new OleClientSite(frame, SWT.NONE, "Word.Document");
addFileMenu(frame);
System.out.println(" I am in run method ");
} catch (final SWTError e) {
System.out.println("Unable to open activeX control");
display.dispose();
return;
}
keyListener = new KeyListener() {
public void keyReleased(KeyEvent paramKeyEvent) {
}
public void keyPressed(KeyEvent paramKeyEvent) {
// TODO Auto-generated method stub
if (((paramKeyEvent.stateMask & SWT.CTRL) == SWT.CTRL)
&& (paramKeyEvent.keyCode == 's')) {
JOptionPane.showMessageDialog(null,
"ctrl+s is pressed down initial ",
"Warning Message", JOptionPane.WARNING_MESSAGE);
if (file != null) {
clientSite.save(file, true);
fileSave();
JOptionPane.showMessageDialog(null,
"ctrl+s is pressed down", "Warning Message",
JOptionPane.WARNING_MESSAGE);
} else
JOptionPane.showMessageDialog(null, "File is null",
"Warning Message", JOptionPane.WARNING_MESSAGE);
}
}
};
display.addFilter(SWT.KeyDown, new Listener() {
public void handleEvent(Event e) {
if (((e.stateMask & SWT.CTRL) == SWT.CTRL)
&& (e.keyCode == 's')) {
System.out.println("From Display I am the Key down !!"
+ e.keyCode);
}
}
});
final Color green = display.getSystemColor(SWT.COLOR_GREEN);
final Color orig = shell.getBackground();
shell.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
if (((e.stateMask & SWT.CTRL) == SWT.CTRL)
&& (e.keyCode == 's')) {
shell.setBackground(orig);
System.out.println("Key up !!");
}
}
public void keyPressed(KeyEvent e) {
if (((e.stateMask & SWT.CTRL) == SWT.CTRL)
&& (e.keyCode == 's')) {
shell.setBackground(green);
System.out.println("Key down !!");
}
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
static void addFileMenu(OleFrame frame) {
final Shell shell = frame.getShell();
Menu menuBar = shell.getMenuBar();
if (menuBar == null) {
menuBar = new Menu(shell, SWT.BAR);
shell.setMenuBar(menuBar);
}
MenuItem fileMenu = new MenuItem(menuBar, SWT.CASCADE);
fileMenu.setText("&File");
Menu menuFile = new Menu(fileMenu);
fileMenu.setMenu(menuFile);
frame.setFileMenus(new MenuItem[] { fileMenu });
MenuItem menuFileCreate = new MenuItem(menuFile, SWT.CASCADE);
menuFileCreate.setText("Create File");
menuFileCreate.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fileCreate();
}
});
MenuItem menuFileOpen = new MenuItem(menuFile, SWT.CASCADE);
menuFileOpen.setText("Open File");
menuFileOpen.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fileOpen();
}
});
MenuItem menuFileSave = new MenuItem(menuFile, SWT.CASCADE);
menuFileSave.setText("Save File");
menuFileSave.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (file != null) {
clientSite.save(file, true);
fileSave();
}
}
});
MenuItem menuFileClose = new MenuItem(menuFile, SWT.CASCADE);
menuFileClose.setText("Close File");
menuFileClose.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (clientSite != null) {
clientSite.dispose();
file = null;
}
}
});
}
static void fileCreate() {
if (clientSite != null)
clientSite.dispose();
if (file != null)
file.delete();
String fileName = JOptionPane
.showInputDialog("Please input the name of you file: ");
if (fileName != null) {
if (fileName.trim().equals("")) {
JFrame frame = new JFrame(
"JOptionPane showMessageDialog example");
JOptionPane.showMessageDialog(frame,
"File Name must have some value", "Warning Message",
JOptionPane.WARNING_MESSAGE);
} else {
Connection conn = DBConnectionHandler.getConnection();
PreparedStatement pstmt;
try {
pstmt = conn
.prepareStatement("insert into FILEDATA(PR_KEY, FILENAME, FILEDATA) values (seq_file.nextval,?, EMPTY_BLOB())");
pstmt.setString(1, fileName + ".docx");
pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
static void fileOpen() {
List<String> FileName = new ArrayList<String>();
try {
Connection conn = DBConnectionHandler.getConnection();
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select FILENAME from FILEDATA");
while (rset.next())
FileName.add(rset.getString(1));
System.out.println("List Size "+FileName.size());
if (clientSite != null)
clientSite.dispose();
shell.setVisible(false);
if (file != null)
file.delete();
SWTMenuExample swtClass = new SWTMenuExample();
NewJFrame form = new NewJFrame(FileName, clientSite, shell, frame,
swtClass);
form.setVisible(true);
form.setSize(400, 400);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* FileDialog dialog = new FileDialog(shell, SWT.OPEN);
* dialog.setFilterExtensions(new String[] { "*.docx" }); String
* fileName = dialog.open(); if (fileName != null) { if (clientSite !=
* null) clientSite.dispose(); file = new File(fileName); clientSite =
* new OleClientSite(frame, SWT.NONE, "Word.Document", file);
* clientSite.addKeyListener(keyListener);
* clientSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE); }
*/
}
void fileOpenFromDrive(File happyFile) {
file = happyFile;
display.asyncExec(new Runnable() {
#Override
public void run() {
shell.setVisible(true);
if (clientSite != null)
clientSite.dispose();
clientSite = new OleClientSite(frame, SWT.NONE,
"Word.Document", file);
clientSite.addKeyListener(keyListener);
clientSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
shell.addListener(SWT.Close, new Listener() {
public void handleEvent(Event event) {
if (file != null)
file.delete();
shell.dispose();
}
});
}
});
}
static void fileSave() {
try {
FileInputStream fis = new FileInputStream(file);
Connection conn = DBConnectionHandler.getConnection();
PreparedStatement pstmt = conn
.prepareStatement("update FILEDATA set FILEDATA = ? where FILENAME = ?");
pstmt.setBinaryStream(1, fis, (int) file.length());
pstmt.setString(2, file.getName());
pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It will open docx as like in the following picture :
As others have pointed out, this sounds a lot like an XY problem—meaning, you have already decided that the best solution is using Microsoft Word, so you are asking how to embed Microsoft Word instead of asking about your actual goal, which appears to be incorporating formatted text in a user interface.
A good way to do this is with a JEditorPane containing HTML content:
import java.awt.EventQueue;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class HtmlPane {
static void show() {
JEditorPane content = new JEditorPane("text/html",
"<p>" +
"The process of finger enrollment is now to be done in database." +
" Previously it was done in file template." +
" There are several reasons behind this:" +
"<ol>" +
"<li>" +
"Time:<br>" +
"--------" +
"<p>" +
"The process of verification in file template based method takes" +
" 6.9 s on average. On the other hand, in database based method," +
" it takes only 3.5 s." +
"<p>" +
"The code for determining time is as follows:" +
"<blockquote>" +
"<pre>" +
"Dim StartTime, Elapsed Time\n" +
"StartTime = Timer\n" +
"ElapsedTime = Timer.CheckTime\n" +
"</pre>" +
"</blockquote>" +
"</ol>");
content.setEditable(false);
JFrame frame = new JFrame("finger");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(content));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> show());
}
}
(Note: The Swing HTML renderer only supports HTML 3.2.)
If you aren’t familiar with HTML, I advise you to learn it. Basic HTML is very easy to write. Plus, you need to know basic HTML to be an effective Java programmer, because professional development requires writing javadoc, and all javadoc is in HTML.
Actaully, you can't show any not-your-project-frames in your java gui application, it is actaully unreal - you can only show java frames in JInternalFrame
Related
I have been working on my "Random Trivia" program and I keep getting stack overflow with NO recursiveness, at least I cannot find any, here is the code to Gui.java, the main class(and only class)
package mods.giantnuker.random_trivia;
import java.awt.event.ActionEvent;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import mods.giantnuker.javautil.FileFilterAccessor;
import mods.giantnuker.javautil.Pair;
import mods.giantnuker.javautil.PairList;
import mods.giantnuker.javautil.file.parser.XMLParser;
import javax.swing.JFileChooser;
#SuppressWarnings("serial")
public class Gui extends JFrame implements ActionListener, ItemListener {
String tsn;
JFileChooser dialg;
JPanel welcome, newt;
JButton sbttn, nbttn, ebttn, nqb, nab, dqb, dab, sav, ext;
#SuppressWarnings("rawtypes")
JComboBox questions, answers;
List<Pair<String, PairList<String, Integer>>> trivia;
public static void main(String[] args) {
new Gui();
}
#SuppressWarnings({ "static-access", "rawtypes" })
public Gui() {
super("Random Trivia");
this.setSize(300, 250);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
//New
newt = new JPanel();
newt.setLayout(new BoxLayout(newt, BoxLayout.Y_AXIS));
questions = new JComboBox();
questions.addItemListener(this);
answers = new JComboBox();
nqb = new JButton("New Question+ ");
nab = new JButton("New Answer+ ");
dqb = new JButton("-Delete Question");
dab = new JButton("-Delete Answer ");
sav = new JButton("*Save ");
ext = new JButton("-Exit- ");
nqb.addActionListener(this);
nab.addActionListener(this);
dqb.addActionListener(this);
dab.addActionListener(this);
sav.addActionListener(this);
ext.addActionListener(this);
newt.add(questions);
newt.add(answers);
newt.add(nqb);
newt.add(nab);
newt.add(dqb);
newt.add(dab);
newt.add(sav);
newt.add(ext);
//Welcome
welcome = new JPanel();
welcome.setLayout(new BoxLayout(welcome, BoxLayout.Y_AXIS));
welcome.add(new JLabel("Welcome To Random Trivia!"));
welcome.add(sbttn = new JButton("Select a file(.trv) to use"));
welcome.add(nbttn = new JButton("Create a new one"));
welcome.add(ebttn = new JButton("Or edit an old one"));
sbttn.addActionListener(this);
nbttn.addActionListener(this);
ebttn.addActionListener(this);
dialg = new JFileChooser();
dialg.setDialogType(dialg.OPEN_DIALOG);
dialg.setFileFilter(new FileFilterAccessor("trv"));
this.add(welcome);
this.setVisible(true);
}
#SuppressWarnings({ "unchecked", "rawtypes", "static-access" })
#Override
public void actionPerformed(ActionEvent arg0) {
Object src = arg0.getSource();
if (src == sbttn) {
dialg.setDialogType(dialg.OPEN_DIALOG);
List<Map<String, Integer>> trivia = new ArrayList();
int out = dialg.showOpenDialog(null);
if(out == 0) {
File f = dialg.getSelectedFile();
}
}
if (src == nbttn) {
trivia = new ArrayList();
this.remove(welcome);
this.add(newt);
this.setVisible(true);
}
if (src == ebttn) {
dialg.setDialogType(dialg.OPEN_DIALOG);
int out = dialg.showOpenDialog(null);
if(out == 0) {
trivia = parse(dialg.getSelectedFile());
this.remove(welcome);
this.add(newt);
ref();
this.setVisible(true);
}
}
if (src == ext) {
this.remove(newt);
this.add(welcome);
this.setVisible(true);
}
if (src == nqb) {
String txt = JOptionPane.showInputDialog(this ,"Enter the Question:", "Question...");
if (txt.length() > 0 && !txt.equals("Question...")) {
trivia.add(new Pair(txt, new PairList()));
questions.addItem(txt);
}
}
if (src == nab) {
if (questions.getItemCount() == 0) {
JOptionPane.showMessageDialog(this, "You must select a question or create one!", "Error", JOptionPane.WARNING_MESSAGE);
return;
}
String txt = JOptionPane.showInputDialog(this ,"Enter the Answer:", "Answer...");
String txt2 = JOptionPane.showInputDialog(this ,"Enter the amount of points for the Answer:", "Points...");
if (txt.length() > 0 && !txt.equals("Answer...")) {
if (txt2.length() > 0 && !txt2.equals("Points...")) {
int points = 0;
boolean err = true;
while(err) {
try {
points = Integer.valueOf(txt2);
err = false;
} catch (NumberFormatException e) {
txt2 = JOptionPane.showInputDialog(this ,"Enter the amount of points for the Answer:", "Points...");
if (txt2.equals("Points...")) return;
}
}
trivia.get(questions.getSelectedIndex()).getB().add(txt, points);
answers.addItem(txt + "(" + points + " points)");
}
}
}
if (src == dab) {
if (questions.getItemCount() == 0) {
JOptionPane.showMessageDialog(this, "You must select a question!", "Error", JOptionPane.WARNING_MESSAGE);
return;
}
if (answers.getItemCount() != 0) {
trivia.get(questions.getSelectedIndex()).getB().remove(answers.getSelectedIndex());
answers.removeItemAt(answers.getSelectedIndex());
}
}
if (src == dqb) {
if (questions.getItemCount() != 0) {
trivia.remove(trivia.get(questions.getSelectedIndex()));
questions.removeItemAt(questions.getSelectedIndex());
ref();
}
}
if (src == sav) {
tsn = JOptionPane.showInputDialog(this ,"Enter the name of the Trivia:", "Name...");
if (!tsn.equals("Name...")) newTriviaSave();
}
}
#SuppressWarnings("static-access")
public void newTriviaSave() {
dialg.setDialogType(dialg.SAVE_DIALOG);
int out = dialg.showSaveDialog(null);
if(out == 0) {
File f = dialg.getSelectedFile();
if (!f.getPath().contains(".")) {
f = new File(f.getPath() + ".trv");
}
System.out.println(f.getPath());
toFile(f, trivia, tsn);
}
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public List<Pair<String, PairList<String, Integer>>> parse(File f) {
List<Pair<String, PairList<String, Integer>>> trivia = new ArrayList();
XMLParser p = new XMLParser(f);
try {
p.read();
p.doc.getDocumentElement().normalize();
NodeList l = p.doc.getElementsByTagName("trivia");
Element root = (Element) l.item(0);
tsn = root.getAttribute("name");
l = root.getElementsByTagName("question");
for (int i = 0; i < l.getLength(); i++) {
Element question = (Element)l.item(i);
NodeList l2 = question.getElementsByTagName("answer");
PairList<String, Integer> answers = new PairList();
for (int j = 0; j < l2.getLength(); j++) {
Element answer = (Element)l2.item(j);
answers.add(answer.getAttribute("text"), Integer.valueOf(answer.getAttribute("points")));
}
trivia.add(new Pair(question.getAttribute("text"), answers));
}
} catch (Exception e) {
}
return trivia;
}
public void toFile(File f, List<Pair<String, PairList<String, Integer>>> questions, String name) {
XMLParser p = new XMLParser(f);
try {
p.create();
Element root = p.doc.createElement("trivia");
root.setAttribute("name", name);
for (Pair<String, PairList<String, Integer>> question : questions) {
Element questionE = p.doc.createElement("question");
questionE.setAttribute("text", question.getA());
for (Pair<String, Integer> answer : question.getB()) {
Element answerE = p.doc.createElement("answer");
answerE.setAttribute("text", answer.getA());
answerE.setAttribute("points", String.valueOf(answer.getB()));
questionE.appendChild(answerE);
}
root.appendChild(questionE);
}
p.doc.appendChild(root);
p.write();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void itemStateChanged(ItemEvent arg0) {
Object src = arg0.getSource();
if (src == questions) {
ref();
}
}
#SuppressWarnings("unchecked")
public void ref() {
questions.removeAllItems();
answers.removeAllItems();
for (Pair<String, PairList<String, Integer>> p : trivia) {
questions.addItem(p.getA());
}
if (questions.getItemCount() != 0) {
PairList<String, Integer> answes = trivia.get(questions.getSelectedIndex()).getB();
for (Pair<String, Integer> ans : answes) {
answers.addItem(ans.getA() + "(" + ans.getB() + " points)");
}
}
}
}
JavaUtil works fine - not related to it.
Here is a runnable jar with JavaUtil prepackaged.
to get my error, click on "edit an old one" and open the following file(just a dummy file, you could make your own and get the same result)
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<trivia name="Dummy Trivia">
<question text="dum">
<answer points="1" text="ans1"/>
</question><question text="dum2">
<answer points="1" text="ans1"/>
<answer points="2" text="ans2"/>
</question>
<question text="dum3">
<answer points="1" text="ans1"/>
<answer points="2" text="ans2"/>
<answer points="3" text="ans3"/>
</question>
</trivia>
Thank you :)
EDIT: Stack overflow is in ref() \ stands for refresh
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at javax.swing.plaf.basic.BasicComboBoxUI$Handler.contentsChanged(BasicComboBoxUI.java:1858)
at javax.swing.plaf.basic.BasicComboBoxUI$Handler.intervalRemoved(BasicComboBoxUI.java:1877)
at javax.swing.AbstractListModel.fireIntervalRemoved(AbstractListModel.java:179)
at javax.swing.DefaultComboBoxModel.removeAllElements(DefaultComboBoxModel.java:174)
at javax.swing.JComboBox.removeAllItems(JComboBox.java:771)
at mods.giantnuker.random_trivia.Gui.ref(Gui.java:264)
at mods.giantnuker.random_trivia.Gui.itemStateChanged(Gui.java:258)
at javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1223)
at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1280)
at javax.swing.JComboBox.contentsChanged(JComboBox.java:1329)
at javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:118)
at javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:93)
at javax.swing.DefaultComboBoxModel.addElement(DefaultComboBoxModel.java:131)
at javax.swing.JComboBox.addItem(JComboBox.java:716)
at mods.giantnuker.random_trivia.Gui.ref(Gui.java:267)
at mods.giantnuker.random_trivia.Gui.itemStateChanged(Gui.java:258)
at javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1223)
at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1271)
at javax.swing.JComboBox.contentsChanged(JComboBox.java:1329)
at javax.swing.JComboBox.intervalRemoved(JComboBox.java:1351)
at javax.swing.AbstractListModel.fireIntervalRemoved(AbstractListModel.java:179)
at javax.swing.DefaultComboBoxModel.removeAllElements(DefaultComboBoxModel.java:174)
at javax.swing.JComboBox.removeAllItems(JComboBox.java:771)
at mods.giantnuker.random_trivia.Gui.ref(Gui.java:264)
at mods.giantnuker.random_trivia.Gui.itemStateChanged(Gui.java:258)
at javax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1223)
at javax.swing.JComboBox.selectedItemChanged(JComboBox.java:1280)
at javax.swing.JComboBox.contentsChanged(JComboBox.java:1329)
at javax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:118)
at javax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:93)
at javax.swing.DefaultComboBoxModel.addElement(DefaultComboBoxModel.java:131)
at javax.swing.JComboBox.addItem(JComboBox.java:716)
at mods.giantnuker.random_trivia.Gui.ref(Gui.java:267)
Continuing...
Looking at your stack trace, we see a problem centered on the ref() method and removing components from a JComboBox.
There appears to be a problem here:
#Override
public void itemStateChanged(ItemEvent arg0) {
Object src = arg0.getSource();
if (src == questions) {
ref();
}
}
#SuppressWarnings("unchecked")
public void ref() {
questions.removeAllItems();
answers.removeAllItems();
...
Your ItemListener, (this -- which has been added to both questions and answers JComboBoxes) calls the ref() method which changes the state of both JComboBoxs, which triggers the ItemListener, which calls the ref() method ..... ad infinitum.
Don't change the state of an object from within one of its listeners, or if you absolutely need to do this, then inactivate or remove the listeners first, and then re-add them. e.g.,
public void ref() {
// first remove all item listeners
ItemListener[] questionListeners = questions.getItemListeners();
ItemListener[] answerListeners = answers.getItemListeners();
for (ItemListener l : questionListeners) {
questions.removeItemListener(l);
}
for (ItemListener l : answerListeners) {
answers.removeItemListener(l);
}
// change state
questions.removeAllItems();
answers.removeAllItems();
// re-add all listeners
for (ItemListener l : questionListeners) {
questions.addItemListener(l);
}
for (ItemListener l : answerListeners) {
answers.addItemListener(l);
}
...
boolean err = true;
while(err) {
try {
points = Integer.valueOf(txt2);
err = false;
} catch (NumberFormatException e) {
txt2 = JOptionPane.showInputDialog(this, "Enter the amount of points for the Answer:", "Points...");
if (txt2.equals("Points..."))
return;
}
}
I am looking into this. if text2 is not a number, it will throw an exception, and it won't set err to false. This might cause the loop to go on infinitely assuming text2 is not equal to "Points..."
I'm coding a swing App. Here the tasks are to download the file from a given URL and then get the counts of them. The program works with no issues/errors.
The problem is I've a testarea in my frame, when file 1 is downloaded I want the text area to show downloaded file 1 and when file 2 is done downloaded file 1 and so on...
Currently in my program the message is displayed but all at once. I mean if I've 10 files, it shows.
downloaded file 1
downloaded file 2
.
.
.
.
.
downloaded file 10
But this is shown only after all the 10 files are downloaded. To see if there is any other problem, I've added sysout just below the textarea code. And to my surprise, sysouts are printed 10 times, I mean each time a file is processed, this is triggered, but the textarea is appended with all the data at a time.
Below are my codes.
GuiForPDFs
import java.awt.BorderLayout;
public class GuiForPDFs extends JFrame {
private JPanel contentPane;
private JTextField srcTextField;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuiForPDFs frame = new GuiForPDFs();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
FileDownloadTest downloadTest = new FileDownloadTest();
public GuiForPDFs() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 552, 358);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
srcTextField = new JTextField();
srcTextField.setBounds(10, 26, 399, 20);
contentPane.add(srcTextField);
srcTextField.setColumns(10);
JButton srcBtn = new JButton("Source Excel");
srcBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fChoose = new JFileChooser();
if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath());
} else {
System.out.println("No Selection");
}
}
});
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setBounds(10, 106, 516, 203);
contentPane.add(textArea);
srcBtn.setBounds(419, 25, 107, 23);
contentPane.add(srcBtn);
JButton dNcButton = new JButton("Process");
dNcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
downloadTest.fileDownloadTest(srcTextField.getText(), textArea);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
dNcButton.setBounds(212, 70, 89, 23);
contentPane.add(dNcButton);
}
}
FileDownloadTest
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JTextArea;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FileDownloadTest {
public void fileDownloadTest(String src, JTextArea textArea) throws IOException, InterruptedException {
String path = src;
FileInputStream fin = new FileInputStream(new File(path));
XSSFWorkbook workbook = new XSSFWorkbook(fin);
XSSFSheet sheet = workbook.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
System.out.println("rows are " + rows);
XSSFCell cell;
// Make sure that this directory exists
String dirName = src.substring(0, src.lastIndexOf("\\"));
File f = new File(dirName);
if (!f.exists()) {
f.mkdir();
}
System.out.println(f.getAbsolutePath() + " is Directory Name " + src + " is the file");
for (int i = 1; i < rows; i++) {
XSSFCell url = sheet.getRow(i).getCell(0);
String URLString = url.toString();
cell = sheet.getRow(i).getCell(7);
String fileName = URLString.substring(URLString.lastIndexOf("/") + 1);
int pageNumbers = downloadFiles(dirName, url.toString().replace("http", "https"));
if (cell == null) {
cell = sheet.getRow(i).createCell(1);
}
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(pageNumbers);
FileOutputStream fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
textArea.append("downloaded " + fileName + "\n");
System.out.println("Done");
}
workbook.close();
fin.close();
}
public static int downloadFiles(String dirName, String urlString) {
System.out.println("Downloading \'" + urlString + "\' PDF document...");
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
System.out.println(fileName + " is file name");
try {
saveFileFromUrlWithJavaIO(dirName + "\\" + fileName, urlString);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Downloaded \'" + urlString + "\' PDF document...");
int pageNumber = 0;
try {
pageNumber = getNoOfPages(dirName + "\\" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
return pageNumber;
}
public static int getNoOfPages(String fileName) throws IOException {
PDDocument document = PDDocument.load(new File(fileName));
int numberOfPages = document.getNumberOfPages();
return numberOfPages;
}
public static void saveFileFromUrlWithJavaIO(String fileName, String fileUrl)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(fileUrl).openStream());
fout = new FileOutputStream(fileName);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
}
public static void saveFileFromUrlWithCommonsIO(String fileName, String fileUrl)
throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
}
please let me know How can I fix this.
Thanks
The above comments are correct, you are on the EDT when adding text to the TextArea. This is because you are calling downloadTest.fileDownloadTest from the dNcButton ActionListener implementation.
It's good practice to get off the EDT is you have a long running operation to perform, and downloading a file is often given as as example of the sort of thing you don't want to do on the EDT.
There are lots of resources online as to how to get off the EDT, including many on this great site;
On Event Dispatch Thread---want to get off of it
Make thread run on non EDT (event dispatch thread) thread from EDT
As with the other comments, you need to keep only UI related tasks on the EDT. Otherwise if your user is downloading 100 files the UI will lock up until the download task is finished. SwingWorker is the perfect class to do this for Swing applications. Here is a quick example:
// Run your FileDownloadTest inside a SwingWorker
// or have the class extend SwingWorker
new SwingWorker<Void, String>() {
#Override
protected Void doInBackground() throws Exception {
//Perform downloading here (done off the EDT)
//Call publish(downloadedFileName) to be sent to the process method()
return null;
}
#Override
protected void process(List<String> chunks) {
// Modify textArea (done on the EDT)
StringBuilder downloadedFiles = new StringBuilder();
for (String fileName : chunks) {
downloadedFiles.append("downloaded" + fileName + "\n");
}
textArea.setText(downloadedFiles);
}
#Override
protected void done() {
//Anything you want to happen after doInBackground() finishes
}
}.execute();
I am trying to make a simple barcode scanner project for fun. And I've run into a slight problem. I am using zXing and Webcam Capture for this.
Even if a Barcode is present in the picture, Java keeps telling me none is found through the NotFoundException. I look for a frame every time webcamImageObtained is run (which I assume is every frame?) and then I look for a barcode in the frame that I captured.
I took this picture with that webcam (Ironically using the code hah):
When I hover over this barcode it reports about 30 images per second and otherwise about 7-8 when it looks at me from my screen (if that means anything).
Whenever I find a code, I want to add it to a JList (not accounting for duplicates and the likes yet).
I call this code every time webcamImageObtained(WebcamEvent we) fires:
#Override
public void webcamImageObtained(WebcamEvent we) {
BufferedImage myImage;
try {
myImage = webcam.getImage();
LuminanceSource source = new BufferedImageLuminanceSource(myImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap);
DefaultListModel dlm = (DefaultListModel) list.getModel();
dlm.addElement(result.toString());
list.setModel(dlm);
} catch (NotFoundException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ChecksumException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (FormatException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the entire class:
package sandbox_webcam;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamDiscoveryEvent;
import com.github.sarxos.webcam.WebcamDiscoveryListener;
import com.github.sarxos.webcam.WebcamEvent;
import com.github.sarxos.webcam.WebcamListener;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamPicker;
import com.github.sarxos.webcam.WebcamResolution;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
public class AdvancedWebcamPanelExample extends JFrame implements Runnable, WebcamListener, WindowListener, UncaughtExceptionHandler, ItemListener, WebcamDiscoveryListener {
private Webcam webcam = null;
private WebcamPanel panel = null;
private WebcamPicker picker = null;
private JButton button = null;
private JList list = null;
private ActionListener buttonListener = null;
private com.google.zxing.Reader reader = new com.google.zxing.MultiFormatReader();
#Override
public void run() {
Webcam.addDiscoveryListener(this);
setTitle("Java Webcam Capture POC");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
addWindowListener(this);
picker = new WebcamPicker();
picker.addItemListener(this);
webcam = picker.getSelectedWebcam();
if (webcam == null) {
System.out.println("No webcams found...");
System.exit(1);
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.addWebcamListener(AdvancedWebcamPanelExample.this);
panel = new WebcamPanel(webcam, false);
panel.setFPSDisplayed(true);
buttonListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (webcam != null) {
BufferedImage image = webcam.getImage();
JFileChooser filechooser = new JFileChooser();
int saveValue = filechooser.showDialog(button, "Save");
if (saveValue == JFileChooser.APPROVE_OPTION) {
try {
File f = filechooser.getSelectedFile();
ImageIO.write(image, "png", new File(f.getAbsolutePath() + ".png"));
System.out.println("Picture saved at: " + f.getAbsolutePath());
} catch (IOException ex) {
System.err.println("Failed to save the picture!");
ex.printStackTrace();
}
}
} else {
System.err.println("no webcam found to take a picture");
}
}
};
button = new JButton("Snap a Picture!");
button.addActionListener(buttonListener);
list = new JList();
list.setMinimumSize(new Dimension(200,this.getHeight()));
add(picker, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
add(list, BorderLayout.EAST);
pack();
setVisible(true);
Thread t = new Thread() {
#Override
public void run() {
panel.start();
}
};
t.setName("example-starter");
t.setDaemon(true);
t.setUncaughtExceptionHandler(this);
t.start();
}
#Override
public void webcamOpen(WebcamEvent we) {
System.out.println("webcam open");
}
#Override
public void webcamClosed(WebcamEvent we) {
System.out.println("webcam closed");
}
#Override
public void webcamDisposed(WebcamEvent we) {
System.out.println("webcam disposed");
}
#Override
public void webcamImageObtained(WebcamEvent we) {
BufferedImage myImage;
try {
myImage = webcam.getImage();
LuminanceSource source = new BufferedImageLuminanceSource(myImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result = reader.decode(bitmap);
DefaultListModel dlm = (DefaultListModel) list.getModel();
dlm.addElement(result.toString());
list.setModel(dlm);
} catch (NotFoundException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (ChecksumException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (FormatException ex) {
Logger.getLogger(AdvancedWebcamPanelExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void windowOpened(WindowEvent e) {
// do nothing
}
#Override
public void windowClosing(WindowEvent e) {
// do nothing
}
#Override
public void windowClosed(WindowEvent e) {
webcam.close();
}
#Override
public void windowIconified(WindowEvent e) {
System.out.println("webcam viewer paused");
panel.pause();
}
#Override
public void windowDeiconified(WindowEvent e) {
System.out.println("webcam viewer resumed");
panel.resume();
}
#Override
public void windowActivated(WindowEvent e) {
// do nothing
}
#Override
public void windowDeactivated(WindowEvent e) {
// do nothing
}
#Override
public void uncaughtException(Thread t, Throwable e) {
System.err.println(String.format("Exception in thread #s", t.getName()));
e.printStackTrace();
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem() != webcam) {
if (webcam != null) {
panel.stop();
remove(panel);
webcam.removeWebcamListener(this);
webcam.close();
webcam = (Webcam) e.getItem();
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.addWebcamListener(this);
System.out.println("selected " + webcam.getName());
panel = new WebcamPanel(webcam, false);
panel.setFPSDisplayed(true);
add(panel, BorderLayout.CENTER);
pack();
Thread t = new Thread() {
#Override
public void run() {
panel.start();
}
};
t.setName("example-stopper");
t.setDaemon(true);
t.setUncaughtExceptionHandler(this);
t.start();
}
}
}
#Override
public void webcamFound(WebcamDiscoveryEvent event) {
if (picker != null) {
picker.addItem(event.getWebcam());
}
}
#Override
public void webcamGone(WebcamDiscoveryEvent event) {
if (picker != null) {
picker.removeItem(event.getWebcam());
}
}
}
Am I missing something about how this library scans for a barcode?
EDIT
Not sure this helps much..
Mar 02, 2015 10:04:34 PM sandbox_webcam.AdvancedWebcamPanelExample webcamImageObtained
SEVERE: null
com.google.zxing.NotFoundException
Throws exception here:
Result result = reader.decode(bitmap);
There is a different question which has some available answers: Android zxing NotFoundException
As James said, it is a good idea to try with bar codes on different media (paper/screen) if it is not working, and in different circumstances and lighting conditions. Particularly ensure that you have enough light, and that the FPS of the camera is high enough while it is pointed at the barcode.
For debugging, one could also convert the BinaryImage back into a viewable format and check whether the barcode is actually visible after conversion to black-and-white.
I'm writing code that implements ActionListener, so in my actionPerformed() function (which is necessary when implementing ActionListener) I have used event.getSource() in each of my if/else clauses to find which JComponent was triggered (because I have multiple JComponents in my code). But for some reason only the first if statement is triggered by its JComponent. Code is below. Thanks in advance for any help.
This is the code my question is focused on:
public void actionPerformed(ActionEvent event) {
if (event.getSource() == newProj || event.getSource() == newFlick) {
String nameProj = JOptionPane.showInputDialog("Name of your Flick:");
int option = 0;
JFileChooser dirChooser = new JFileChooser();
if (nameProj != null) {
dirChooser.setCurrentDirectory(new File("~"));
dirChooser.setDialogTitle("Choose Directory");
dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
dirChooser.setAcceptAllFileFilterUsed(false);
option = dirChooser.showOpenDialog(this);
}
if (option == JFileChooser.APPROVE_OPTION) {
File dir = dirChooser.getSelectedFile();
String dirPath = dir.getAbsolutePath();
String newDirPath = dirPath + "\\" + nameProj;
new File(newDirPath).mkdir();
File config = null;
try {
config = new File(newDirPath + "\\.flick.flick");
if (!config.exists()) {
config.createNewFile();
}
PrintWriter writer = new PrintWriter(config);
writer.append("*WARNING - TAMPERING WITH THIS DATA COULD LEAD TO PROBLEMS IN YOUR FLICK.* \n");
writer.append("Project Name: " + nameProj + "\n");
writer.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Error: " + e, null, JOptionPane.ERROR_MESSAGE);
} catch (UnsupportedEncodingException e) {
JOptionPane.showMessageDialog(null, "Error: " + e, null, JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error: " + e, null, JOptionPane.ERROR_MESSAGE);
}
dispose();
new Flick(nameProj);
} else if (event.getSource() == loadProj || event.getSource() == loadFlick) {
JOptionPane.showMessageDialog(null, "Loaded");
option = 0;
dirChooser = new JFileChooser();
dirChooser.setCurrentDirectory(new File("~"));
dirChooser.setDialogTitle("Load Flick Directory");
dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
dirChooser.setAcceptAllFileFilterUsed(false);
option = dirChooser.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
File dir = dirChooser.getSelectedFile();
File config = new File(dir + "\\.flick");
if (config.exists()) {
dispose();
new Flick(config.getName());
} else {
JOptionPane.showMessageDialog(null, "Error: Not A Flick Directory", null, JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}
Here is the rest of the code that came before the previous code:
package com.shreypandya.flickstudios;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class Home extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JLabel title = new JLabel("Welcome to FlickStudios!");
MenuBar menuBar = new MenuBar();
Menu file = new Menu("File");
MenuItem newProj = new MenuItem("New Flick");
MenuItem loadProj = new MenuItem("Load Flick");
JButton newFlick = new JButton("New Flick");
JButton loadFlick = new JButton("Load Flick");
Panel panel = new Panel();
public Home() throws FontFormatException, IOException {
super("FlickStudios");
InputStream myStream = new BufferedInputStream(new FileInputStream("Resources/OpenSans.ttf"));
Font ttf = Font.createFont(Font.TRUETYPE_FONT, myStream);
Font openSans = ttf.deriveFont(Font.PLAIN, 16);
add(panel);
panel.setLayout(new BorderLayout());
panel.add(title, BorderLayout.PAGE_START);
title.setFont(openSans.deriveFont(Font.PLAIN, 36));
panel.add(newFlick, BorderLayout.LINE_START);
newFlick.setFont(openSans);
newFlick.setFocusPainted(false);
newFlick.addActionListener(this);
panel.add(loadFlick, BorderLayout.LINE_END);
loadFlick.setFont(openSans);
loadFlick.setFocusPainted(false);
loadFlick.addActionListener(this);
setMenuBar(menuBar);
menuBar.add(file);
file.add(newProj);
newProj.addActionListener(this);
newProj.setShortcut(new MenuShortcut(KeyEvent.VK_N, false));
file.add(loadProj);
loadProj.addActionListener(this);
loadProj.setShortcut(new MenuShortcut(KeyEvent.VK_L, false));
setExtendedState(JFrame.MAXIMIZED_BOTH);
setVisible(true);
setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
}
The first if encapsulates your entire function:
public void actionPerformed(ActionEvent event) {
if (event.getSource() == newProj || event.getSource() == newFlick) {
if (nameProj != null) {
}
if (option == JFileChooser.APPROVE_OPTION) {
} else if (event.getSource() == loadProj || event.getSource() == loadFlick) {
if (option == JFileChooser.APPROVE_OPTION) {
if (config.exists()) {
} else {
}
}
}
}
}
I don't think this is as you intend, and would certainly explain why no inner blocks are being reached when the first if evaluates to false.
Your braces are mismatched.
This if (event.getSource() == newProj || event.getSource() == newFlick) { does not end until:
} else {
JOptionPane.showMessageDialog(null, "Error: Not A Flick Directory", null, JOptionPane.ERROR_MESSAGE);
}
}
}
}//HERE
Therefore, if the first if statement fails, your function ends, and never checks the other conditions.
EDIT: The code now works! Here's how I did it:
package me.nrubin29.jterminal;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
public class JTerminal extends JFrame {
private JTextPane area = new JTextPane();
private JTextField input = new JTextField("Input");
private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();
private File workingFolder = FileSystemView.getFileSystemView().getDefaultDirectory();
public JTerminal() throws IOException {
super("JTerminal");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
StyleConstants.setForeground(inputSAS, Color.GREEN);
StyleConstants.setBackground(inputSAS, Color.BLACK);
StyleConstants.setForeground(output, Color.WHITE);
StyleConstants.setBackground(output, Color.BLACK);
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.BLACK);
input.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String command = input.getText();
if (command.equals("")) return;
setTitle("JTerminal (" + command.split(" ")[0] + ")");
input.setText("");
input.setEditable(false);
write(inputSAS, command);
Process bash = new ProcessBuilder("bash").directory(workingFolder).start();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bash.getOutputStream());
outputStreamWriter.write(command);
outputStreamWriter.close();
int code = bash.waitFor();
writeStream(bash.getErrorStream(), error);
writeStream(bash.getInputStream(), output);
input.setEditable(true);
setTitle("JTerminal");
if (code == 0 && command.split(" ").length > 1) workingFolder = new File(command.split(" ")[1]);
} catch (Exception ex) { error(ex); }
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
area.setBackground(Color.black);
area.setCaretColor(Color.green);
area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
area.setEditable(false);
JScrollPane pane = new JScrollPane(area);
pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pane.setPreferredSize(new Dimension(640, 460));
input.setBackground(Color.black);
input.setForeground(Color.green);
input.setCaretColor(Color.green);
input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
input.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(pane);
add(input);
Dimension DIM = new Dimension(640, 480);
setPreferredSize(DIM);
setSize(DIM);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
pack();
setVisible(true);
input.requestFocus();
}
public static void main(String[] args) throws IOException {
new JTerminal();
}
private void write(SimpleAttributeSet attributeSet, String... lines) {
try {
if (lines.length == 0) return;
for (String line : lines) {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
}
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
}
catch (Exception e) { error(e); }
}
private void error(Exception e) {
write(error, "An error has occured: " + e.getLocalizedMessage());
e.printStackTrace(); //TODO: temp.
}
private void writeStream(InputStream s, SimpleAttributeSet color) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s));
ArrayList<String> strs = new ArrayList<String>();
while(reader.ready()) strs.add(reader.readLine());
if (strs.size() > 0) write(color, strs.toArray(new String[strs.size()]));
}
catch (Exception e) { error(e); }
}
}
I have been working on a Java terminal application. It works except that it only prints the output of the first command. Here's a picture of the GUI when I try to run ls more than once.
package me.nrubin29.jterminal;
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
public class JTerminal extends JFrame {
private JTextPane area = new JTextPane();
private JTextField input = new JTextField("Input");
private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();
public JTerminal() throws IOException {
super("JTerminal");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
StyleConstants.setForeground(inputSAS, Color.GREEN);
StyleConstants.setBackground(inputSAS, Color.BLACK);
StyleConstants.setForeground(output, Color.WHITE);
StyleConstants.setBackground(output, Color.BLACK);
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.BLACK);
final Process bash = new ProcessBuilder("/bin/bash").start();
input.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String command = input.getText();
if (command.equals("")) return;
setTitle("JTerminal (" + command.split(" ")[0] + ")");
input.setText("");
input.setEditable(false);
write(inputSAS, command);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bash.getOutputStream());
outputStreamWriter.write(command);
outputStreamWriter.close();
bash.waitFor();
writeStream(bash.getErrorStream(), error);
writeStream(bash.getInputStream(), output);
input.setEditable(true);
setTitle("JTerminal");
} catch (Exception ex) { error(ex); }
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
area.setBackground(Color.black);
area.setCaretColor(Color.green);
area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
area.setEditable(false);
JScrollPane pane = new JScrollPane(area);
pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pane.setPreferredSize(new Dimension(640, 460));
input.setBackground(Color.black);
input.setForeground(Color.green);
input.setCaretColor(Color.green);
input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
input.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(pane);
add(input);
Dimension DIM = new Dimension(640, 480);
setPreferredSize(DIM);
setSize(DIM);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
pack();
setVisible(true);
input.requestFocus();
}
public static void main(String[] args) throws IOException {
new JTerminal();
}
private void write(SimpleAttributeSet attributeSet, String... lines) {
try {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
for (String line : lines) {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
}
}
catch (Exception e) { error(e); }
}
private void error(Exception e) {
write(error, "An error has occured: " + e.getLocalizedMessage());
e.printStackTrace(); //TODO: temp.
}
private void writeStream(InputStream s, SimpleAttributeSet color) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s));
ArrayList<String> strs = new ArrayList<String>();
while(reader.ready()) strs.add(reader.readLine());
if (strs.size() > 0) write(color, strs.toArray(new String[strs.size()]));
}
catch (Exception e) { error(e); }
}
}
A Process object can be used only once, so subsequent calls to Process.waitFor() just immediately return (as the process is already terminated).
Instead you have to request a new Process each time from your ProcessBuilder.
Here is the correct code:
package me.nrubin29.jterminal;
import javax.swing.*;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.*;
import java.util.ArrayList;
public class JTerminal extends JFrame {
private JTextPane area = new JTextPane();
private JTextField input = new JTextField("Input");
private SimpleAttributeSet inputSAS = new SimpleAttributeSet(), output = new SimpleAttributeSet(), error = new SimpleAttributeSet();
public JTerminal() throws IOException {
super("JTerminal");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
StyleConstants.setForeground(inputSAS, Color.GREEN);
StyleConstants.setBackground(inputSAS, Color.BLACK);
StyleConstants.setForeground(output, Color.WHITE);
StyleConstants.setBackground(output, Color.BLACK);
StyleConstants.setForeground(error, Color.RED);
StyleConstants.setBackground(error, Color.BLACK);
final ProcessBuilder builder = new ProcessBuilder("/bin/bash");
input.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String command = input.getText();
if (command.equals("")) return;
setTitle("JTerminal (" + command.split(" ")[0] + ")");
input.setText("");
input.setEditable(false);
write(inputSAS, command);
Process bash = builder.start();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bash.getOutputStream());
outputStreamWriter.write(command);
outputStreamWriter.close();
bash.waitFor();
writeStream(bash.getErrorStream(), error);
writeStream(bash.getInputStream(), output);
input.setEditable(true);
setTitle("JTerminal");
} catch (Exception ex) { error(ex); }
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
});
area.setBackground(Color.black);
area.setCaretColor(Color.green);
area.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
area.setEditable(false);
JScrollPane pane = new JScrollPane(area);
pane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pane.setPreferredSize(new Dimension(640, 460));
input.setBackground(Color.black);
input.setForeground(Color.green);
input.setCaretColor(Color.green);
input.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
input.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(pane);
add(input);
Dimension DIM = new Dimension(640, 480);
setPreferredSize(DIM);
setSize(DIM);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
pack();
setVisible(true);
input.requestFocus();
}
public static void main(String[] args) throws IOException {
new JTerminal();
}
private void write(SimpleAttributeSet attributeSet, String... lines) {
try {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), "\n", attributeSet);
for (String line : lines) {
area.getStyledDocument().insertString(area.getStyledDocument().getLength(), line + "\n", attributeSet);
}
}
catch (Exception e) { error(e); }
}
private void error(Exception e) {
write(error, "An error has occured: " + e.getLocalizedMessage());
e.printStackTrace(); //TODO: temp.
}
private void writeStream(InputStream s, SimpleAttributeSet color) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s));
ArrayList<String> strs = new ArrayList<String>();
while(reader.ready()) strs.add(reader.readLine());
if (strs.size() > 0) write(color, strs.toArray(new String[strs.size()]));
}
catch (Exception e) { error(e); }
}
}
Once a process has exited, it can not be "read" from or "written" to.
You're code will also block on the "waitFor" method, meaning that your UI won't be updated until the process has completed running. This is really helpful...
Instead, you need to start the process and allow it to continue running, monitoring the state in the background.
Because Swing is a single threaded environment, you need to be careful about how you handle long running/blocking processes and updates to the UI.
To this end, I've used a SwingWorker to read the output of the Process in a background thread and re-sync the updates back to the Event Dispatching Thread. This allows the UI to continue running and remain responsive while the output from the running process is read in...
Also, instead of "running" a new command each time, creating a new process, you will need to write to the Process's input put stream.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTerminal {
public static void main(String[] args) {
new TestTerminal();
}
public TestTerminal() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
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 JTextArea output;
private JTextField input;
private Process process;
public TestPane() {
setLayout(new BorderLayout());
output = new JTextArea(20, 20);
input = new JTextField(10);
output.setLineWrap(false);
output.setWrapStyleWord(false);
output.setEditable(false);
output.setFocusable(false);
add(new JScrollPane(output));
add(input, BorderLayout.SOUTH);
input.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = input.getText() + "\n";
input.setText(null);
output.append("\n" + cmd + "\n\n");
if (process == null) {
ProcessBuilder pb = new ProcessBuilder("bash");
pb.directory(new File("."));
try {
process = pb.start();
InputStreamWorker isw = new InputStreamWorker(output, process.getInputStream());
isw.execute();
} catch (IOException ex) {
ex.printStackTrace();
input.setEnabled(false);
}
new Thread(new Runnable() {
#Override
public void run() {
int exit = -1;
try {
exit = process.waitFor();
} catch (InterruptedException ex) {
}
System.out.println("Exited with " + exit);
input.setEnabled(false);
}
}).start();
}
OutputStream os = process.getOutputStream();
try {
os.write(cmd.getBytes());
os.flush();
} catch (IOException ex) {
ex.printStackTrace();
input.setEnabled(false);
}
}
});
}
}
public class InputStreamWorker extends SwingWorker<Void, Character> {
private InputStream is;
private JTextArea output;
public InputStreamWorker(JTextArea output, InputStream is) {
this.is = is;
this.output = output;
}
#Override
protected void process(List<Character> chunks) {
StringBuilder sb = new StringBuilder(chunks.size());
for (Character c : chunks) {
sb.append(c);
}
output.append(sb.toString());
}
#Override
protected Void doInBackground() throws Exception {
int in = -1;
while ((in = is.read()) != -1) {
publish((char)in);
}
return null;
}
}
}
I would also recommend that you avoid KeyListener where you can. JTextField utilises a ActionListener, which will be called when ever the user presses the "action" key, what ever that might be for the given platform...