开发者

Use command line args in a Java Swing program

开发者 https://www.devze.com 2023-03-16 19:46 出处:网络
How can you process command line arguments in a Java Swing program? EDIT: What I want t开发者_如何学运维o do is have the user give a file path as the arg. Then I set the text of a jTextPane to the co

How can you process command line arguments in a Java Swing program?

EDIT: What I want t开发者_如何学运维o do is have the user give a file path as the arg. Then I set the text of a jTextPane to the contents of that file.


The only way is through the main method when you run the Java class file.

You do the following in the command line once compiled; java NameOfClassFile a b c d

For example to print them out as an array of command line arguments:

public static void main(String[] args)
{
    for(String arg : args)
        System.out.println(arg);
}

I don't know of anyway to pass command line arguments to a currently running Java Swing program. Not sure if you can.

To display a files contents on a JTextPane you can use args[0] a a command line argument to the file path using:

JTextPane pane = new JTextPane();
JFrame frame = new JFrame("Example");
frame.add(pane);
frame.setVisible(true);
File file = new File(args[0]);
pane.setPage(file.toURL().toString());
frame.pack();

If you want more than one files contents just use java NameOfClassFile file1 file2 file3 Then you can use args[0] args[1] args[2] to get the file path and modify the above code to put on a JTextPane.


As mentioned, there's no direct way to go from command-line arguments to Swing. Your Swing application will be executed from a main method somewhere, so you'll have to modify that method to obtain the file from the provided arguments, and then somehow pass that into your Swing components.

On the other hand, if you're making a Swing application, you might as well forget the command-line and instead provide a way to invoke the JFileChooser to allow your user to graphically select a file on their system, and then proceed to load the contents into your JTextArea.

Another method that would be similar to providing command-line arguments would be to provide a JTextField that allows the user to type in the full path to the file.

I'd recommend just adding a "Load File" button above your JTextArea that will invoke JFileChooser.

Good luck!

  • How To Use File Choosers
0

精彩评论

暂无评论...
验证码 换一张
取 消