Trying to read a text file into a JTextArea - java

I'm trying to open a text file and add its value into a String variable to then set in a JTextArea. No matter what I do it always returns nothing in the textarea.
I want it change the text like it does when you hit the clear button, but I want to change it to what's in the Test.txt file it makes.
package texteditor;
import java.awt.FlowLayout;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class GUI extends JFrame {
//GUI Variables
private JButton save;
private JButton clear;
private JButton copy;
private JButton paste;
private JButton open;
private JTextArea textField;
private StringSelection stringSelection;
private Clipboard clipboard;
String textFieldWritable;
public GUI() {
super("Text Editor");
//Sets Layout
setLayout(new FlowLayout());
save = new JButton("Save");
add(save);
clear = new JButton("Clear");
add(clear);
open = new JButton("Open");
add(open);
textField = new JTextArea(10, 35);
add(textField);
handler handle = new handler();
save.addActionListener(handle);
clear.addActionListener(handle);
}
private class handler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == save) {
textFieldWritable = String.format("%s", textField.getText());
try {
FileWriter fileWrite = new FileWriter("Text.txt");
PrintWriter printWrite = new PrintWriter(fileWrite);
printWrite.println(textFieldWritable);
printWrite.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Error, File Already Exists!", "Error",
JOptionPane.ERROR_MESSAGE);
}
} else if (event.getSource() == clear) {
textField.setText("");
} else if (event.getSource() == open) {
try {
FileReader fileReader = new FileReader("Text.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputFile = "";
String textFieldReadable = bufferedReader.readLine();
while (textFieldReadable != null) {
inputFile += textFieldReadable;
textFieldReadable = bufferedReader.readLine();
}
System.out.println("inputFile");
} catch (FileNotFoundException ex) {
System.out.println("no such file exists");
} catch (IOException ex) {
System.out.println("unkownerror");
}
}
}
}
}

To me, it looks like you never set the text you've read to the text area.
try {
FileReader fileReader = new FileReader("Text.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String inputFile = "";
String textFieldReadable = bufferedReader.readLine();
while (textFieldReadable != null){
inputFile += textFieldReadable;
textFieldReadable = bufferedReader.readLine();
}
System.out.println("inputFile");
// Opps //
textField.setText(inputFile);
}
catch (FileNotFoundException ex) {
System.out.println("no such file exists");
}
catch (IOException ex) {
System.out.println("unkownerror");
}
Personally, I'd just use the functionality provide by JTextComponent and pass it a Reader and allow it to read itself.
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.FileReader;
import java.io.Reader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TextAreaReadTest {
public static void main(String[] args) {
new TextAreaReadTest();
}
public TextAreaReadTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
public TestPane() {
setLayout(new BorderLayout());
textArea = new JTextArea(10, 80);
add(new JScrollPane(textArea));
JButton read = new JButton("Read");
read.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Reader reader = null;
try {
reader = new FileReader(new File("D:/SWANH.txt"));
textArea.read(reader, "The force is strong with this one");
} catch (Exception exp) {
exp.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception exp) {
}
}
}
});
add(read, BorderLayout.SOUTH);
}
}
}

This Code Worked for me
public DisplayText() throws IOException {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textArea.setBounds(15, 13, 424, 210);
textArea.setEditable(false);
contentPane.add(textArea);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setBounds(12, 12, 424, 185);
contentPane.add(scrollPane);
JButton btnPatchDetails = new JButton("Details");
btnPatchDetails.setBounds(135, 234, 137, 25);
contentPane.add(btnPatchDetails);
btnPatchDetails.addActionListener(this);
btnPatchDetails.setActionCommand("Patch Details");
JButton btnNext = new JButton("Next");
btnNext.setBounds(314, 234, 107, 25);
contentPane.add(btnNext);
JLabel lblDependancyPatchAvailable = new JLabel("Dependancy Patch Available : ");
lblDependancyPatchAvailable.setBounds(22, 209, 220, 15);
contentPane.add(lblDependancyPatchAvailable);
lblAvailability.setBounds(254, 209, 61, 15);
contentPane.add(lblAvailability);
}
public void actionPerformed(ActionEvent e) {
if ("Patch Details".equals(e.getActionCommand())) {
BufferedReader reader = null;
JarFile jarFile = null;
try {
String inputFile = "readMe/tempReadme.txt";
String write;
jarFile = new JarFile(inputJar);
JarEntry entry = jarFile.getJarEntry(inputFile);
reader = new BufferedReader(new InputStreamReader(jarFile.getInputStream(entry)));
String line,searchStr = "Patch Details",endStr = "Problem:";
boolean readFlag = false;
boolean writeFlag = false;
while ((line = reader.readLine()) != null) {
if (line.trim().contains(searchStr)) {
readFlag = true;
}
if (line.trim().equals(endStr)) {
break;
}
if (readFlag) {
StringTokenizer tempTokenizer = new StringTokenizer(line,"");
while (tempTokenizer.hasMoreElements()) {
write = tempTokenizer.nextToken();
textArea.append(write + "\n");
}
}
writeFlag = true;
}
if(writeFlag){
lblAvailability.setText("YES");
} else {
lblAvailability.setText("");
}
lblAvailability.getText();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
jarFile.close();
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

Related

Choosing a txt file with JFileChooser and making it appear on a JTextField just won't work

When I press open another window appears with JFileChooser to select the file again, and when I try to select the file again it just gives me "open command canceled by user" message. The program stops working and ends with an unknown exception.
Here is my code:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileC extends JFrame {
File file;
JFileChooser chooser = new JFileChooser();
JTextArea TArea = new JTextArea();
public FileC()
{
super.setLayout(new FlowLayout());
super.add(chooser);
super.add(TArea);
FileNameExtensionFilter filter = new FileNameExtensionFilter ( "text files " , "txt");
chooser.setFileFilter(filter);
ActionHandler handler = new ActionHandler ();
chooser.addActionListener(handler);
}
private class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent e) {
int returnVal = chooser.showOpenDialog(FileC.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null,"Open command cancelled by user.");
}
try {
BufferedReader in = new BufferedReader ( new FileReader (file));
String s = in.readLine();
while (s != null)
{
TArea.append(s);
s = in.readLine();
}
}catch (FileNotFoundException z){ JOptionPane.showMessageDialog(null, "file not found"); }
catch (IOException z) { z.printStackTrace(); }
}
}
}
the new codes
public class FileC extends JFrame {
File file;
JFileChooser chooser = new JFileChooser();
JTextArea TArea = new JTextArea();
JButton b = new JButton("open");
public FileC()
{
TArea.setRows(10);
TArea.setColumns(20);
super.setLayout(new FlowLayout());
super.add(TArea);
super.add(b);
FileNameExtensionFilter filter = new FileNameExtensionFilter ( "text files " , "txt");
chooser.setFileFilter(filter);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
chooser.showOpenDialog(FileC.this);
}
});
chooser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int returnVal = chooser.showOpenDialog(FileC.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
} else {
JOptionPane.showMessageDialog(null,"Open command cancelled by user.");
}
try {
BufferedReader in = new BufferedReader ( new FileReader (file));
String s = in.readLine();
while (s != null)
{
TArea.append(s);
s = in.readLine();
}
in.close();
}catch (FileNotFoundException z){ JOptionPane.showMessageDialog(null, "file not found"); }
catch (IOException z) { z.printStackTrace(); }
}
});
}
}
As an example...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;
public class FileChooserExample {
public static void main(String[] args) {
new FileChooserExample();
}
public FileChooserExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton open;
private JTextArea textArea;
private JFileChooser chooser;
public TestPane() {
setLayout(new BorderLayout());
open = new JButton("Open");
textArea = new JTextArea(20, 40);
add(new JScrollPane(textArea));
add(open, BorderLayout.SOUTH);
open.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (chooser == null) {
chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
chooser.addChoosableFileFilter(new FileFilter() {
#Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
}
#Override
public String getDescription() {
return "Text Files (*.txt)";
}
});
}
switch (chooser.showOpenDialog(TestPane.this)) {
case JFileChooser.APPROVE_OPTION:
try (BufferedReader br = new BufferedReader(new FileReader(chooser.getSelectedFile()))) {
textArea.setText(null);
String text = null;
while ((text = br.readLine()) != null) {
textArea.append(text);
textArea.append("\n");
}
textArea.setCaretPosition(0);
} catch (IOException exp) {
exp.printStackTrace();
JOptionPane.showMessageDialog(TestPane.this, "Failed to read file", "Error", JOptionPane.ERROR_MESSAGE);
}
break;
}
}
});
}
}
}
Take a look at How to use file choosers for more details

Java Terminal Only Printing Output From First Command

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...

Can't access variables for SwingWorker

I am trying to get this SwingWorker to function correctly. However,the variables that need to be accessed seem to be not global. What do I do? I tried adding static but it creates more errors and complications later about accessing static from non static. The variables that are not working in the SwingWorker are the LOCAL_FILE and URL_LOCATION variables.
package professorphysinstall;
//Imports
import com.sun.jmx.snmp.tasks.Task;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingWorker;
import javax.tools.FileObject;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
public class ProfessorPhysInstall {
/**
* #param args the command line arguments
*/
static class Global {
public String location;
}
public static void main(String[] args) {
// TODO code application logic here
//Variables
final JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
final JPanel cards = new JPanel(new CardLayout());
final CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(TextPaneScreen1);
JTextArea TextAreaScreen1 = new JTextArea();
JScrollPane sbrText = new JScrollPane(TextAreaScreen1);
TextAreaScreen1.setRows(15);
TextAreaScreen1.setColumns(40);
TextAreaScreen1.setEditable(false);
TextAreaScreen1.setText("stuff");
TextAreaScreen1.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextAreaScreen1.setMargin(new Insets(4,4,4,4));
screen1.add(sbrText);
final JCheckBox Acceptance = new JCheckBox();
Acceptance.setText("I Accept The EULA Agreenment.");
screen1.add(Acceptance);
final JButton NextScreen1 = new JButton();
NextScreen1.setText("Next");
NextScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.next(cards);
}
});
screen1.add(NextScreen1);
JButton CancelScreen1 = new JButton();
CancelScreen1.setText("Cancel");
CancelScreen1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen1.add(CancelScreen1);
cards.add(screen1);
//Screen2
final JPanel screen2 = new JPanel();
JPanel screen3 = new JPanel();
JTextPane TextPaneScreen2 = new JTextPane();
TextPaneScreen2.setEditable(false);
TextPaneScreen2.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen2.setText("Please select the Future Retro Gaming Launcher. Professor Phys will be installed there.");
TextPaneScreen2.setSize(358, 48);
TextPaneScreen2.setLocation(0, 0);
TextPaneScreen2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen2.setMargin(new Insets(4,4,4,4));
screen2.add(TextPaneScreen2);
JLabel screen2instructions = new JLabel();
screen2instructions.setText("Launcher Location: ");
screen2.add(screen2instructions);
final JTextField folderlocation = new JTextField(25);
screen2.add(folderlocation);
final JButton Browse = new JButton();
final JLabel filelocation = new JLabel();
final JLabel filename = new JLabel();
Browse.setText("Browse");
Browse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Create a file chooser
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(screen2);
folderlocation.setText(fc.getSelectedFile().getAbsolutePath());
filelocation.setText(fc.getCurrentDirectory().getAbsolutePath());
filename.setText(fc.getSelectedFile().getName());
}
});
screen2.add(filelocation);
screen2.add(filename);
screen3.add(filelocation);
filelocation.setVisible(false);
filename.setVisible(false);
screen2.add(Browse);
final JButton BackScreen2 = new JButton();
BackScreen2.setText("Back");
BackScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen2.add(BackScreen2);
final JButton NextScreen2 = new JButton();
NextScreen2.setText("Next");
NextScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//Checking Code
String correctname = "Future_Retro_Gaming_Launcher.jar";
if (filename.getText().equals(correctname))
{
cl.next(cards);
}
else
{
JFrame popup = new JFrame();
popup.setBounds(0, 0, 380, 100);
Label error = new Label();
error.setText("Sorry you must select your Future_Retro_Gaming_Launcher.jar");
popup.add(error);
popup.show();
}
}
});
screen2.add(NextScreen2);
JButton CancelScreen2 = new JButton();
CancelScreen2.setText("Cancel");
CancelScreen2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen2.add(CancelScreen2);
cards.add(screen2);
//Screen3
JTextPane TextPaneScreen3 = new JTextPane();
TextPaneScreen3.setEditable(false);
TextPaneScreen3.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen3.setText("Professor Phys will be instaleld in the directory you have chosen. Please make sure\nyour launcher is in that folder or the game will not work.\nClick next to begin the install process.");
TextPaneScreen3.setSize(358, 48);
TextPaneScreen3.setLocation(0, 0);
TextPaneScreen3.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5, 5, 5, 5)));
TextPaneScreen3.setMargin(new Insets(4,4,4,4));
screen3.add(TextPaneScreen3);
final JButton BackScreen3 = new JButton();
BackScreen3.setText("Back");
BackScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(Acceptance.isSelected())
cl.previous(cards);
}
});
screen3.add(BackScreen2);
final JButton NextScreen3 = new JButton();
NextScreen3.setText("Next");
NextScreen3.addActionListener(new ActionListener() {
#Override
#SuppressWarnings({"null", "ConstantConditions"})
public void actionPerformed(ActionEvent ae) {
//ProgressBar/Install
System.out.println("FILELOCATION:\n----------");
System.out.println(filelocation.getText());
String URL_LOCATION = "https://dl.dropboxusercontent.com/u/10429987/Future%20Retro%20Gaming/ProfessorPhys.iso";
String LOCAL_FILE = (filelocation.getText() + "\\ProfessorPhys\\");
System.out.println("LOCALFILE:\n-------");
System.out.println(LOCAL_FILE);
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(LOCAL_FILE+"professorphys.iso", "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
// Getting simple interface of the archive inArchive
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
System.out.println(" Hash | Size | Filename");
System.out.println("----------+------------+---------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
ExtractOperationResult result;
final long[] sizeArray = new long[1];
result = item.extractSlow(new ISequentialOutStream() {
public int write(byte[] data) throws SevenZipException {
hash[0] ^= Arrays.hashCode(data); // Consume data
sizeArray[0] += data.length;
return data.length; // Return amount of consumed data
}
});
if (result == ExtractOperationResult.OK) {
System.out.println(String.format("%9X | %10s | %s", //
hash[0], sizeArray[0], item.getPath()));
} else {
System.err.println("Error extracting item: " + result);
}
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
});
screen3.add(NextScreen3);
JButton CancelScreen3 = new JButton();
CancelScreen3.setText("Cancel");
CancelScreen3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
screen3.add(CancelScreen3);
System.out.println("Done");
JProgressBar progress = new JProgressBar();
progress.setIndeterminate(true);
screen3.add(progress);
cards.add(screen3);
mainframe.add(cards);
mainframe.setVisible(true);
}
}
class DownloadWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(URL_LOCATION);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(LOCAL_FILE+"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Your program is mostly a huge static main method. You're kind of getting the cart in front of the horse trying to do advanced programming such as with SwingWorker before first creating clean OOP code. In other words -- start over and do it right. Then the connections between classes will be much more natural and it will be much easier to get things to work right. The main method should only concern itself with starting the Swing event thread, creating a GUI object in that thread, and displaying it. Everything else should be in classes that create objects.
Also, on a more practical level, you have yet to tell us what variables are causing you trouble or what errors you might be seeing. Also, where are you trying to create and execute the SwingWorker?
Edit
One tip that will likely help: Give your SwingWorker class a constructor, and pass important parameters into your SwingWorker object via constructor parameters. Then use those parameters to initialize class fields that will be used in the SwingWorker's doInBackground method.
e.g.,
class DownloadWorker extends SwingWorker<Integer, Integer>
{
private String urlLocation;
private String localFile;
public DownLoadWorker(String urlLocation, String localFile) {
this.urlLocation = urlLocation;
this.localFile = localFile;
}
protected Integer doInBackground() throws Exception
{
try {
URL website = new URL(urlLocation);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(localFile +"\\ProfessorPhys.iso\\");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
System.out.println("--------\nDone Downloading\n---------");
} catch (Exception e) {
System.err.println(e);
}
return 42;
}
protected void done()
{
try
{
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Chat program freezes JFrame

I'm writing a simply chat client and am moving it over to a nice GUI. The constructor for the server side (client side is android) contains a list that's in the JFrame, and the first part of the server runs, but then the entire frame locks up. Does anyone see the issue? Sorry for the relatively disorganized, not cleanly commented code...
Server:
import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class ChatServer {
private final int CHAT_PORT = 4453;
ServerSocket sSocket;
Socket cSocket;
PrintWriter pWriter;
BufferedReader bReader;
InetAddress localAddr;
List messageList;
public ChatServer(List entList)
{
messageList = entList;
}
public synchronized void run()
{
messageList.add("Chat Server Starting...");
try {
localAddr = InetAddress.getLocalHost();
} catch (UnknownHostException e1) {
messageList.add("InnetAddress error");
}
while(true)
{
try {
sSocket = new ServerSocket(CHAT_PORT);
sSocket.setReuseAddress(true);
messageList.add("Server has IP:" + localAddr.getHostAddress());
messageList.add("Server has hostname:" + localAddr.getHostName());
messageList.add("Server has port:" + CHAT_PORT);
} catch (IOException e) {
//ERRORS
if(cSocket.isConnected())
{
messageList.add("User disconnected\n");
try {
cSocket.close();
} catch (IOException e1) {
messageList.add("Error closing client socket");
}
}
else
{
messageList.add("ERROR CREATING SOCKET\n");
}
}
try {
cSocket = sSocket.accept();
cSocket.setReuseAddress(true);
messageList.add("INFO: socket connected");
} catch (IOException e) {
messageList.add("Client Socket Error");
System.exit(-1);
}
try {
pWriter = new PrintWriter(cSocket.getOutputStream(), true);
messageList.add("INFO: Print writer opened");
} catch (IOException e) {
messageList.add("PrintWriter error");
}
try {
bReader = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
messageList.add("INFO: buffered reader opened");
} catch (IOException e) {
messageList.add("BufferedReader error");
}
String inputLine;
try {
while((inputLine = bReader.readLine()) != null)
{
messageList.add(inputLine);
if(inputLine.equals("close"))
{
close();
}
}
} catch (IOException e) {
messageList.add("Buffered Reader error");
}
}
}
public synchronized void close()
{
messageList.add("****Server closing****");
try {
sSocket.close();
} catch (IOException e) {
messageList.add("Error closing server socket");
}
try {
cSocket.close();
} catch (IOException e) {
messageList.add("Error closing client socket");
}
pWriter.close();
try {
bReader.close();
} catch (IOException e) {
messageList.add("Error closing buffered reader");
}
messageList.add("****It's been fun, but I've got to go.****\n****Server has shut down.****");
System.exit(0);
}
}
GUI:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.List;
import java.awt.Toolkit;
#SuppressWarnings("serial")
public class ClientGUI extends JFrame {
private JPanel contentPane;
private JTextField txtEnterTextHere;
private JMenuBar menuBar;
private List messageList;
private JMenu mnOptions;
private JMenu mnHelp;
private JMenuItem mntmStartServer;
private JMenuItem mntmStopServer;
private JMenuItem mntmConnectionInfo;
private JMenuItem mntmEmailDeveloper;
private static String userName;
private ChatServer cServer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClientGUI frame = new ClientGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ClientGUI() {
setTitle("Ben's Chat Client");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?");
}
});
mnFile.add(mntmExit);
mnOptions = new JMenu("Options");
menuBar.add(mnOptions);
mntmStartServer = new JMenuItem("Start Server");
mntmStartServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ChatServer cServer = new ChatServer(messageList);
cServer.run();
}
});
mnOptions.add(mntmStartServer);
mntmStopServer = new JMenuItem("Stop Server");
mnOptions.add(mntmStopServer);
mntmConnectionInfo = new JMenuItem("Connection Info");
mnOptions.add(mntmConnectionInfo);
mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
mntmEmailDeveloper = new JMenuItem("Email Developer");
mnHelp.add(mntmEmailDeveloper);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
txtEnterTextHere = new JTextField();
txtEnterTextHere.setBounds(10, 220, 334, 20);
txtEnterTextHere.setText("Enter text here...");
contentPane.add(txtEnterTextHere);
txtEnterTextHere.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
messageList.add(userName + ": " + txtEnterTextHere.getText().toString());
}
});
messageList = new List();
btnSend.setBounds(349, 219, 85, 23);
contentPane.add(btnSend);
messageList.setBounds(10, 10, 424, 204);
contentPane.add(messageList);
}
public static String getUsername()
{
return userName;
}
public static void setUsername(String entName)
{
userName = entName;
}
}
Thanks!
It looks like you're starting the server on the Swing thread (see: The Event Dispatch Thread). As soon as you call cServer.run(); in the ActionListener, you are blocking the EDT from doing anything else (such as updating your JFrame and responding to events). Start your server in a background thread instead:
new Thread(new Runnable()
{
#Override
public void run()
{
// start your server
}
}).start();

In Attempt to Create a JFileChooser--public variables?

In my previous question, I've stated I'm somewhat new to Java's JFrame features.
I'm trying to create a JFileChooser that will get a directory in which a file named setup.exe will be saved. That's irrelevant, though.
I'm receiving this error:
C:\Users\b\Downloads\files\thankyousanta>javac UpdateMechanism.java
UpdateMechanism.java:31: error: <identifier> expected
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
^
UpdateMechanism.java:31: error: <identifier> expected
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
^
UpdateMechanism.java:33: error: <identifier> expected
openButton.addActionListener(openButton);
^
UpdateMechanism.java:33: error: <identifier> expected
openButton.addActionListener(openButton);
^
4 errors
...for this code:
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
import javax.swing.filechooser.*;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFileChooser;
import javax.swing.BoxLayout;
import javax.Swing.SwingUtilities;
import javax.swing.BorderFactory;
import javax.swing.border.EmptyBorder;
import javax.imageio.ImageIO;
public class definitiveVoid extends JFileChooser implements ActionListener {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
JButton openButton = new JButton("The update is waiting on you.");
openButton.addActionListener(openButton);
}
public class UpdateMechanism extends JPanel
implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(UpdateMechanism.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
} else {
// operation cancelled
}
} else {
// destroy life
}
}
private static String readURL(String targetURL) {
String returnish = "";
try {
URL tempURL = new URL(targetURL);
Scanner s = new Scanner(tempURL.openStream());
while (s.hasNextLine()) {
returnish = returnish+s.nextLine();
}
} catch (IOException e) {
System.out.println(e);
}
return returnish;
}
private static String readFile(String targetFile) {
String returnString = "";
try {
File tempFile = new File(targetFile);
Scanner s = new Scanner(tempFile);
while (s.hasNextLine()) {
returnString = returnString + s.nextLine();
}
} catch(IOException e) {
// !
System.out.println(e);
}
return returnString;
}
private static void showGUI() {
JFrame frame = new JFrame("The Neverhood Restoration Project");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(1024, 600));
frame.setExtendedState(frame.MAXIMIZED_BOTH);
frame.getContentPane().setBackground(new Color(0xA64343));
File fileCheck = new File("C:/Program Files (x86)");
String returnString = null;
String rootDirectory = null;
if (fileCheck.exists()) {
rootDirectory = "C:/Program Files (x86)/DreamWorks Interactive";
String checkFile = rootDirectory+"/Neverhood/version.txt";
File tempFile = new File(checkFile);
if (tempFile.exists()) {
returnString = readFile(checkFile);
} else {
returnString = "It appears you do not have the Neverhood Restoration Project installed, or you are using an earlier version.";
}
} else {
rootDirectory = "C:/Program Files/DreamWorks Interactive";
String checkFile = rootDirectory+"/Neverhood/version.txt";
File tempFile = new File(checkFile);
if (tempFile.exists()) {
returnString = readFile(checkFile);
} else {
returnString = "It appears you do not have the Neverhood Restoration Project installed, or you are using an earlier version.";
}
}
if (returnString.equals(readURL("http://theneverhood.sourceforge.net/version.txt"))) {
returnString = "You are updated to the recent version!";
} else {
returnString = "It appears you're not updated.";
}
JLabel headerLabel = new JLabel("The Neverhood Restoration Project");
headerLabel.setHorizontalAlignment(JLabel.CENTER);
JPanel heapPanel = new JPanel();
heapPanel.setLayout(new BoxLayout(heapPanel, BoxLayout.PAGE_AXIS));
heapPanel.setPreferredSize(new Dimension(500, heapPanel.getPreferredSize().height));
JTextArea heapLabel = new JTextArea(50, 50);
heapLabel.setLineWrap(true);
heapLabel.setWrapStyleWord(true);
heapLabel.setEditable(false);
heapLabel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
heapLabel.setFont(new Font("Serif", Font.PLAIN, 14));
heapLabel.append("Current version: "+readURL("http://theneverhood.sourceforge.net/prettyversion.txt")+".\nInstalled version: "+readFile(rootDirectory+"/Neverhood/prettyversion.txt")+".\n"+returnString+"\n" +
"You can read the full version of the document to the left at http://theneverhood.sourceforge.net."
+ "\nBelow is the download button. Just click, choose your directory to save setup.exe in and enjoy!");
heapPanel.add(heapLabel);
try {
Font sFont = Font.createFont(Font.TRUETYPE_FONT, new File("DUGFB___.TTF"));
sFont = sFont.deriveFont(Font.PLAIN, 48);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(sFont);
headerLabel.setFont(sFont);
} catch (FontFormatException | IOException e) {
System.out.println(e);
}
BufferedImage icoImage = null;
try {
icoImage = ImageIO.read(
frame.getClass().getResource("/nhood.bmp"));
} catch (IOException e) {
System.out.println(e);
}
frame.setIconImage(icoImage);
JEditorPane updateLog = new JEditorPane();
JScrollPane scrollPane = new JScrollPane(updateLog);
updateLog.setEditable(false);
try {
updateLog.setPage("http://theneverhood.sourceforge.net/");
} catch (IOException e) {
updateLog.setContentType("text/html");
updateLog.setText("<html>The application could not load the webpage.</html>");
}
frame.add(headerLabel, BorderLayout.NORTH);
frame.add(scrollPane);
frame.add(heapPanel, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showGUI();
}
});
}
}
In Java, public classes must be defined in their own file, having the same name (with a .java suffix) as the class name.
You defined a public class named definitiveVoid in the file UpdateMechanism.java. And you tried to put code directly in this class, outside of any method. That isn't valid Java.
Swing is hard and complex. Don't try to use it before knowing the basics of Java.
Moreover, classes, by convention, start with an uppercase letter in Java.

Categories