Example of using KeyListener |
package javamyframe; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; /** * @web http://java-buddy.blogspot.com/ */ public class JavaMyFrame extends JFrame implements KeyListener{ JTextArea textArea; JButton buttonClear; String s = ""; public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JavaMyFrame myFrame = new JavaMyFrame(); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.prepareUI(); myFrame.pack(); myFrame.setVisible(true); } private void prepareUI(){ textArea = new JTextArea(); textArea.setEditable(false); textArea.addKeyListener(this); JScrollPane panel = new JScrollPane(textArea); panel.setPreferredSize(new Dimension(300, 100)); buttonClear = new JButton("Clear"); buttonClear.addActionListener(anotherActionListener); getContentPane().add(panel, BorderLayout.CENTER); getContentPane().add(buttonClear, BorderLayout.PAGE_END); } ActionListener anotherActionListener = new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { s = ""; textArea.setText(s); } }; @Override public void keyTyped(KeyEvent e) { s += e.getKeyChar(); textArea.setText(s); } @Override public void keyPressed(KeyEvent e) {} @Override public void keyReleased(KeyEvent e) {} }
Related: Example of using ActionListener
No comments:
Post a Comment