when enter is hit add string to the end of the line - java

In my java code below it produces a frame with a jtextrea. This allows for simple text processing. All I want to do is add " Sam". Which is 5 spaces with sam at the end. Every time the user hits enter. You can see also the gif I added below which is exactly what I am looking for.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class text11 extends JFrame implements ActionListener {
// JFrame
static JFrame f;
// text area
static JTextArea jt;
// main class
public static void main(String[] args)
{
// create a new frame to store text field and button
f = new JFrame("textfield");
// create a label to display text
// create a object of the text class
text11 te = new text11();
// create a text area, specifying the rows and columns
jt = new JTextArea(" ", 20, 20);
JPanel p = new JPanel();
// add the text area and button to panel
p.add(jt);
f.add(p);
// set the size of frame
f.setSize(300, 300);
f.show();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

String actionKey = "ADD_SAM";
InputMap inputMap = jt.getInputMap(JComponent.WHEN_FOCUSED);
KeyStroke enterPressed = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
inputMap.put(enterPressed, actionKey);
jt.getActionMap().put(actionKey, new TextAction(actionKey) {
#Override
public void actionPerformed(ActionEvent e) {
jt.append(" Sam\n");
}
});

To get input so you know when the use hits enter, you have to create your own KeyListener class. If you don't know how to use it, here is a handy link from the documentation you can use: https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html.
But simply put, an KeyListener is an interface where you have to specify a few methods, but in your case I think the only one you need is keyPressed(KeyEvent e)(which is called pressed). If you're interested in the others, keyReleased(KeyEvent e) is when a key gets released, and keyType(KeyEvent e) is when it's pressed and released quickly. Then, use JFrames addKeyListener(KeyListener k) to add your custom action listener.
After you did that, you can use JTextArea's setText() and getText() method to append " sam" to the end (the 5 spaces get cut of by stack overflow, I know you want 5 spaces).
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {
jt.setText(jt.getText() + " sam");
}
}
If you added the KeyListener correctly, you should be fine!

Related

Need help understanding how a specific getter affects my program

I'm very new to coding(2 months) and i attempted to make Tic-Tac-Toe in java. I'm in a little over my head but i managed to create it using swing. My main problem is in the button1 class. I was going to use the getText() method but ended up not needing it or so i thought. I tried deleting it but as it turns out my tictactoe buttons don't switch letters without it. The compiler told me it overrides AbstractButton's getText() method but i don't see why that should matter since i never actually used it i thought. I'm thinking it's maybe a scope issue handled by it being overwritten somehow but i'm not sure. I was trying to use the text variable to update the button with setText() and that doesn't seem to work like i thought it should. I also don't understand why the 3 by 3 gridlayout seems to work properly most of the time but sometimes the number of buttons added is wrong.
So in summation the program works(mostly) but i'm not fully understanding how the button1 class is working.
TicTacToe.java
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class TicTacToe extends JFrame {
public static void main(String[] args) {
JFrame window = new JFrame("Tic-Tac-Toe");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setSize(600, 600);
window.setLayout(new GridLayout(3, 3));
ArrayList<button1> buttonArrayList = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
button1 newbutton = new button1();
buttonArrayList.add(newbutton);
window.add(buttonArrayList.get(i));
}
}
}
button1.java
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
public class button1 extends JButton {
int value = 0;
String text = "";
public button1() {
class ButtonAction extends AbstractAction {
public ButtonAction() {}
#Override
public void actionPerformed(ActionEvent Switcher) {
System.out.println(text + " " + value);
value++;//value is a relic from earlier attempts that i just felt like keeping.
if (text.equals("O")) {
text = "X";
} else if (text.equals("X")) {
text = "";
} else if (text.equals("")) {
text = "O";
}
}
}
this.setAction(new ButtonAction());
this.setText(text);
this.setFont(new Font("Arial",Font.PLAIN,120));
}
public String getText()// <----culprit
{
return text;
}
}
A JButton class has a methods defined for it, including setText() (which will set the displayed text on the button) and getText() (which will return the current text that is displayed on the button).
You created a class button1 (note: classes should start with Capital Letters).
You added an Action to the button1 class, which means that when the action is activated, something happens. Note that in that actionPerformed method, you should call setText(text) to update the displayed value.
You have also defined a getText() method that overrides the getText() method defined in JButton. This approach is fine if it is a conscious design decision. As it is, I think you should remove the getText() method from the button1 class, and allow the standard JButton class to handle the update. Right now, you are attempting to keep an instance variable text with the value, but it is possible for that instance variable to not be in alignment with the actual displayed value of the button (consider another class calling .setText() on the button).
EDIT: It is true that this referring to the JButton in the ButtonAction is not available. However, the Action itself contains the button that was pressed.
#Override
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
// if desired, String cur = btn.getText() may be called to find the
// current setting; get and process if needed
btn.setText(WHAT_EVER_TEXT);
}
Unless it is a specific requirement to process the current text, however (allowing selecting an O to an X to a blank), I would implement something to keep track of the current turn. This code is something I was experimenting with, and has good and bad points to it (as it is illustrative):
static class TurnController
{
// whose turn it is; start with X
private Player whoseTurn = Player.X;
// the instance variable
private static final TurnController instance = new TurnController();
private TurnController()
{
}
public static Player currentTurn()
{
return instance.whoseTurn;
}
public static Player nextTurn()
{
switch (instance.whoseTurn) {
case X:
instance.whoseTurn = Player.O;
break;
case O:
instance.whoseTurn = Player.X;
break;
}
return instance.whoseTurn;
}
public static String getMarkerAndAdvance()
{
String marker = currentTurn().toString();
nextTurn();
return marker;
}
enum Player
{
X,
O,
;
}
}
Using this TurnController, the actionPerformed becomes:
#Override
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
btn.setText(TurnController.getMarkerAndAdvance());
}
and the Button1 class may have the String text instance variable removed.
What you have tried is Try to make a Custom Button Class and its EventHandler just by extending AbstractAction namee button1 as we See in Your Question.
You have Override the method actionPerformed(ActionEvent Switcher) which actually belongs to Class AbstractAction by your own definition (What should Performed on Action Event of Every Button).
class ButtonAction extends AbstractAction {
public ButtonAction() {}
#Override
public void actionPerformed(ActionEvent Switcher) { // Your Definition For actionPerformed..
System.out.println(text + " " + value);
value++;//value is a relic from earlier attempts that i just felt like keeping.
if (text.equals("O")) {
text = "X";
} else if (text.equals("X")) {
text = "";
} else if (text.equals("")) {
text = "O";
}
}
}
this.setAction(new ButtonAction()); // add ActionListener to each Button.
this.setText(text); // Setting Text to each Button
this.setFont(new Font("Arial",Font.PLAIN,120)); //add Font to each Button.
}
Now In this Code.
ArrayList buttonArrayList = new ArrayList<>();
for (int i = 0; i < 9; i++) {
button1 newbutton = new button1(); // Creating 9 new buttons.
buttonArrayList.add(newbutton); // add each button into the ArrayList.
window.add(buttonArrayList.get(i)); // each Button to the the AWT Window.
}
Above Code will generate 9 Button and add it to Your AWT Window. each button have actionPerformed() method which contains the overrided Definition.
Now Each button will performed action as per the definition you give to actionPerformed() Method.
Thank You.

Return to previous control when pressing BACKSPACE

I have looked at many sites and did not get a result. I have some JTextFields that only accept one character. What I need is that when I press BACKSPACE that character is cleared and the focus returns to the previous JTextField and so on. I added a KeyListener to all JTextFields and try KeyTyped, KeyReleased and KeyPressed events but none worked. The code below:
jt.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent evt) {
char c = evt.getKeyChar();
if(Character.isLetter(c) || Character.isISOControl(c))
{
evt = evt;
} else
evt.consume();
}
public void keyReleased(KeyEvent evt) {
if(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE)
{
robot.keyPress(KeyEvent.VK_BACK_SPACE);
robot.keyRelease(KeyEvent.VK_BACK_SPACE);
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_SHIFT);
}
}
});
Thanks for any help.
Don't use a KeyListener. Swing was designed to be used with Key Bindings.
Don't use the Robot. The API has a method that allows you to transfer focus.
Here is the basic code for the Key Binding:
textField.getInputMap().put(KeyStroke.getKeyStroke("BACK_SPACE"), "backspace");
textField.getActionMap().put("backspace", new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
Component c = (Component)e.getSource();
c.transferFocusBackward();
}
});
I have some JTextFields that only accept one character.
You may also want to look at Text Field Auto Tab. It is a class that will allow you to automatically tab to the next text field when a character is entered.
I've quickly made a small app that hopefully solved your problem, here's the entire code:
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BackspaceTest extends JFrame implements KeyListener {
// In this example I've used 4 Text Fields, each of which takes 1 character
private JTextField text1, text2, text3, text4;
// I've stored the Text Fields in a ArrayList so we can easily shuffle trough them later
private ArrayList<JTextField> fieldList = new ArrayList<>();
// Numerical value for tracking the currently focused TextField
private int focusIndex;
// This constructor is the first thing that gets called from main
public BackspaceTest() {
init();
}
private void init() {
// Initialize the text fields with 1 character column size
text1 = new JTextField(1);
text2 = new JTextField(1);
text3 = new JTextField(1);
text4 = new JTextField(1);
// Key listeners for implementing 1 character limitations and Backspace functionality
text1.addKeyListener(this);
text2.addKeyListener(this);
text3.addKeyListener(this);
text4.addKeyListener(this);
// The focus listener keeps track of currently focused Text Fields
text1.addFocusListener(new TextFocusListener());
text2.addFocusListener(new TextFocusListener());
text3.addFocusListener(new TextFocusListener());
text4.addFocusListener(new TextFocusListener());
// The default focus is on the first field
text1.requestFocus();
fieldList.add(text1);
fieldList.add(text2);
fieldList.add(text3);
fieldList.add(text4);
// Puts the items on the screen
createLayout(text1, text2, text3, text4);
setTitle("Backspace Test");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
JPanel panel = (JPanel) getContentPane();
GroupLayout gl = new GroupLayout(panel);
panel.setLayout(gl);
gl.setAutoCreateContainerGaps(true);
gl.setAutoCreateGaps(true);
gl.setHorizontalGroup(gl.createSequentialGroup()
.addComponent(arg[0])
.addComponent(arg[1])
.addComponent(arg[2])
.addComponent(arg[3])
);
gl.setVerticalGroup(gl.createParallelGroup()
.addComponent(arg[0])
.addComponent(arg[1])
.addComponent(arg[2])
.addComponent(arg[3])
);
gl.linkSize(text1, text2, text3, text4);
pack();
}
class TextFocusListener implements FocusListener {
#Override
public void focusGained(FocusEvent e) {
focusIndex = fieldList.indexOf(getFocusOwner());
System.out.println(focusIndex);
}
#Override
public void focusLost(FocusEvent e) { }
}
#Override
public void keyTyped(KeyEvent e) { }
#Override
public void keyPressed(KeyEvent e) {
JTextField focusedText = fieldList.get(focusIndex);
// Check if BACKSPACE is pressed and if Text Field is empty and if it's not the first field
if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE &&
focusedText.getText().equals("") &&
focusIndex > 0) {
fieldList.get(--focusIndex).requestFocus();
}
}
#Override
public void keyReleased(KeyEvent e) {
// This limits the amount of characteres to 1. I'm not fully pleased with it but it works for this demonstration
if (text1.getText().length() >= 1)
text1.setText(text1.getText().substring(0, 1));
if (text2.getText().length() >= 1)
text2.setText(text2.getText().substring(0, 1));
if (text3.getText().length() >= 1)
text3.setText(text3.getText().substring(0, 1));
if (text4.getText().length() >= 1)
text4.setText(text4.getText().substring(0, 1));
}
// Here's where the program starts
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new BackspaceTest().setVisible(true);
}
});
}
});
If you don't have time to run it, look at the line 96, I think the Focus Listener is a good way to solve your problem. Hope this helps you out, good luck!

java take mouse coordinates from natural screen and display them in a GUI [duplicate]

This question already has an answer here:
How do I make my JWindow window always stay focused
(1 answer)
Closed 7 years ago.
First of all i don't know good english.
I want to make a window and have 2 labels and 2 fields. One label for x-coordinate and 1 for y-coordinate.Fields will show the x-y coordinates.
Coordinates are from mouse from full screen (meaning outside from window).
I prefer to be on clicking but i have read from other answers and questions that this will not act as we want (because it loses focus).So i tried not to be on clicking
I want help with my code because it has 2 problems-mistakes:
1) window can't close
2)when mouse is not moving fields take the same coordinates forever and i want take 1 time the coordinates and don't take the same until it moves.
here is the full code:
package mouseClick;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MouseEventDemo extends Frame implements MouseListener {
// Private variables
private TextField tfMouseX; // mouse-click-x
private TextField tfMouseY; // mouse-click-y
// Constructor
public MouseEventDemo() {
//handle the close-window button.
WindowDestroyer listener =new WindowDestroyer();
addWindowListener(listener);
setLayout(new FlowLayout()); // sets layout
// Label
add(new Label("X-Click: ")); // adds component
// TextField
tfMouseX = new TextField(10); // 10 columns
tfMouseX.setEditable(false); // read-only
add(tfMouseX); // adds component
// Label
add(new Label("Y-Click: ")); // adds component
// TextField
tfMouseY = new TextField(10);
tfMouseY.setEditable(false); // read-only
add(tfMouseY); // adds component
// fires the MouseEvent
addMouseListener(this);
setTitle("MouseEvent Demo"); // sets title
setSize(350, 100); // sets initial size
setVisible(true); // shows
}
public static void main(String[] args) {
new MouseEventDemo();
}
// MouseEvent handlers
public void mouseClicked(MouseEvent e) {
while (true){
tfMouseX.setText(Integer.toString(xmouse()));
tfMouseY.setText(Integer.toString(ymouse()));
}
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public class WindowDestroyer extends WindowAdapter {
public void windowClosing (WindowEvent e) {
System.exit(0);
}
}
public int xmouse() {
Point simiox = MouseInfo.getPointerInfo().getLocation();
int x= (int) simiox.getX();
return x;
}
public int ymouse() {
Point simioy = MouseInfo.getPointerInfo().getLocation();
int y=(int) simioy.getY();
return y;
}
}
in order to close the window, use
windowVariable.seDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
where windowVariable is the variable for you JFrame
EDIT:
For returning the value only once, try using a for loop and a hasMoved boolean. For instance,
for (int i = 0; i < 1; i++){
tfMouseX.setText(Integer.toString(xmouse()));
if (hasMoved == true)
i = -1;
}
then do the same for the y.
this basically checks to see if the mouse has moved, and if it has not, it will set the label only once. If it has, it will update the label.

Swing - Thread.sleep() stop JTextField.setText() working [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
using sleep() for a single thread
I'm having issues with JTextField.setText() when using Thread.sleep(). This is for a basic calculator I'm making. When the input in the input field is not of the correct format I want "INPUT ERROR" to appear in the output field for 5 seconds and then for it to be cleared. The setText() method did work when I just set the text once to "INPUT ERROR" and by printing out the text in between I found it does work with both that and the setText("") one after the other. The problem arises when I put the Thread.sleep() between them.
Here's a SSCCE version of the code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Pattern;
import javax.swing.*;
public class Calc {
static Calc calc = new Calc();
public static void main(String args[]) {
GUI gui = calc.new GUI();
}
public class GUI implements ActionListener {
private JButton equals;
private JTextField inputField, outputField;
public GUI() {
createFrame();
}
public void createFrame() {
JFrame baseFrame = new JFrame("Calculator");
baseFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
BoxLayout layout = new BoxLayout(contentPane, BoxLayout.Y_AXIS);
contentPane.setLayout(layout);
baseFrame.setContentPane(contentPane);
baseFrame.setSize(320, 100);
equals = new JButton("=");
equals.addActionListener(this);
inputField = new JTextField(16);
inputField.setHorizontalAlignment(JTextField.TRAILING);
outputField = new JTextField(16);
outputField.setHorizontalAlignment(JTextField.TRAILING);
outputField.setEditable(false);
contentPane.add(inputField);
contentPane.add(outputField);
contentPane.add(equals);
contentPane.getRootPane().setDefaultButton(equals);
baseFrame.setResizable(false);
baseFrame.setLocation(100, 100);
baseFrame.setVisible(true);
}
/**
* When an action event takes place, the source is identified and the
* appropriate action is taken.
*/
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == equals) {
inputField.setText(inputField.getText().replaceAll("\\s", ""));
String text = inputField.getText();
System.out.println(text);
Pattern equationPattern = Pattern.compile("[\\d(][\\d-+*/()]+[)\\d]");
boolean match = equationPattern.matcher(text).matches();
System.out.println(match);
if (match) {
// Another class calculates
} else {
try {
outputField.setText("INPUT ERROR"); // This doesn't appear
Thread.sleep(5000);
outputField.setText("");
} catch (InterruptedException e1) {
}
}
}
}
}
}
I'm not actually using a nested class but I wanted it to be able to be contained in one class for you. Sorry about how the GUI looks but again this was to cut down the code. The the important section (if (e.getSource() == equals)) remains unchanged from my code. The simplest way to give an incorrect input is to use letters.
When you use Thread.sleep() you're doing it on the main thread. This freezes the gui for five seconds then it updates the outputField. When that happens, it uses the last set text which is blank.
It's much better to use Swing Timers and here's an example that does what you're trying to accomplish:
if (match) {
// Another class calculates
} else {
outputField.setText("INPUT ERROR");
ActionListener listener = new ActionListener(){
public void actionPerformed(ActionEvent event){
outputField.setText("");
}
};
Timer timer = new Timer(5000, listener);
timer.setRepeats(false);
timer.start();
}
As Philip Whitehouse states in his answer, you are blocking the swing Event Dispatch Thread with the Thread.sleep(...) call.
Given that you've taken the time to set up an ActionListener already, it would probably be easiest to use a javax.swing.Timer to control clearing the text. To do this, you could add a field to your GUI class:
private Timer clearTimer = new Timer(5000, this);
In the constructor for GUI, turn off the repeats feature, as you really only need a one-shot:
public GUI() {
clearTimer.setRepeats(false);
createFrame();
}
Then, actionPerformed can be modified to use this to start the timer/clear the field:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == equals) {
inputField.setText(inputField.getText().replaceAll("\\s", ""));
String text = inputField.getText();
System.out.println(text);
Pattern equationPattern = Pattern.compile("[\\d(][\\d-+*/()]+[)\\d]");
boolean match = equationPattern.matcher(text).matches();
System.out.println(match);
if (match) {
// Another class calculates
} else {
clearTimer.restart();
outputField.setText("INPUT ERROR"); // This doesn't appear
}
} else if (e.getSource() == clearTimer) {
outputField.setText("");
}
}
You're doing a Thread.sleep() in the Swing main thread. This is NOT good practice. You need to use a SwingWorker thread at best.
What's happening is that it's running the first line, hitting Thread.sleep().
This prevents the (main) EDT thread from doing any of the repaints (as well as preventing the next line executing).
You should use a javax.swing.Timer to setup the delayed reaction and not put sleep() calls in the main thread.

Removing new line function when enter button is pressed Java

I have a text area that I would like to become blank when the enter button is pressed. I know this would normally be done with a setText method. However when I do this, the text is removed but the new line function created by the return key being pressed. My question is, is the anyway of stopping this default action from happening?
thanks
Are you listening for the ENTER key on the text area and then clearing it? The following works for me:
final JTextArea ta = new JTextArea();
ta.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
ta.setText("");
}
}
#Override
public void keyPressed(KeyEvent e) {
}
});
Hi
I have a text area that I would like to become blank when the enter button is pressed.
This, I understand. Here's how you can do that:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main {
public static void main(String[]args) {
final JFrame frame = new JFrame();
final JTextArea area = new JTextArea();
area.setPreferredSize(new Dimension(200, 200));
area.addKeyListener(new KeyAdapter(){
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
area.setText("");
}
}
});
frame.add(area);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
I know this would normally be done with a setText method. However when I do this, the text is removed but the new line function created by the return key being pressed. My question is, is the anyway of stopping this default action from happening?
That, I don't understand.
The problem is probably that you are not consuming the keystroke event, and although the text area is cleared, the normal processing of the keystroke ends up inserting a newline.
Rather than trapping the keystroke event (which isn't necessarily portable) I would recommend using a DocumentFilter. There is a tutorial here that shows you how to write one. Implement the filter so that when there is a 'newline' in the insert or replace string, replace the entire contents of the document with "".
However this approach can't tell the difference between a newline typed at the keyboard and one pasted into the text area.
Before you clear the text you need to remove the new line code the return button left. You do that with the consume() method.
So to clear your text:
yourkeyevent.consume();
yourTextObject.setText("");
Instead, you can also use:
yourTextarea.setText(null);
yourTextarea.setCaretPosition(-1);
I solved your problem overriding the code in the method "public void keyTyped(KeyEvent e)" instead of "public void keyPressed(KeyEvent e)" and it works.
Here the code:
package versione1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class WhiteEnter {
final JFrame frame = new JFrame();
private JTextArea area = new JTextArea();
public static void main(String[]args) {
WhiteEnter prova = new WhiteEnter();
prova.run();
}
public void run(){
area.setPreferredSize(new Dimension(200, 200));
area.addKeyListener(new PressEnterKeyListener());
frame.add(area);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public class PressEnterKeyListener implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == (KeyEvent.VK_ENTER)){
try{
area.setText(null);
area.setCaretPosition(0);
} catch(Exception ex){
ex.printStackTrace();
}
}
}
}
}

Categories

Resources