Swing- TextArea.append没有触发

时间:2016-07-09 15:27:15

标签: java swing keylistener keylogger

正如标题所说。摆动textArea并未发射。我使用getter从主KeyGUI类中获取组件。在下面的代码中是"主类":

public class KeyGUI {

/*
 * Version: 1.0
 * 
 * I have declared instance variables: frame, textArea and btnSave.
 * I also made 3 methods called: guiLayout and guiSettings, guiListeners
 * I will explain everything in details in their respective bodies.
 */
JFrame frame = new JFrame();    
JTextArea textArea = new JTextArea();
JButton btnSave = new JButton("Save log");

public void guiListeners() {

    /*
     * Version: 1.0
     * 
     * I have made this method.
     * It's primary use is to set all kinds of listeners that
     * GUI components need. 
     * Added KeyListener to textArea and added ActionListener to btnSave.
     */

    Logger loggerObj = new Logger();
    textArea.addKeyListener(loggerObj.getE());

    btnSave.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            String text = textArea.getText();

            String fileName = JOptionPane.showInputDialog("Input the name of your file:");
            File fileDir = new File(FileSystemView.getFileSystemView().getDefaultDirectory().getPath().toString() + "/Logger/");
             if (!fileDir.exists()) {
                 fileDir.mkdir();
             }
            File fileLoc = new File(FileSystemView.getFileSystemView().getDefaultDirectory().getPath().toString() + "/Logger/" + fileName + ".txt");

            BufferedWriter bw = null;

            try {
                FileWriter fw = new FileWriter(fileLoc);
                bw = new BufferedWriter(fw);
                text = text.replaceAll("(?!\\r)\\n", "\r\n");
                bw.write(text);
            } catch (IOException e1) {
                System.err.println(e1 + "IOException at line 98");
            } finally {
                if (bw != null) {
                    try {
                        bw.close();
                    } catch (IOException e2) {
                        System.err.println(e2 + "Error closing buffered reader at line 104");
                    }
                }
            }
        }

    });
}

public void guiLayout() {

/*
 * Version: 1.0
 * 
 * Methods created.
 * This method is used only for setting the layout for GUI and it's components.
 * Using springLayout I was able to completely manipulate look of GUI.
 * Only textArea and btnSave are added. Only ones needed anyway.    
 */
SpringLayout springLayout = new SpringLayout();
frame.getContentPane().setLayout(springLayout);

springLayout.putConstraint(SpringLayout.NORTH, textArea, 10, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, textArea, 10, SpringLayout.WEST, frame.getContentPane());
springLayout.putConstraint(SpringLayout.SOUTH, textArea, 192, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, textArea, -10, SpringLayout.EAST, frame.getContentPane());
frame.getContentPane().add(textArea);

springLayout.putConstraint(SpringLayout.WEST, btnSave, 170, SpringLayout.WEST, frame.getContentPane());
springLayout.putConstraint(SpringLayout.SOUTH, btnSave, -10, SpringLayout.SOUTH, frame.getContentPane());
frame.getContentPane().add(btnSave);
}

public void guiSettings() {

/*
 * Version: 1.0
 * 
 * Method created.
 * This method is used only for settings for GUI and it's components.
 * I have setVisibility of frame on true allowing it to be visible and have set size
 * of frame on x: 300 y: 300. I have set background of textArea to light gray color and set it's editability
 * on false. Since it's made to precisely log every key.    
 */
    frame.setVisible(true);
    frame.setSize(300, 300);

    textArea.setBackground(Color.LIGHT_GRAY);
    textArea.setEditable(false);
}

public JFrame getFrame() {
//This is one of getters which returns JFrame
    return frame;
}

public JTextArea getTextArea() {
//This is one of getters which returns JTextArea    
    return textArea;
}

public JButton getBtnSave() {
//This is one of getters which returns JButton  
    return btnSave;
}

public static void main(String[] args) {
/*
 * This is main method of the program.
 * 
 * Version: 1.0
 * 
 * I have made KeyGUI object and assigned all methods to it.
 */
    KeyGUI keyGUIobj = new KeyGUI();
    Logger loggerObj = new Logger();
    keyGUIobj.getBtnSave();
    keyGUIobj.getFrame();
    keyGUIobj.getTextArea();

    keyGUIobj.guiLayout();
    keyGUIobj.guiSettings();
    keyGUIobj.guiListeners();

    loggerObj.getE();
}
}

(是的,它是一种个人密钥记录器),反正我也做了Logger类。这将使用KeyListener来检查按下了哪个键:

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Logger {

KeyGUI keyGUIObject = new KeyGUI();

KeyListener e = new KeyListener() {

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
        case KeyEvent.VK_ESCAPE:
            System.out.println("Esc");
            keyGUIObject.getTextArea().append("Esc");
            break;
        case KeyEvent.VK_F1:
            System.out.println("F1");
            break;
        case KeyEvent.VK_F2:
            System.out.println("F2");
            break;
        case KeyEvent.VK_F3:
            System.out.println("F3");
            break;
        case KeyEvent.VK_F4:
            System.out.println("F4");
            break;
        case KeyEvent.VK_F5:
            System.out.print("F5");
            break;
        case KeyEvent.VK_F6:
            System.out.println("F6");
            break;
        case KeyEvent.VK_F7:
            System.out.println("F7");
            break;
        case KeyEvent.VK_F8:
            System.out.println("F8");
            break;
        case KeyEvent.VK_9:
            System.out.println("F9");
            break;
        case KeyEvent.VK_F10:
            System.out.println("F10");
            break;
        case KeyEvent.VK_F11:
            System.out.println("F11");
            break;
        case KeyEvent.VK_F12:
            System.out.println("F12");
            break;
        case KeyEvent.VK_PRINTSCREEN:
            System.out.println("Print Sc");
            break;
        case KeyEvent.VK_SCROLL_LOCK:
            System.out.println("Scr lock");
            break;
        case KeyEvent.VK_PAUSE:
            System.out.println("Pause");
            break;
        case KeyEvent.VK_INSERT:
            System.out.println("Insert");
            break;
        case KeyEvent.VK_DELETE:
            System.out.println("Delete");
            break;
        case KeyEvent.VK_PAGE_UP:
            System.out.println("PgUp");
            break;
        case KeyEvent.VK_PAGE_DOWN:
            System.out.print("PgDown");
            break;
        case KeyEvent.VK_DEAD_TILDE:
            System.out.println("Tilde");
            break;
        case KeyEvent.VK_1:
            System.out.println("1");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

};

public KeyListener getE() {
    return e;
}

}

我已经制作了System.out.println("Esc"),以防万一它被解雇了。因为在控制台中它确实显示Esc。所以我想我注册了一些错误。

1 个答案:

答案 0 :(得分:1)

你的设计已关闭。

在main()方法中,您有代码:

KeyGUI keyGUIobj = new KeyGUI();
Logger loggerObj = new Logger();

在Logger类中你有:

KeyGUI keyGUIObject = new KeyGUI();

所以你要创建同一个类的多个实例。

为了简化设计,Logger类应该implement KeyListener接口。然后就不需要getter / setter或访问KeyGUI类。

然后在创建文本区域时在主类中,您只需使用以下代码:

JTextArea textArea = new JTextArea(5, 10);
textArea.addKeyListener( new Logger() );

我建议您查看How to Write a Key Listener上Swing教程中有关工作示例和更好结构化代码的部分。