Update JTabbedPane when new file added to directory - java

I have situation as follows: GUI with several tabs. Every tab shows content of files in the specific directory in my home directory. Some of these directories exist at the point of GUI creation and others do not. In one of tab via FTP I get some file and add it to the home directory.
Note: I'm using java 5.
How to let every tab know that FTP has added a new file to the directory which belongs to this tab?
public class ScannerPanel extends JPanel implements ChangeListener {
private void initGUI() {
setPreferredSize(new Dimension(700, 400));
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("FTP", IconLib.ICON_16X16_DATA,new FtpTabPanel (this),"FTP");
tabbedPane.addTab("PCS", IconLib.ICON_16X16_THUM,new PcsTabPanel (this),"PCS");
tabbedPane.addTab("Car", IconLib.ICON_16X16_PAPE,new CarTabPanel (this),"Car");
tabbedPane.addTab("Pic", IconLib.ICON_16X16_RETI,new PicTabPanel (this),"Pic");
tabbedPane.addChangeListener(this);
add(tabbedPane);
}
public void stateChanged(ChangeEvent e) {
//detect new file has been added to directory
// update the content of tab
}
}

Take a look at the 'Watching a directory' tutorial which contains a lot of useful information and recommends to use a WatchService. For a file system watch service, you can use the FileSystem#newWatchService method

You can try http://jpathwatch.wordpress.com/ this one should work with Java 5.
jpatchwatch is a Java library for monitoring directories for changes. It uses the host platform’s native OS functions to achieve this to avoid polling.
Or of course you could write your own polling: wait with Thread.sleep, read the directory, compare the results with the previous list... But this can get I/O intensive, if your polling interval is very short. Also see this: WatchService for Java 6

Related

Unable to set icon for java application using setIconImage() method

I'm trying to create one simple GUI based testing tool in Java using Eclipse. I have been trying to add icon to my application. Images are present inside the project in a folder. Could you please suggest what mistake I'm doing.
I'm used below two ways, unfortunately both are not helping me. -
1.) frame.setIconImage(image).
2.) setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath)));
Below is the setup of my project in Eclipse -
Below is code which i'm using -
public static void main(String[] args) {
JFrame frame = new JFrame("Testing Tool");
// setting close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// sets 500 width and 600 height
frame.setSize(500, 600);
try {
Image image = new ImageIcon("/Project_T/Images/biplane.jpg").getImage();
frame.setIconImage(image);
} catch(Exception e) {
System.out.println("Application icon not found");
}
// uses no layout managers
frame.setLayout(null);
// makes the frame visible
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Since i'm going to create an .exe file for this project using lunach4J, is this the way of keeping files (placing them in a folder of project since I would be using multiple images and files) that ensures the application running on any machine.
This is the code I used with a Swing application packaged in an executable JAR file. The JFrame has the icon image.
private static final String APP_ICON_PATH = "myapp/icondirectory/report.png";
ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource(APP_ICON_PATH));
frame.setIconImage(icon.getImage())
The "myapp" is the root of my package structure; e,g., the GUI class using the frame is in the package myapp.gui package. The image PNG files are within the application's executable JAR file (as you see in the code within a separate folder).
Also, look at the Oracle's Java Swing tutorials explain the usage of icons.
I fiddled a lot and finally found a way out , since my explanation was a bit long so I thought of writing an answer. Also please suggest that is this a good way since we would be exporting our project.
Java gives you the power to change the ICON for your application with the help
of setIconImage(image), but this method is not that direct, since we are
dealing with multiple files those should be present while executing the code so we
would have to ensure that their paths are correct and accessible in order to run smoothly.
Hence we save our files inside the src by creating another folder and from there
we can import the files easily. Follow these steps
Step - 0 - Place the files inside src folder of the project
Put the files inside the scr folder by creating another folder, here I created another folder by the name of images and placed my files there, hence the file path would be
"Images/biplane.png",
please ensure that there are no "/" placed before Images (our folder name)
Step - 1 - Place the file path inside a URL variable
Step - 2(Optional) - Print this URL variable to cross check that this is not null. If this is null check your path again and repeat the activity so that this value is not null.
Step - 3 - Now pass this URL to ImageIcon method.
Step - 4 - Call the setIconImage method with that image.
Code Used -
URL url = test.class.getClassLoader().getResource("Images/biplane.png");
System.out.println("Path for file is :- \"" + url + "\"");
Image image = new ImageIcon(url).getImage();
frame.setIconImage(image);

How to add a seekbar to a video played using vlcj in Java Swing?

I’ve trimmed down the code to only the relevant parts and posted it below. The code works fine. The video plays when you run it but it doesn’t have a seekbar.
public class Screen {
//JFrmae
private JFrame frame;
// Panel which I add the canvas to
private JPanel pVid = new JPanel();
// Canvas
Canvas canvas = new Canvas();
// Embedded Media Player
EmbeddedMediaPlayer emp;
/**
* Create the application.
*/
public Screen() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
//Frame
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//Adding the panel to the frame
frame.getContentPane().add(pVid);
//Adding the canvas to the panel
pVid.add(canvas);
//Setting canvas size
canvas.setSize(715, 402);
//Loading the VLC native library
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "lib");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
//Initializing the media player
MediaPlayerFactory mpf = new MediaPlayerFactory();
//Misc
emp = mpf.newEmbeddedMediaPlayer(new Win32FullScreenStrategy(frame));
emp.setVideoSurface(mpf.newVideoSurface(canvas));
//Video file name and playing
String file = "video.mp4";
emp.prepareMedia(file);
emp.play();
//pack method
frame.pack();
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Screen window = new Screen();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
I’ve looked for an answer online for the last 4 days. Finally I decided to ask here. The official website for vlcj has pictures of a vlcj player they’ve made. There is a seekbar in those pictures. Link to the webpage which has the pics: http://capricasoftware.co.uk/#/projects/vlcj
They have a number of useful tutorials there but they don’t have any instructions for adding the seekbar.
Then I tried downloading their vlcj-player project from their GitHub page. It showed an error because it couldn’t resolve the “com.google.common.collect.ImmutableList” which is supposed to be imported. (At the moment I’m reading about ImmutableList and stuff and see if there’s a way to fix it.) Since I couldn’t figure that out yet, I looked for a class named seekbar or the like in their project. I couldn’t find any.
I also searched elsewhere online for the answer but I just couldn’t find it. I’d really appreciate any help. Thank you.
Edit:
(This edit is in response to the suggestion given to me by #caprica. Read their comment to this question and my reply to that in the comment to understand what I'm talking about here in this edit. I think it'll be useful for others in the future.)
All right, there must have been some problem with my Eclipse or computer. (I’ll type out how I fixed it at the end of this comment.) It’s working now. I’ll type out what I did step by step so that may be it’ll be useful to others in the future to download and install the project.
Download the project.
Import it as a Maven project. (Import > Maven > Existing Maven Project)
Now in Eclipse right click the imported project and select Run As > Maven Install
And that’s it. Now you can just run the project normally. If you don’t know how to run the project, do it like this. Right click the project and select Run As > Java Application and then Select VlcjPlayer – uk.co.caprica.vlcplayer.
Alternatively you can open the class where the main method is and run it. VlcjPlayer class is where the main method is located. The class is in the package uk.co.caprica.vlcplayer.
The problem I faced was that somehow all the necessary files didn’t get downloaded when I ran it as Maven Install. But it worked fine in another computer. Since I knew where the files are downloaded to, I just copied the folder from that PC and put it in the same place in my PC. The folder name is ‘repository’. It’s location is C:\Users\User Name\ .m2. Perhaps Eclipse in this PC has some problem. I’ll reinstall it later to avoid problems in the future.
And this may be useful, the VLC that’s installed in this PC is 64 bit. Not sure if that makes a difference but mentioning it just in case.
Now that the app is working fine I will see the code and see how the seekbar is made. Thanks a lot #caprica for telling me that I should import it as a Maven project. :)
The Basic Controls tutorial shows the essential approach: Add a panel of buttons to the frame and give each button an ActionListener that invokes the relevant media player command. As an example, this notional Rewind button would "skip backwards 10 seconds (-10,000 milliseconds)."
JPanel controlsPane = new JPanel();
JButton rewindButton = new JButton("Rewind");
rewindButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.getMediaPlayer().skip(-10000);
}
});
controlsPane.add(rewindButton);
frame.add(controlsPane, BorderLayout.SOUTH);
The software design is up to you, but you should at least be aware of
JToolBar, seen here and here.
Action, seen here and cited here.
Timer, seen here as a way to repeat an Action.
All right, guys. I’ve figured out how to do it. I’m not sure how it was done in the official Vlcj project but I’ve figured out my own simple way by learning from the official project.
It just takes a few lines of code. It’s very simple.
These are the steps you have to follow:
Create a JSlider.
To the JSlider, add a mouseMotionListener (‘mouseDragged’ to be exact).
Inside that put in the code which would update the video position based on
the change in the JSlider.
Create a Timer.
Put the code inside it to set the value of the JSlider based on the position
of the video.
And that’s it!
This is the code. It comes inside the initialize() method which you can see in the code I’ve given in the question. (And of course you'll also have to create the JSlider and add it to the panel. I haven't shown the code since it's simple.)
js.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
if (js.getValue() / 100 < 1) {
emp.setPosition((float) js.getValue() / 100);
}
}
});
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
js.setValue(Math.round(emp.getPosition() * 100));
}
});
timer.start();
Some explanation.
The value you get when you use emp.getPosition always seems to be in decimals. It’s something like 0.1334344 at the start of the video and it’s something like 0.998988 at the end. But the value of JSlider is in int. From 0 to 100. So in the mouseMotionListener added to the JSlider I’ve converted the int value of the JSlider to float by dividing it by 100.
And in the action listener inside the timer I’ve multiplied the value of the video position by 100 and then rounded it off to make it an int value. So that value can be set in the JSlider to make it move in sync with the video.
I’m sure the code is rudimentary and there could be some best practices which I may not have followed. Sorry about that but I’m just getting into java by learning the stuff which I find interesting. Those who are good at java and have used such code in an actual project can comment below with how it can be improved.

Take action on NetBean's editor's window closing

We are using NetBeans Platform 7.0.1, and have implemented support for a new language using this (now “obsolete”) tutorial.
Since all our contents are stored in a database, and not on files, we open them like this:
FileSystem fs = FileUtil.createMemoryFileSystem();
FileObject fo = fs.getRoot().createData(fileName, fileExtension);
… write contents from database to `fo` ….
DataObject data = MyMultiDataObject.find(fo);
EditorCookie.Observable cookie = data.getCookie(EditorCookie.Observable.class);
cookie.open();
… forces undock of editor window …
And, in our layer.xml, have added a custom button to Save that sends the content back to the database.
However, when the user closes the file (by either closing the tab or the window), we haven’t figured a way of saving it.
Adding a PropertyChangeListener to the Cookie and watching for PROP_DOCUMENT (and newValue() == null) seems to do the trick for when the window is closed. But how does one get the return value from the confirmation window (I’m referring to when the file is closed after changes, the message File xxx.xxx is modified. Save it?)?
Well, it seems we've been approaching the problem in the wrong way.
Since we are opening the file in-memory, it was suggested in the netbeans-dev list that we should listen for changes in the file itself, by using
fo.addFileChangeListener(new CustomFileChangeListener());
public class CustomFileChangeListener implements FileChangeListener {
#Override
public void fileChanged(FileEvent fe) {
... file has been saved in the editor, sync with database ...
}
}
And keep it synchronized that way, taking advantage of the built-in NetBeans Platform "save" functionality.

Create a simple form application to edit a textfile

I think I need to restate my question ...
I want to create a SIMPLE form application that edits certain areas of one very specific text file. Though I have some web development experience, I do not want to create a browser based application. Basically I want to give a Desktop application a try and I am looking for some help to get started including suggestions for the language of choice. The application should run on Mac OS X. Besides there's no restriction: Java, Cocoa, Python, even a some interactive shell script would be ok.
If you are interested in the details, continue to read here, but not that my question is not LaTex specific...:
I have an automatically generated report file that contains LaTex Code. Now I want to build a little application that creates a form field for every section and it's header. The document contains only a few hundred lines and the should work the following:
\section{ This is were the header text should go inside the document }
\normalsize{ This is where the normal text should go}
The header / normalsize pairs occur 5-6 times within the document. All I want is a little GUI that allows user to edit between the curly braces without seeing any TeX code. I know that there's LyX and other WYSIWYG approaches to LaTeX – I do not want to reinvent the wheel. I just want to protect the auto-generated code a litte from users and make it a little more comfortable to them.
EDIT:
here's my very first try. I guess I should use PlainDocument instead of directly sending it, but I´ll figure that out, since I got plenty of help from trashgod with the editor / Text Component links. The major problem is to single out the content from \section{} and \normalsize{} stuff. Probably I will some regexp here. I need to get a new text area for every appearance.
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileReader;
import javax.swing.*;
public class basicFrame extends JFrame {
// Declare Variables
JScrollPane bildlauf = new JScrollPane();
JTextArea txtfeld = new JTextArea();
public basicFrame() {
super();
// Main window
setTitle("ReportEditor");
setBackground(Color.LIGHT_GRAY);
// components
try {
File datei = new File("report.Rnw");
FileReader in = new FileReader(datei);
txtfeld.read(in, datei);
in.close();
} catch (Exception e) {
System.out.println("Error !");
}
// setLayout(new GridLayout(2,2));
// Scroll Shizzle
bildlauf.getViewport().add(txtfeld, null);
getContentPane().add(bildlauf, BorderLayout.CENTER);
//txtfeld.setSize(500,680);
//add(txtfeld);
//this.getContentPane().add(txtfeld);
// close
addWindowListener(new WindowLauscher());
}
// event handlers...
protected static final class WindowLauscher extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
//Fesnter erzeugen und anzeigen, die main Sache halt
basicFrame hf = new basicFrame();
hf.setSize(500, 700);
hf.setLocation(100, 100);
hf.setVisible(true);
}
}
Thx in advance for any suggestions!
The TeX on Mac OS X wiki recommends jEdit, which supports plugins. LaTeXTools might be a good start.
Addendum:
I do not want to reinvent the wheel.
All I want to do is create a form application.
Although these goals are somewhat contradictory, you can always parse the file and use a suitable JTextComponent for each editable section. Here's an overview of Using Text Components; see Text Component Features if you want to create your own editor kit, as discussed in Customizing a Text Editor.
Addendum: In addition to the tutorial, you might look at this text field layout example. Also, consider a two-column JTable, which would allow you to cleanly separate your document model from your form view.
Addendum: A few notes on your code.
Class names are usually capitalized, e.g. BasicFrame.
Don't extend JFrame if you're not changing it's behavior; JPanel is a good container for other components, and it can be displayed in a JFrame.
Always buid your GUI on the EDT.
Keep you view and model separate.

How can I make a JFileChooser on the Mac that lets users create directories?

I have an installer program that lets the user choose a directory in which to install. The JFileChooser implementation on MacOS uses a native dialog (or at least it looks native). That's great.
The only problem is there's no way to create a directory from this dialog ... you can only choose a pre-existing one, which is clunky. Is there a way to get this functionality?
I use the JFileChooser in "select directories only" mode. Thus it isn't the same dialog as the usual MacOS file picker which does have that functionality.
That is correct that the showOpenDialog method will not give you an option to create new folders. This is a usability thing as it does not really make sense to open something that does not exist. If you use the showSaveDialog there will be a button 'Make new Folder' or similar to that.
public static void main(String[] args) {
JFrame frame = new JFrame();
FileDialog d = new FileDialog(frame);
d.setVisible(true);
}

Categories

Resources