2015-10-04 77 views
0

所以我不想讓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) 
+2

千萬不要永遠不要將KeyListener添加到JTextField。永遠。改用ActionListener,因爲這樣當用戶輸入數據時,監聽器可以響應,然後按''。但是,就像@AndyTurner提到的那樣,你試圖打開一個不存在的文件。 –

+1

呃,你試圖打開的文件是否存在?該文件的名稱是什麼? –

+0

也可以在**用戶有機會輸入任何內容之前從JTextField **中獲取文本。 –

回答

2

下面在棧跟蹤消息,

at com.parth.Console.keyPressed(Console.java:52) 

這相當於以下行(假設你有2個行額外的在您的實際代碼(包聲明之後新線?)),

desktop.open(file); 

Javadoc說你會使用時獲得一個IllegalArgumentExceptionopen方法Desktop文件不存在時的類。

command.addKeyListener(this); 

您:

IllegalArgumentException - if the specified file doesn't exist

調用open方法和驗證,如果你試圖打開該文件實際上存在

+0

沒錯。 1+ –

4

一些問題,你的代碼之前,請做file.getName()打印我們希望避免使用KeyListeners來處理大多數與Swing鍵相關的代碼,因爲它是低級偵聽器,只有當組件具有焦點時纔會激活。更多的問題是在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,迫使你創建和顯示JFrames畫自己在一個角落裏,當往往更多的靈活性要求。事實上,我敢打賭,我已經創建了大多數Swing GUI代碼,而且我已經看到了而不是擴展了JFrame,事實上很少有人會想要這樣做。更常見的是,您的GUI類將專門用於創建JPanel,然後可將其放置到JFrame或JDialogs或JTabbedPanes中,或在需要時通過CardLayouts進行交換。這將大大增加您的GUI編碼的靈活性。

此外,您將不希望您的GUI類實現您的監聽器接口,因爲這會給課程帶來太多不同的責任。無論是使用匿名內部類還是私有內部類,或者如果您的偵聽器涉及單獨的獨立類。


你想要做的是再次使用ActionListener,並根據用戶輸入的內容改變其狀態。如果用戶輸入「open」,則可能將openFile布爾值設置爲true,並且在偵聽器中如果爲true,則在下一次調用actionPerformed時,將使用獲得的字符串打開文件。或者你可以使用枚舉來保存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

*「..顯示一個JFileChooser以允許用戶選擇一個現有的文件。」*可惜的是,建議被掩埋在這個優秀答案的底部。如果某些應用程序希望我輸入一個文件名,我想要把程序員打倒在頭上。 *「不會有人想到這個**最終用戶嗎?」(說着一邊扭着手,一邊擔心地皺着眉頭)。 –