JTextArea: set text of a large file content freezes my application - java

I read a file and set the text(about 4000KB of size) into a JTextArea. It freezes my application. Following is my code snippet. I appreciate your suggestions....
public void setText(final JTextArea textArea)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
BufferedReader from = null;
try
{
from = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
System.out.println("Started..........");
textArea.read(from, file.getName());
System.out.println("Completed..........");
}
catch (Exception ex)
{
Logger.getLogger(FileTools.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
try
{
from.close();
}
catch (IOException ex)
{
Logger.getLogger(FileTools.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}

Related

Is it possible to select the file name in a JFileChooser window?

I can set the default File Name: in a JFileChooser window using:
fileChooser.setSelectedFile();
I was wondering if it is also possible to select it, so that if you want to save the file as something else you can immediately start to overtype it. Thanks for any help on this.
package filetest;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
#SuppressWarnings("serial")
class Editor {
public static class TextClass extends JTextArea {
FileClass fileClass = new FileClass();
public void setKeyboardShortcuts() {
fileClass.setKeyboardShortcuts();
}
private class FileClass {
private File directory;
private String filepath = "";
private String filename = "";
private void setKeyboardShortcuts() {
Action ctrlo = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
openFile();
} catch (UnsupportedEncodingException e1) {
}
}
};
getInputMap().put(KeyStroke.getKeyStroke("ctrl O"), "ctrlo");
getActionMap().put("ctrlo", ctrlo);
Action ctrls = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
saveFile();
} catch (UnsupportedEncodingException e1) {
}
}
};
getInputMap().put(KeyStroke.getKeyStroke("ctrl S"), "ctrls");
getActionMap().put("ctrls", ctrls);
}
private String selectFile(String fileaction) throws FileNotFoundException {
JFileChooser filechooser = new JFileChooser();
if (directory != null) {
filechooser.setCurrentDirectory(directory);
} else {
filechooser.setCurrentDirectory(new File("."));
}
filechooser.setSelectedFile(new File(filepath));
int r = 0;
if (fileaction.equals("openfile"))
r = filechooser.showDialog(new JPanel(), "Open file");
else
r = filechooser.showDialog(new JPanel(), "Save file");
if (r == JFileChooser.APPROVE_OPTION) {
try {
directory = filechooser.getSelectedFile().getParentFile();
filename = filechooser.getSelectedFile().getName();
return filename;
} catch (Exception exception) {
return "";
}
} else {
return "";
}
}
private void openFile() throws UnsupportedEncodingException {
try {
String filestr = selectFile("openfile");
if (filestr.equals(""))
return;
else
filepath = filestr;
} catch (FileNotFoundException ex) {
Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void saveFile() throws UnsupportedEncodingException {
try {
String filestr = selectFile("savefile");
if (filestr.equals(""))
return;
else
filepath = filestr;
} catch (FileNotFoundException ex) {
Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
createAndShowGui();
}
});
}
private static void createAndShowGui() {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
JTextArea textArea = new TextClass();
frame.add(textArea);
((TextClass) textArea).setKeyboardShortcuts();
frame.setVisible(true);
}
}
It does that by default on the machine I'm typing from:
package stackoverflow;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* #author ub
*/
public class StackOverflow
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif","png");
chooser.setFileFilter(filter);
chooser.setSelectedFile(new File("C:\\Users\\ub\\Pictures\\Capt.PNG"));
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION)
System.out.println("You chose to open this file: "+chooser.getSelectedFile().getName());
}
}
It's because when you first call .setSelectedFile your filepath is an empty string.
You set your filepath variable after having shown the file chooser to the user.
If you print to console the string value of filepath, right before invoking .showDialog, you should see this.
The problem seems to be caused by these lines:
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
If they are removed, the file name is highlighted as in Unai Vivi's example.

Java app can't be closed even "CLOSE ON EXIT", TCP Server

I just wanna make a Server application which gets Strings and put these into a JTextArea. There are two errors I get, even no errors are showed.
the window can't be closed although I used this statement:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If the client connects to the Server, the whole window turns black. What could be the error? Here the code:
Client:
public Main() {
super("Main");
setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/images/ic.png")));
panelFields = new JPanel();
panelFields.setLayout(new BoxLayout(panelFields,BoxLayout.X_AXIS));
panelFields2 = new JPanel();
panelFields2.setLayout(new BoxLayout(panelFields2,BoxLayout.X_AXIS));
scrollPane = new JScrollPane();
panelFields.add(scrollPane);
getContentPane().add(panelFields);
getContentPane().add(panelFields2);
getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
setSize(326, 264);
setVisible(true);
messagesArea = new JTextArea();
scrollPane.setViewportView(messagesArea);
messagesArea.setColumns(30);
messagesArea.setRows(10);
messagesArea.setEditable(false);
startServer = new JButton("Start");
startServer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
socketConnection();
startServer.setEnabled(false);
}
});
panelFields.add(startServer);
}
And the Server connection:
private void socketConnection() {
try {
serverSocket = new ServerSocket(9090);
System.out.println("Listening: " + serverSocket.getLocalPort());
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Maybe you could tell me, how I can fix those problems and also, how I can make, that the server doesn't close the socket although the client disconnects. I wanna reconnect maybe later...
You need to start your socket listener in its own thread, and you need to add a window close listener that shuts down that thread.
For example:
private ServerSocket serverSocket = null;
private boolean done = false;
private void startServer() {
Thread t = new Thread(new Runnable() {
public void Run() {
socketConnection();
});
}
t.start();
}
private void socketConnection() {
try {
serverSocket = new ServerSocket(9090);
System.out.println("Listening: " + serverSocket.getLocalPort());
while (!done) {
try {
final Socket socket = serverSocket.accept();
Thread t = new Thread(new Runnable() {
public void Run() {
handle(socket);
}
});
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void handle(Socket socket) {
if (socket == null) return;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void windowClosing(WindowEvent e) {
done = true;
socketServer.close();
}
Your button click listener should call startServer(), then your window close function would set done = true and call socketServer.close().
Now you have one thread for the UI, one thread for the socket server, and one thread for each connection to the server.

ftpClient wont upload,what am I missing?

Yeah, so I am using this code but whenever I run it, it doesnt upload anything. I have a similar code in another program the works perfect. What have I missed?
public void upload(){
new Thread(new Runnable() {
public void run() {
if (Looper.myLooper() == null)
{
Looper.prepare();
}
FTPClient ftpClient = new FTPClient();
FileInputStream inputStream = null;
int Upload = sharedPreferences.getInt("Upload", 1);
if (Upload == 1) {
try {
ftpClient.connect(InetAddress.getByName("XXX.net"));
ftpClient.login("XXX", "XXX");
ftpClient.changeWorkingDirectory("/public_html/Images/Cross");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
File file = new File(getApplicationInfo().dataDir + "/files/" + "temp" + ".jpg");
inputStream = new FileInputStream(file);
ftpClient.storeFile("temporary.jpg", inputStream);
file.delete();
ftpClient.logout();
ftpClient.disconnect();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
...
}

Stop process of webcam in java netbeans

I want to capture an image using an available webcam. I have successfully accessed the webcam but I couldn't stop the webcam process. I want to stop the webcam process using a stop button. How can I accomplish this? This my code:
public Component componen() throws IOException , NoPlayerException, CannotRealizeException
{
Component comp_video;
MediaLocator loo = new MediaLocator("vfw://0");
try {
broadcast = Manager.createRealizedPlayer(loo);
} catch (IOException ex) {
Logger.getLogger(CapturImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoPlayerException ex) {
Logger.getLogger(CapturImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (CannotRealizeException ex) {
Logger.getLogger(CapturImage.class.getName()).log(Level.SEVERE, null, ex);
}
broadcast.start();
if((comp_video = broadcast.getVisualComponent()) != null)
{
comp_video.setSize(321,228);
return comp_video;
}
else
{
return null;
}
}
public void capture_image()
{
FrameGrabbingControl grab = (FrameGrabbingControl) broadcast.getControl("javax.media.control.FrameGrabbingControl");
javax.media.Buffer buff = grab.grabFrame();
BufferToImage buffer =new BufferToImage((VideoFormat) buff.getFormat());
img = buffer.createImage(buff);
}
public void set_iamge_label(final JLabel lb)
{
Thread web = new Thread(){
public void run(){
capture_image();
Rectangle rect = lb.getBounds();
Image img1 = img.getScaledInstance(rect.width,rect.height,Image.SCALE_DEFAULT);
lb.setIcon(new javax.swing.ImageIcon(img1));
}
};
web.start();
}

indexoutofboundsexception by sending pictures over Socket

I want to make a little programm that makes a live-stream for Desktop.
It should be so that you send pictures to an echo-server and he response it to the clients.
There you get be draw the Images. Side by Side. And so it is like a movie(or something like that).
But I always get an indexoutofboundsexception. Where is the error or how can I improve my program.
The ImageIO.write lines thows the Error
//Client Main
public class Main {
public static void main(String[] args) {
Frame frm = new Frame();
Frame.Client client;
frm.setLayout(null);
frm.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
frm.setResizable(false);
frm.setSize(1600,900);
frm.setVisible(true);
}
}
// get and send the Desktopimage
public class desktopCapture {
Robot robo;
BufferedImage screenImage;
Rectangle bounding;
public desktopCapture() {
try {
bounding = new Rectangle(0,0,1600,900);
robo = new Robot();
} catch (AWTException e) {e.printStackTrace();}
}
public void sendScreenCapture(Socket client) {
screenImage = robo.createScreenCapture(bounding);
try {
ImageIO.write(screenImage, "png", client.getOutputStream());
} catch (IOException e) {e.printStackTrace();}
}
}
// in Frame two function for actionListener Objects, so I can say who streams his Desktop and which get only the Images to.
public void readImage() {
while(true) {
try {
while((screenImage = ImageIO.read(in)) != null){
repaintScreen();
}
} catch (IOException e) {e.printStackTrace();}
}
}
public void sendImage() {
try {
while(true){
dC.sendScreenCapture(client);
System.out.println("read1");
while((screenImage = ImageIO.read(in)) != null){
System.out.println("read2");
ImageIO.write(screenImage, "png", new File("image1.png"));
Thread.sleep(250);
}
repaintScreen();
screenImage = null;
}
} catch (IOException | InterruptedException e) {e.printStackTrace();}
}
}
}
//Thread for a Client
public class handler implements Runnable {
Socket client;
OutputStream out;
InputStream in;
PrintWriter writer;
BufferedImage image;
public handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while(true) {
System.out.println("write1");
while((image = ImageIO.read(in)) != null){
System.out.println("write2");
for(int i = 1;i <= Server.connectionArray.size();i++){
Socket TEMP_SOCK = (Socket)Server.connectionArray.get(i-1);
out = TEMP_SOCK.getOutputStream();
writer = new PrintWriter(out);
ImageIO.write(image, "png", TEMP_SOCK.getOutputStream());
System.out.println("write3");
}
image = null;
}
}
} catch (IOException e) {e.printStackTrace();}
}
}
I would change your for loop to:
int count = Server.connectionArray.size()
int index = count - 1;
for(int i = 0;i < count; i++){
Socket TEMP_SOCK = (Socket)Server.connectionArray.get(index);
out = TEMP_SOCK.getOutputStream();
writer = new PrintWriter(out);
ImageIO.write(image, "png", TEMP_SOCK.getOutputStream());
System.out.println("write3");
}

Categories