Opening edrawingsviewer files from java - java

I have an application that I run on a pc with a mouse, I want to launch edrawingsviewer with a particular file name from java and then when the user returns to the fullscreen app, if they haven't closed it I want to close it. This is what I've got so far for a quick demo but I cannot figure out what to put in the arguments in order to launch solidworks with a particular file.
package com.protocase.hmiclient.edrawings;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* #author DavidH
*/
public class EDrawingHelper {
public static File[] getEDrawingsForJob(final String jobNumber) {
File f = new File("\\\\itsugar\\www\\HMI\\POD EDRAWINGS");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(jobNumber) && (name.endsWith("EASM") || name.endsWith("EDRW"));
}
});
return matchingFiles;
}
public static void test(String[] args) {
File[] files = getEDrawingsForJob("G080111004-13162-1");
for (File file : files){
System.out.println(file.getName());
}
}
public static void openEDrawingForFileName(String fileName){
try {
final Process process = Runtime.getRuntime().exec("C:\\Program Files\\SolidWorks Corp\\SolidWorks eDrawings (2)\\EModelViewer.exe \\\\itsugar\\www\\HMI\\POD EDRAWINGS\\"+fileName);
JFrame frame = new JFrame();
JButton killButton = new JButton("KILL");
killButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
process.destroy();
System.exit(0);
}
});
frame.getContentPane().add(killButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
openEDrawingForFileName("G080111004-13162-1 ASSEMBLY.EASM");
}
}
I don't think this is a solidworks problem, I think this is just something I'm passing wrong or formatting wrong or something.

It appears as if running it through the FileProtocolHandler causes it to open fine.
final Process process = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler \\\\itsugar\\www\\HMI\\POD EDRAWINGS\\"+fileName);

Related

How can I show progress bar using Swingworker?

This is my code snippet. On the click of button it executes the loading program in the background, but I am unable to fetch the details of the task in the progress bar. Can anyone please tell me what am I missing here?
The point is I don't want to include all the insertion code inside my doInBackground method.
public class ProgressBarDemo extends JPanel
implements ActionListener,
PropertyChangeListener {
private JProgressBar progressBar;
private JButton startButton;
private JTextArea taskOutput;
private Task task;
class Task extends SwingWorker<Void, Integer> {
#Override
protected void process(List<Integer> arg0) {
// TODO Auto-generated method stub
super.process(arg0);
for(int k:arg0)
System.out.println("arg is "+k);
setProgress(arg0.size()-1);
}
/*
* Main task. Executed in background thread.
*/
#Override
public Void doInBackground() throws Exception {
Random random = new Random();
int progress = 0;
//Initialize progress property.
setProgress(0);
Thread.sleep(100);
new LoadUnderwritingData().filesinfolder("D:\\files to upload\\");
System.out.println("records inserted are "+LoadData.records_count_inserted);
publish(LoadData.records_count_inserted);
/*
* while (progress < 100) { //Sleep for up to one second. try {
* Thread.sleep(random.nextInt(1000)); } catch (InterruptedException ignore) {}
* //Make random progress. progress += random.nextInt(10);
* setProgress(Math.min(progress, 100)); }
*/
return null;
}
/*
* Executed in event dispatching thread
*/
#Override
public void done() {
Toolkit.getDefaultToolkit().beep();
startButton.setEnabled(true);
setCursor(null); //turn off the wait cursor
taskOutput.append("Done!\n");
}
}
I see you aren't calling progressBar.setValue(progress);.
Also you'd need to call publish(currentInsertCount); after each inserted element.
In the process method you'd do:
// assuming you are passing the current insert count to publish()
for (int k : arg0){
System.out.println("arg is " + k);
progressBar.setValue(k);
}
However from what you posted now it is not really clear where processing even occurs.
Is it this line:
new LoadUnderwritingData().filesinfolder("D:\\files to upload\\");
If it is then you would have to pass some Callback to the filesinfolder("..."), so that it can update the progress.
Note: It might be easier to just do it in a plain new Thread instead of using the SwingWorker.
How I would do it with a plain Thread:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class ProgressBarDemo extends JPanel implements ActionListener {
private JProgressBar progressBar;
private JButton startButton;
private JTextArea taskOutput;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("ProgressBarDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setPreferredSize(new Dimension(500, 500));
frame.add(new ProgressBarDemo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
public ProgressBarDemo() {
progressBar = new JProgressBar(0, 100);
startButton = new JButton(">");
taskOutput = new JTextArea();
startButton.addActionListener(this);
setLayout(new BorderLayout());
add(startButton, BorderLayout.NORTH);
add(taskOutput, BorderLayout.CENTER);
add(progressBar, BorderLayout.SOUTH);
progressBar.setVisible(false);
}
// If you don't care about a small chance of the UI not updating properly then you can perform the updates directly instead of calling invokeLater.
// If you are compiling below Java 1.8, you need to convert Lambda expression to a Runnable and make the directory parameter final.
public void upload(File directory) {
// No need for invokeLater here because this is called within the AWT Event Handling
startButton.setEnabled(false);
progressBar.setVisible(true);
new Thread() {
#Override
public void run() {
taskOutput.append("Discovering files...\n");
// List<File> files = Arrays.asList(directory.listFiles()); //
// if you want to process both files and directories, but only
// in the given folder, not in any sub folders
// List<File> files = Arrays.asList(getAllFiles(directory)); //
// if you only want the files in that directory, but not in sub
// directories
List<File> files = getAllFilesRecursive(directory); // if you
// want all
// files
SwingUtilities.invokeLater(() -> {
taskOutput.append(" -> discovered " + files.size() + " files.\n");
progressBar.setMaximum(files.size());
taskOutput.append("Processing files...\n");
});
int processedCount = 0;
for (File file : files) {
try {
byte[] bytes = Files.readAllBytes(file.toPath());
// TODO: process / upload or whatever you want to do with it
} catch (Throwable e) {
// Same here, you may skip the invokeLater
SwingUtilities.invokeLater(() -> taskOutput.append("Failed to process " + file.getName() + ": " + e.getMessage() + "\n"));
e.printStackTrace();
} finally {
processedCount++;
final int prcCont = processedCount; // not necessary if invoking directly
SwingUtilities.invokeLater(() -> progressBar.setValue(prcCont));
}
}
SwingUtilities.invokeLater(() -> {
taskOutput.append(" -> done.\n");
startButton.setEnabled(true);
progressBar.setVisible(false);
});
}
}.start();
}
#Override
public void actionPerformed(ActionEvent e) {
upload(new File("C:\\directoryToUpload"));
}
/**
* Gets all normal files in the directory.
*/
public static File[] getAllFiles(File directory) {
return directory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
}
/**
* Gets all normal files in the given directory and its sub directories.
*/
public static List<File> getAllFilesRecursive(File directory) {
List<File> result = new ArrayList<File>();
getAllFilesRecursive(directory, result);
return result;
}
private static void getAllFilesRecursive(File directory, List<File> addTo) {
if (directory.isFile()) {
addTo.add(directory);
} else if (directory.isDirectory()) {
File[] subFiles = directory.listFiles();
if (subFiles == null)
return;
for (File subFile : subFiles) {
getAllFilesRecursive(subFile, addTo);
}
}
}
}

Problem with synchronisation between FileReader and ActionListner,FileReader gives nullpointer before i can give him any valor;

Here is my program. I have to select a file from the JFileChooser and then perform some operations on it. The problem is that filereader gives nullpointer before I can choose the file, to be honest, I can't even choose because nothing appears to me when testo=new file reader(cavia) is there, if I try to remove it, everything goes right but I can't choose the file.
What can I do?
public class Chooser {
static File cavia;
public static void main(String[] args) throws IOException {
JFrame quadro= new JFrame();
JFileChooser scelta= new JFileChooser();
quadro.setLayout(new GridLayout());
JButton apriselezione = new JButton("Selezionafle");
quadro.setBounds(20, 20, 300, 300);
FileReader testo;
scelta.setCurrentDirectory(new File (System.getProperty("user.home")+System.getProperty("file.separator")+"Desktop"));
apriselezione.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
scelta.showOpenDialog(apriselezione);
cavia=scelta.getSelectedFile();
}
});
testo= new FileReader(cavia);
apriselezione.setVisible(true);
quadro.add(apriselezione);
quadro.setVisible(true);
quadro.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testo.close();
}
}
Here is how you should do it (Some extra comments and changes inside the code):
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.SwingUtilities;
public class Chooser {
static File cavia;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> { // All swing applications should run in their own thread
JFrame quadro = new JFrame();
JFileChooser scelta = new JFileChooser();
quadro.setLayout(new GridLayout());
JButton apriselezione = new JButton("Selezionafle");
quadro.setBounds(20, 20, 300, 300);
scelta.setCurrentDirectory(
new File(System.getProperty("user.home") + System.getProperty("file.separator") + "Desktop"));
apriselezione.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
scelta.showOpenDialog(apriselezione);
cavia = scelta.getSelectedFile();
try (FileReader testo = new FileReader(cavia)) { // try-with-resources
//Do something with filereader
} catch (IOException e2) {
e2.printStackTrace();
}
}
});
apriselezione.setVisible(true);
quadro.add(apriselezione);
quadro.setVisible(true);
quadro.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
});
}
}

How to list recently used files in JFileChooser Swing component

I am using javax.swing.JFileChooser swing component in my Java Project for opening file by dialog. How to list recently used files for selection in JFileChooser. Everytime I am going inside the directory and selecting file which is time-consuming.
How do I list last few recently used files in the component itself so that we dont need to navigate through the directories again and again to select a file?
JFileChooser allows you to supply a accessory Component which is added to the JFileChooser component, on the right side under Windows.
What you could do is ...
Create a JList and ListModel, set the JList as the JFileChoosers accessory (wrapping it in JScrollPane)
Each time you select a file, add it to a Set
Each time your go to open the JFileChooser, update the JList's model with the values from the Set (or back the model with the Set).
Each time the user selects a value from the list, you will need to change the JFileChoosers selectedFile property to reflect the change...
For more details, take a look at Providing an Accessory Component for more details...
Updated
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileSystemView;
public class TestFileChooser {
public static void main(String[] args) {
new TestFileChooser();
}
public TestFileChooser() {
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 JFileChooser fc;
private RectentFileList rectentFileList;
public TestPane() {
setLayout(new GridBagLayout());
JButton chooser = new JButton("Choose");
chooser.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (fc == null) {
fc = new JFileChooser();
rectentFileList = new RectentFileList(fc);
fc.setAccessory(rectentFileList);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
}
switch (fc.showOpenDialog(TestPane.this)) {
case JOptionPane.OK_OPTION:
File file = fc.getSelectedFile();
rectentFileList.add(file);
break;
}
}
});
add(chooser);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class RectentFileList extends JPanel {
private final JList<File> list;
private final FileListModel listModel;
private final JFileChooser fileChooser;
public RectentFileList(JFileChooser chooser) {
fileChooser = chooser;
listModel = new FileListModel();
list = new JList<>(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setCellRenderer(new FileListCellRenderer());
setLayout(new BorderLayout());
add(new JScrollPane(list));
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
File file = list.getSelectedValue();
// You might like to check to see if the file still exists...
fileChooser.setSelectedFile(file);
}
}
});
}
public void clearList() {
listModel.clear();
}
public void add(File file) {
listModel.add(file);
}
public class FileListModel extends AbstractListModel<File> {
private List<File> files;
public FileListModel() {
files = new ArrayList<>();
}
public void add(File file) {
if (!files.contains(file)) {
if (files.isEmpty()) {
files.add(file);
} else {
files.add(0, file);
}
fireIntervalAdded(this, 0, 0);
}
}
public void clear() {
int size = files.size() - 1;
if (size >= 0) {
files.clear();
fireIntervalRemoved(this, 0, size);
}
}
#Override
public int getSize() {
return files.size();
}
#Override
public File getElementAt(int index) {
return files.get(index);
}
}
public class FileListCellRenderer extends DefaultListCellRenderer {
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof File) {
File file = (File) value;
Icon ico = FileSystemView.getFileSystemView().getSystemIcon(file);
setIcon(ico);
setToolTipText(file.getParent());
setText(file.getName());
}
return this;
}
}
}
}
The question of persistence is broad question and will come down to your personal needs, for example, you could just dump the list of files out to a flat file, this is probably the simplest solution, as it means you can simply read the file from start to finish and know you have the entire contents. Also, writing out the file again will override any previous values, making it easy to manage.
Other solutions might require to provide a "count" property, which you would then suffix to a known key to list the values, which would require to manually remove the old values when you update the details. You could also try using a delimiter to save all the values as a single value in the persistence store, but this wrought with issues of picking a delimiter that won't be used within the file names (the path separator might do :D)
Take a look at How can I save the state of my program and then load it? for some more ideas...
Updated
After a little thought, you could use the Preferences API to store the list of files using a single key by using the File.pathSeparator, as this should be unique and not used by a file name/path.
For example, you could save the list using something like...
StringBuilder sb = new StringBuilder(128);
for (int index = 0; index < listModel.getSize(); index++) {
File file = listModel.getElementAt(index);
if (sb.length() > 0) {
sb.append(File.pathSeparator);
}
sb.append(file.getPath());
}
System.out.println(sb.toString());
Preferences p = Preferences.userNodeForPackage(TestFileChooser.class);
p.put("RectentFileList.fileList", sb.toString());
And load it again using something like...
Preferences p = Preferences.userNodeForPackage(TestFileChooser.class);
String listOfFiles = p.get("RectentFileList.fileList", null);
if (listOfFiles != null) {
String[] files = listOfFiles.split(File.pathSeparator);
for (String fileRef : files) {
File file = new File(fileRef);
if (file.exists()) {
add(file);
}
}
}
Use setSelectedFile(File file) method of JFileChooser.
The doc says:
public void setSelectedFile(File file)
Sets the selected file. If the file's parent directory is not the
current directory, changes the current directory to be the file's
parent directory.
This links may be helpful
example by peeskillet

Spring boot jar double-click

A spring boot application can start with a double-click on the .jar, but opens no terminal or something else, so a tomcat is running on port 8080 and I have to kill it from the task manager (what's a bit annoying when running different java applications).
Is there a way to force spring/java to open a terminal or create a run context with a new window?
I know I could open the jar from a terminal with java -jar application.jar and when killing the terminal also the server is killed. But for customer needs it would be interesting to have a double-click solution.
Thanks
Edit:
Right now my main class looks
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
Edit #2 - Possible Solution:
Through the comment I got the idea about opening a terminal window. What is possible but the command differs for every system. So the testing with different systems is a bit complicated.
So my actual solution is to open a java window and redirect the console output to this window. Which I found here and just edited a few lines, so the java window looks now like this:
import java.awt.BorderLayout;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class TextAreaOutputStreamTest extends JPanel {
private JTextArea textArea = new JTextArea(15, 30);
private TextAreaOutputStream taOutputStream = new TextAreaOutputStream(
textArea, "> ");
public TextAreaOutputStreamTest() {
setLayout(new BorderLayout());
add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
System.setOut(new PrintStream(taOutputStream));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Output");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TextAreaOutputStreamTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void mainRunner(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class TextAreaOutputStream extends OutputStream {
private final JTextArea textArea;
private final StringBuilder sb = new StringBuilder();
private String title;
public TextAreaOutputStream(final JTextArea textArea, String title) {
this.textArea = textArea;
this.title = title;
sb.append(title);
}
#Override
public void flush() {
}
#Override
public void close() {
}
#Override
public void write(int b) throws IOException {
if (b == '\r')
return;
if (b == '\n') {
final String text = sb.toString() + "\n";
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
sb.setLength(0);
sb.append(title);
return;
}
sb.append((char) b);
}
}
and I call it from my main method with
public static void main(String[] args) throws IOException {
if (args.length == 0) {
TextAreaOutputStreamTest.mainRunner(args);
}
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
With this I control the behavior also through command line arguments.
Different solutions are welcome but right now this works for my purpose.
You could write a simple .bat file.
Just write the cmd statements in a file and save it as "random".bat

Java click button to open URI: “Firefox can't find the server at www.%u.com.”

I want to have a button that, when clicked, opens the default browser and points to a URI.
I have some code that works in my testing, when run in Netbeans 7.x, but it fails when deployed as a JAR. My Java app runs on Linux only.
Anyone see the problem or know of another solution?
This code is in my main form:
linkBtnTest = new LinkButton(
new URI("http://www.example.com/some-page"),
"Click here for blah blah blah");
linkBtnTest.init();
} catch (Exception ex) {
Logger.log(ex);
}
Accessibility.increaseFontSize(linkBtnTest,
ApplicationContext.get().getFontIncreaseSize());
TestPanel.add(linkBtnTest);
Here's the class. I didn't write this code and I'm open to other suggestions:
package com.example.client;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;
import javax.swing.JButton;
public class LinkButton extends JButton
implements ActionListener {
/** The target or href of this link. */
private URI target;
final static private String defaultText = "<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT>"
+ " to go to the example website.</HTML>";
public LinkButton(URI target, String text) {
super(text);
this.target = target;
//this.setText(text);
this.setToolTipText(target.toString());
}
public LinkButton(URI target) {
this( target, target.toString() );
}
public void init() {
this.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
open(target);
}
class OpenUrlAction implements ActionListener {
#Override public void actionPerformed(ActionEvent e) {
open(target);
}
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(uri);
} catch (IOException e) { /* TODO: error handling */ }
} else { /* TODO: error handling */ }
}
}
}

Categories