所以我不希望textfeild打开一个文本文件,读取它,并将其内容复制到其中。我不希望这样。
我想知道的是如何使用此文本字段打开任何类型的文件。我已经尝试过这段代码,但它不起作用:
import java.awt.event.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.swing.*;
@SuppressWarnings("serial")
public class Console extends JFrame implements KeyListener{
TextArea c = new TextArea("", 30,30, TextArea.SCROLLBARS_VERTICAL_ONLY);
JTextField command = new JTextField(2);
public Console(String title) {
super(title);
c.setEditable(false);
c.setBackground(Color.BLACK);
c.setForeground(Color.GREEN);
c.setFont(new Font("Courier", 12, 16));
c.setText("Booted up the console" + "\n" + "Enter a command...");
command.setBackground(Color.BLACK);
command.setForeground(Color.GREEN);
command.setFont(new Font("Courier", 12, 16));
add(c, BorderLayout.PAGE_START);
add(command, BorderLayout.PAGE_END);
command.addKeyListener(this);
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
String COMMAND = command.getText();
String otherCommand = command.getText();
Desktop desktop = Desktop.getDesktop();
File file = new File(otherCommand);
String f = file.toString();
if (COMMAND.equals("open")) {
c.append("\n" + "Enter file to open:");
if(otherCommand.equals(f)) {
try {
desktop.open(file);
} catch (IOException e1) {
c.append("Invalid file location");
}
}
}
if (COMMAND.equals("exit")) {
c.append("\n" + "Exiting...");
System.exit(0);
}
}
}
public void windowActivated(WindowEvent e){
}
public void windowDeactivated(WindowEvent e){
}
public void windowIconified(WindowEvent e){
}
public void windowDeiconified(WindowEvent e){
}
public void windowOpened(WindowEvent e){
}
public void windowClosing(WindowEvent e){
System.exit(0);
}
public void windowClosed(WindowEvent e){
System.exit(0);
}
}
我遇到的主要问题是这段代码:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
String COMMAND = command.getText();
String otherCommand = command.getText();
Desktop desktop = Desktop.getDesktop();
File file = new File(otherCommand);
String f = file.toString();
if (COMMAND.equals("open")) {
c.append("\n" + "Enter file to open:");
if(otherCommand.equals(f)) {
try {
desktop.open(file);
} catch (IOException e1) {
c.append("Invalid file location");
}
}
}
if (COMMAND.equals("exit")) {
c.append("\n" + "Exiting...");
System.exit(0);
}
}
}
我收到此错误:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: open doesn't exist.
at java.awt.Desktop.checkFileValidation(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
at com.parth.Console.keyPressed(Console.java:52)
at java.awt.Component.processKeyEvent(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
答案 0 :(得分:4)
您的代码存在一些问题:
command.addKeyListener(this);
对于大多数与Swing密钥相关的代码,您将希望避免使用KeyListener,因为它是一个低级侦听器,并且仅在组件具有焦点时才处于活动状态。更多的问题是在JTextField中使用它,因为这样做可以阻止JTextField的一些关键核心行为。最好使用DocumentListener,但实际上在你的情况下,使用ActionListener要好得多。
关于:
String COMMAND = command.getText();
String otherCommand = command.getText();
Desktop desktop = Desktop.getDesktop();
File file = new File(otherCommand);
String f = file.toString();
if (COMMAND.equals("open")) {
c.append("\n" + "Enter file to open:");
if (otherCommand.equals(f)) {
try {
desktop.open(file);
} catch (IOException e1) {
c.append("Invalid file location");
}
}
}
在这里,您需要在用户输入任何新文本之前从命令JTextField 获取文本。
关于:
public class Console extends JFrame implements KeyListener {
通过让您的类扩展JFrame,迫使您创建和显示JFrame,通常需要更多的灵活性,您在角落里画画。事实上,我冒昧地说,我创建的大部分Swing GUI代码和我见过的不扩展了JFrame,事实上你很少想做这个。更常见的是,您的GUI类将面向创建JPanels,然后可以将其放置到JFrames或JDialogs或JTabbedPanes中,或者在需要时通过CardLayouts交换。这将大大提高GUI编码的灵活性。
此外,您将不希望您的GUI类实现您的侦听器接口,因为这会给类一个太多不同的责任。要么使用匿名内部类,要么使用私有内部类,或者如果要为侦听器使用单独的独立类。
您要做的是再次使用ActionListener,并根据用户输入的内容更改其状态。如果用户输入“open”,则可能将openFile boolean设置为true,并且在侦听器内,如果为true,则在下次调用actionPerformed
时,获取的String将用于打开文件。或者您可以使用枚举来保存ActionListener的状态。例如:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.*;
public class Console2 extends JPanel {
private static final String INTRO_TEXT = "Booted up the console" + "\n"
+ "Enter a command...\n";
private static final String ENTER_FILE_PROMPT = "Enter file to open:\n";
private static final String OPEN = "open";
private static final String EXIT = "exit";
public static final String USER_PROMPT = "User > ";
private JTextArea textArea = new JTextArea(INTRO_TEXT, 20, 40);
private JTextField inputField = new JTextField();
public Console2() {
// have text area wrap lines
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
// have it not get focus
textArea.setFocusable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// ***** this is it! Add an ActionListener to our JTextField. *****
inputField.addActionListener(new InputListener());
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(inputField, BorderLayout.PAGE_END);
}
// listener state
enum InputState {
GETTING_COMMAND, OPEN_FILE
}
private class InputListener implements ActionListener {
private InputState state = InputState.GETTING_COMMAND;
@Override
public void actionPerformed(ActionEvent e) {
// get input text and clear the field
String inputText = inputField.getText().trim();
inputField.setText("");
textArea.append(USER_PROMPT + inputText + "\n");
if (state == InputState.GETTING_COMMAND) {
if (OPEN.equalsIgnoreCase(inputText)) {
state = InputState.OPEN_FILE; // change the listener's state
textArea.append(ENTER_FILE_PROMPT); // prompt user
}
if (EXIT.equalsIgnoreCase(inputText)) {
Window window = SwingUtilities
.getWindowAncestor(Console2.this);
window.dispose();
}
} else if (state == InputState.OPEN_FILE) {
state = InputState.GETTING_COMMAND; // reset
Desktop desktop = Desktop.getDesktop();
File file = new File(inputText);
if (!file.exists()) {
Component parentComponent = Console2.this;
Object message = "File " + file.toString()
+ " does not exist";
String title = "Error Attempting to Open File";
int messageType = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(parentComponent, message,
title, messageType);
} else {
try {
desktop.open(file);
} catch (IOException e1) {
Component parentComponent = Console2.this;
Object message = e1.getMessage();
String title = "Error Attempting to Open File";
int messageType = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(parentComponent, message,
title, messageType);
e1.printStackTrace();
}
}
}
}
}
private static void createAndShowGui() {
Console2 mainPanel = new Console2();
JFrame frame = new JFrame("Console2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
另一种选择是当输入“打开”时,显示JFileChooser以允许用户选择现有文件。
答案 1 :(得分:2)
堆栈跟踪中的消息,
at com.parth.Console.keyPressed(Console.java:52)
这对应于下面的行(假设你的实际代码中还有2行额外的(包声明后跟新行?),
desktop.open(file);
Javadoc表示当文件不存在时,使用IllegalArgumentException
类open
方法时,您将获得Desktop
。
IllegalArgumentException - 如果指定的文件不存在
请在调用file.getName()
方法之前打印open
,并验证您尝试打开的文件是否确实存在