I need to have all the system.out.println statements to be displayed on the JTextArea when the copying is in progress. I tried giving ta.append instead of the println statements but it won't desplay. Please let me know how should I go about doing this.
public class copy {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Copy c = new Copy();
c.setTitle("Copy folders");
c.setVisible(true);
}
});
JPanel jp = new JPanel();
TextArea ta = new JTextArea(5, 50);
ta.setEditable(false);
DefaultCaret caret = (DefaultCaret) ta.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane scrollPane = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(6, 625, 1035, 296);
jp.add(scrollPane); //Adding to JPanel
}
public Copy() {
build();
}
public void build() {
String source = "\\hostname\\d$\\somedirecotry";
String detination = "\\C:\\foldername";
File s = new File(source);
File s2 = new File(detination);
if (!s.exists()) {
System.out.println("Directory does not exist.");
} else if (!s2.exists()) {
System.out.println("Directory is not accessible or Server is down");
} else {
try {
copyFolder(s, s2);
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
System.out.println("Done");
}
public static void copyFolder(File src, File dest)
throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists()) {
dest.mkdir();
System.out.println("Directory copied from " + src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
File srcFile = new File(src, file);
File destFile = new File(dest, file);
copyFolder(srcFile, destFile);
}
} else {
//if file, then copy it
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
Swing is an event driven environment, this includes, but is not limited to, keyboard, mouse and paint events.
These events are delivered by the Event Dispatching Thread. Any operation (such as, but not limited to, loops, I/O or Thread#sleep) that blocks this thread will prevent (amongst other things) paint requests from begin processed. This will make your application stop responding to key and mouse events as well as make it look like its hung.
The easiest fix to your problem is to move the physical copy process to a separate thread. This is most easily accomplished by using a SwingWorker.
Take a look at Concurrency in Swing, in particular The Event Dispatch Thread and Worker Threads and SwingWorker
Examples can be found
JTextArea appending problems
SwingWorker with FileReader
JProgressBar won't update
Related
I need hlep with figuring out how to wrap the text in the JavaFX TextField object.
So my code gets a file name from the user, opens the file by pasting the contents of the text file into the text field. Then the user can edit the text and save it into the same file.
My code does all of the above so that's not what I need help with. The JavaFX TextField object does not seem to have a way to wrap the text in the text box. It ends up looking like this:
Alt Image Link: https://drive.google.com/open?id=1q2yU5ox6WA5EwS3YSxaKoqUDpCxpbPmu
I want to wrap the text for obvious reasons. Below is my code (minus the import statements)
public class TextEditor extends Application
{
private Button button = new Button();
private TextField text = new TextField();
private Label label = new Label("Enter filename:");
private String filename = "";
String filetext = "";
Scanner file = new Scanner("");
PrintWriter pw = null;
FileOutputStream fos = null;
#Override
public void start(Stage primaryStage) throws Exception
{
GridPane myPane = new GridPane();
myPane.setHgap(10);
myPane.setVgap(10);
Scene myScene = new Scene(myPane, 500, 500);
primaryStage.setScene(myScene);
primaryStage.show();
primaryStage.setTitle("Find File");
myPane.setAlignment(Pos.BASELINE_CENTER);
label.setAlignment(Pos.BASELINE_CENTER);
myPane.add(label, 0, 0, 3, 1);
text.setAlignment(Pos.TOP_LEFT);
text.setPrefWidth(480);
text.setPrefHeight(400);
myPane.add(text, 0, 1);
button = new Button("Submit Filename");
button.setPrefSize(180, 50);
button.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
if(button.getText().equals("Save Changes"))
{
try
{
fos = new FileOutputStream(filename);
pw = new PrintWriter(fos);
System.out.println("Saving changes in " + filename);
pw.println(text.getText());
pw.close();
primaryStage.close();
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(button.getText().equals("Submit Filename"))
{
filename = text.getText();
try
{
file = new Scanner(new FileInputStream(new File(filename)));
while(file.hasNextLine())
{
String line = file.nextLine();
System.out.println(line);
filetext += line + "\n";
}
System.out.println("File text: " + filetext);
text.setText(filetext);
button.setText("Save Changes");
}
catch(FileNotFoundException exc)
{
System.out.println("Cannot find file. Program aborted.");
primaryStage.close();
}
}
}
});
myPane.add(button, 0, 2);
}
public static void main(String[] args)
{
Application.launch(args);
}
}
Would love some assistance getting the text to wrap. Do I need to not use a JavaFX TextField? Should I use something else?
Thanks in advance!
EDIT
SOLUTION FOUND
I changed the TextField text to a TextArea, removed the text.setAlignment(Pos.TOP_LEFT) line and added a text.setWrapText(true) (as suggested below) and now the program works great. Thanks Fabian and Zephyr!
Here's a screenshot application. Compiled with 1.8 JDK, works perfectly well in 64 bit systems, but lags and hangs in two iterations in 32 bit systems.
Basically this application takes a screenshot using robot class, takes the file name from user which is a URL. Truncates and removes all illegal characters from it and saves it using a save as dialog box with time-stamp as the prefix.
I am using Windows Low Level KeyHook to initiate the screenshot with PrtSc key.
Error in 32 bit systems:
It only takes 2 screenshots and then does not respond when I press PrtSc for the 3rd time. Can JFrame cause any problems, it certainly loads up slow. Should I use any alternate text box than JFrame or is it because I have complied in java 1.8 jdk 64 bit environment, which wont work in lower versions of jdk or 32 bit systems.
public class KeyHook {
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
static JFileChooser fileChooser = new JFileChooser();
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
if (nCode >= 0) {
switch(wParam.intValue()) {
case WinUser.WM_KEYUP:
case WinUser.WM_KEYDOWN:
case WinUser.WM_SYSKEYUP:
case WinUser.WM_SYSKEYDOWN:
if (info.vkCode == 44) {
try {
Robot robot = new Robot();
// Capture the screen shot of the area of the screen defined by the rectangle
BufferedImage bi=robot.createScreenCapture(new Rectangle(0,25,1366,744));
JFrame frame = new JFrame();
JFrame.setDefaultLookAndFeelDecorated(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// prompt the user to enter their name
String name = JOptionPane.showInputDialog(frame, "Enter file name");
// frame.pack();
frame.dispose();
String fileName= dovalidateFile(name);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG", ".png");
fileChooser.setFileFilter(filter);
fileChooser.setSelectedFile(new File (fileName));
int returnVal = fileChooser.showSaveDialog(null);
if ( returnVal == JFileChooser.APPROVE_OPTION ){
File file = fileChooser.getSelectedFile();
file = validateFile(file);
System.out.println(file);
ImageIO.write(bi, "png", file);
}
}
catch (NullPointerException e1)
{e1.printStackTrace(); }
catch (AWTException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
private File validateFile(File file) {
DateFormat dateFormat = new SimpleDateFormat("HH.mm.ss.ddMMMMMyyyy");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
// System.out.println(dateFormat.format(cal.getTime()));
String filePath = file.getAbsolutePath();
if (filePath.indexOf(".png") == -1) {
filePath += "." + dateFormat.format(cal.getTime()) + ".png";
}
//System.out.println("File Path :" + filePath);
file = new File(filePath);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private String dovalidateFile(String name) {
String input = name.replace("https://www.","");
input = input.replaceAll("http://www.","");
input = input.replaceAll("https://","");
input = input.replace("http://","");
input = input.replace("/?",".");
input = input.replace("/",".");
input = input.replace("|",".") ;
input = input.replace("%",".");
input = input.replace("<",".");
input = input.replace(">",".");
input = input.replaceAll("\\?",".");
input = input.replaceAll("\\*",".");
input = input.replace(":",".");
input = input.replace("\\",".");
input = Character.toUpperCase(input.charAt(0)) + input.substring(1);
return input;
}
};
hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
if(!SystemTray.isSupported()){
return ;
}
SystemTray systemTray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage(KeyHook.class.getResource("/images/icon.png"));
//popupmenu
PopupMenu trayPopupMenu = new PopupMenu();
MenuItem close = new MenuItem("Exit");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
});
trayPopupMenu.add(close);
//setting tray icon
TrayIcon trayIcon = new TrayIcon(image, "captur", trayPopupMenu);
//adjust to default size as per system recommendation
trayIcon.setImageAutoSize(true);
try{
systemTray.add(trayIcon);
}catch(AWTException awtException){
awtException.printStackTrace();
}
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
System.err.println("error in get message");
break;
}
else {
System.err.println("got message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
lib.UnhookWindowsHookEx(hhk);
}
}
I don't have any experience with JNA, but there are several things that are wrong about your code - I don't think I got them all, but here are some:
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
quit=true;
}
});
The quit=true will never be reached because your program exit()s before it ever goes there.
2.
new Thread() {
public void run() {
while (!quit) {
try { Thread.sleep(10); } catch(Exception e) { }
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
doesn't make any sense since quit will never be true. Also spinning on a variable to detect a change will severly slow down your application (espacially with sleep-times of 10 ms). Why not do the unhook in your ActionListener?
3.
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
Here I'm not too sure because I don't have experience with JNA and the windows event system. The method waits for messages sent to the specified window, but since you don't specify any (second parameter is null) I don't think you will ever get one.
For each callback you are creating a new JFrame but at the end of the method you are only hiding it using frame.setVisible(false);. Since it is still referenced from various Swing-classes it will never be garbage-collected. This creates a memory-leak which will slow down your application. You will have to call frame.dispose() to get rid of it.
I have an application to show a image of the user's data. Where each user has more than 1 image data.
When I select the user in the JTable, my image data show in JPanel. The picture actually also JPanel with background image.
My question is, memory consumption always increases, and not reduce. Sometimes the application hangs.
How to register the picture(JPanel) to garbage collection. And if it possible, when i must to register them?
I am new in performance issue in Java.
This is my code :
public void getStreamData(final PanelEntry view, final String data) {
String files = null;
String path = null;
if(isImages()) {
path = "data/"+data+"/images";
} else {
path = "data/"+data+"/videos/thumbs";
}
File folder = new File(path);
// Always remove previous image label when new data selected
view.getPanelStream().removeAll();
if (!folder.exists()) {
JLabel label = new JLabel("No Stream Data");
label.setForeground(Color.red);
label.setVisible(true);
// Adding to panelGallery
view.getPanelStream().add(label);
view.getPanelStream().revalidate();
view.getPanelStream().repaint();
} else {
File [] listOfFiles = folder.listFiles();
int maxFiles = listOfFiles.length;
int maxView = 15;
// Loop for get image from file
for (int i = listOfFiles.length; i > 0 ; i--) {
if(listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
final String videoFiles = files;
if(files.endsWith(".jpg") || files.endsWith(".JPG") ||
files.endsWith(".jpeg") || files.endsWith(".JPEG") ||
files.endsWith(".png") || files.endsWith(".PNG")) {
final String newPath = path+"/"+files;
try {
File showFile = new File(newPath);
ImageIcon imgSource = new ImageIcon(newPath);
JPanel labelGallery = new BackgroundImageRounded(showFile);
labelGallery.setLayout(null);
labelGallery.setPreferredSize(new Dimension(160, 120));
labelGallery.setVisible(true);
JLabel labelName = new JLabel(files);
labelName.setSize(150,15);
labelName.setLocation(8, 8);
labelName.setVisible(true);
labelName.setForeground(Color.ORANGE);
labelGallery.add(labelName);
String videoPath = "data/"+data+"/videos/";
String video = videoFiles.replace(".jpg", ".wmv");
String videoFile = video.replace("thumb_", "video_");
final String videoPlayer = videoPath+videoFile;
if (isImages()) {
labelGallery.setToolTipText("View Image");
} else {
labelGallery.setToolTipText("Play Video");
JLabel iconPlayer = new JLabel();
iconPlayer.setIcon(new ImageIcon(getClass().getResource("/com/ikbiz/gastroscope/resources/player.png")));
iconPlayer.setSize(61,42);
iconPlayer.setVisible(true);
iconPlayer.setLocation(50, 35);
labelGallery.add(iconPlayer);
}
labelGallery.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if(isImages()) {
ImageViewer viewer = new ImageViewer(newPath);
viewer.setVisible(true);
} else {
VideoViewer videoViewer = new VideoViewer();
videoViewer.setViewer(videoPlayer);
videoViewer.setLocationRelativeTo(null);
videoViewer.pack();
videoViewer.setVisible(true);
}
}
});
// Adding to panelGallery
view.getPanelStream().add(labelGallery);
view.getPanelStream().revalidate();
view.getPanelStream().repaint();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
Please help,
Thank you.
You should use a memory profiler to find out what is going on.
Here, you talk about registering the JPanel, but how are you 100% sure that this is the kind of objects that consume memory ?
I think you should :
Profile your heap utilization
Find out the objects that consume a lot of memory
Find where they are instantiated
Find out why they are not reclaimed by the GC (what are the GC roots that links to them)
Without more information, you are just guessing that some portion of your code must be the culprit, but you do not have a clue.
I am creating an editor in java. I would like to know how to save an intermediate state in java?
For Example when user wants to save the changes done on the editor, how could it be done and also should be reloaded later.
Eg. powerpoint application is saved as .ppt or .pptx. Later the same .ppt while could be opened for further editions. I hope I am clear with my requirement.
The Preferences API with user preferences; most recently edited files, per file maybe timestamp + cursor position, GUI settings.
To save the contents of JTextPane you can serialize the DefaultStyledDocument of JTextPane in a file using proper way of serialization. And when you want to load the content again you can deserialize the same and display it on the JTextPane . Consider the code given below:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SaveEditor extends JFrame implements ActionListener{
public static final String text = "As told by Wikipedia\n"
+"Java is a general-purpose, concurrent, class-based, object-oriented computer programming language."
+ "It is specifically designed to have as few implementation "
+ "dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), "
+ "meaning that code that runs on one platform does not need to be recompiled to run on another. "
+ "Java applications are typically compiled to bytecode (class file) that can run on any Java virtual "
+ "machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming "
+ "languages in use, particularly for client-server web applications, with a reported 10 million users.";
JTextPane pane ;
DefaultStyledDocument doc ;
StyleContext sc;
JButton save;
JButton load;
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SaveEditor se = new SaveEditor();
se.createAndShowGUI();
}
});
} catch (Exception evt) {}
}
public void createAndShowGUI()
{
setTitle("TextPane");
sc = new StyleContext();
doc = new DefaultStyledDocument(sc);
pane = new JTextPane(doc);
save = new JButton("Save");
load = new JButton("Load");
JPanel panel = new JPanel();
panel.add(save);panel.add(load);
save.addActionListener(this);load.addActionListener(this);
final Style heading2Style = sc.addStyle("Heading2", null);
heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
try
{
doc.insertString(0, text, null);
doc.setParagraphAttributes(0, 1, heading2Style, false);
} catch (Exception e)
{
System.out.println("Exception when constructing document: " + e);
System.exit(1);
}
getContentPane().add(new JScrollPane(pane));
getContentPane().add(panel,BorderLayout.SOUTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == save)
{
save();
}
else if (evt.getSource() == load)
{
load();
}
}
private void save()//Saving the contents .
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Save");
int returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file != null)
{
FileOutputStream fos = null;
ObjectOutputStream os = null;
try
{
fos = new FileOutputStream(file);
os = new ObjectOutputStream(fos);
os.writeObject(doc);
JOptionPane.showMessageDialog(this,"Saved successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (Exception ex){}
}
if (os != null)
{
try
{
os.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
private void load()//Loading the contents
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Open");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file!= null)
{
FileInputStream fin = null;
ObjectInputStream ins = null;
try
{
fin = new FileInputStream(file);
ins = new ObjectInputStream(fin);
doc = (DefaultStyledDocument)ins.readObject();
pane.setStyledDocument(doc);
JOptionPane.showMessageDialog(this,"Loaded successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fin != null)
{
try
{
fin.close();
}
catch (Exception ex){}
}
if (ins != null)
{
try
{
ins.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}
I'm learning java and I have made simple program that simply reads value from JTextField and saves it to file using FileOutputStream.
My question is: is it normal for data to be unreadable (using same program with FileInputStream) after restarting it? If i read it without terminating program it works fine.
How can I make data wrote to file permament?
Edit:
It seems the file is being cleaned when starting the program.
Here is the code:
public class Test extends JFrame
{
JTextField field;
JButton write;
JButton read;
File file;
FileOutputStream fOut;
FileInputStream fIn;
int x;
Test() throws IOException
{
setAlwaysOnTop(true);
setLayout(new BorderLayout());
field = new JTextField(4);
write = new JButton("Write");
read = new JButton("Read");
file = new File("save.txt");
if(!file.exists())
{
file.createNewFile();
}
fOut = new FileOutputStream(file);
fIn = new FileInputStream(file);
add(field);
add(write, BorderLayout.LINE_START);
add(read, BorderLayout.LINE_END);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(160,60);
write.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
x = Integer.parseInt(field.getText());
try
{
fOut.write(x);
System.out.println("Saving completed.");
fOut.flush();
}
catch(Exception exc)
{
System.out.println("Saving failed.");
}
}
});
read.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
x = fIn.read();
fIn.close();
}
catch(Exception exc)
{
System.out.println("Reading failed.");
}
}
});
}
public static void main(String[] args) throws IOException
{
new Test();
}
}
Make sure you flush() and close() the streams.
This fOut = new FileOutputStream(file); will overwrite the file, you need to use fOut = new FileOutputStream(file, true); to append to it.
here's some code to open a file for writing .. observe the "true" parameter which means we APPEND the text at the end instead of adding it to the start. The same goes for FileOutputStream .. if you don't specify the second argument (true) you will end up with an overwritten file.
try{
// Create file
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (IOException e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}