•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the Java section within the Software Development category of DaniWeb, a massive community of 456,504 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,683 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Java advertiser: Lunarpages Java Web Hosting
Views: 1848 | Replies: 3
![]() |
Sun's tutorial is a good palce to start.
Tutorial: Writing a Key Listener
If you still have unanswered questions after that, just post them here
Tutorial: Writing a Key Listener
If you still have unanswered questions after that, just post them here
my key listener is on the last part...and i don't know what to do with it...
i'm suppose to add a key listener to this code...
i'm suppose to add a key listener to this code...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
class CalcGUI extends JPanel {
//=============================================== instance variables
//--- variable for GUI elements
private JTextField _displayField; // display result / input.
//--- variables representing state of the calculator
private boolean _startNumber = true; // true: num key next
private double _resultValue = 0.0; // result so far
private String _previousOp = "="; // previous operation
//end instance variables
//-------------------------------------------- static (class) variables
private static final Font BIGGER_FONT = new Font("monspaced",
Font.PLAIN, 24);
//======================================================constructor
public CalcGUI() {
//--- Display field
_displayField = new JTextField("0", 12);
_displayField.setHorizontalAlignment(JTextField.RIGHT);
_displayField.setFont(BIGGER_FONT);
//--- Clear button
JButton clearButton = new JButton("CLEAR");
clearButton.setFont(BIGGER_FONT);
clearButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
action_clear();
}
}
);
//--- Use one listener for all numeric keys.
ActionListener numListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
action_num(e); // process it below
}
};
//--- Layout numeric keys in a grid.
//--- Use the characters in a string as a guide
//--- for producing the numeric keys.
String buttonOrder = "789456123 0 ";
JPanel buttonPanel = new JPanel(new GridLayout(5, 3));
for (int i = 0; i < buttonOrder.length(); i++) {
String keyTop = buttonOrder.substring(i, i+1);
if (keyTop.equals(" ")) {
buttonPanel.add(new JLabel(""));
} else {
JButton b = new JButton(keyTop);
b.addActionListener(numListener);
b.setFont(BIGGER_FONT);
buttonPanel.add(b);
}
}
//--- Create an ActionListener that will be used for
//--- all of the operator buttons.
ActionListener opListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
action_op(e);
}//endmethod actionPerformed
};
//--- Create panel with gridlayout to hold operator buttons.
//--- Use array of button names to create buttons in a loop.
JPanel opPanel = new JPanel(new GridLayout(5, 1));
String[] opOrder = {"+", "-", "*", "/", "=","%"};
for (int i = 0; i < opOrder.length; i++) {
JButton b = new JButton(opOrder[i]);
b.addActionListener(opListener);
b.setFont(BIGGER_FONT);
opPanel.add(b);
}
JButton c= new JButton(".");
c.setFont(BIGGER_FONT);
opPanel.add(c);
/**c.addKeyListener( new KeyListener (){
public void keyPressed( KeyEvent e){
_displayField.setText(".");
}
});*/
//--- Layout this, the top level, panel.
this.setLayout(new BorderLayout());
this.add(_displayField, BorderLayout.NORTH );
this.add(buttonPanel , BorderLayout.CENTER);
this.add(opPanel , BorderLayout.EAST );
this.add(clearButton , BorderLayout.SOUTH );
this.add(MyPanel, BorderLayout.SOUTH);
}//end constructor
//============================================================ action_op
// Called by the action listener for all op buttons.
private void action_op(ActionEvent e) {
// The calculator is always in one of two states.
// 1. A number must be entered next (so this operator is wrong).
// 2. An operator must be entered next (so we're ok).
if (_startNumber) { // Error: needed number, not operator
action_clear();
_displayField.setText("ERROR");
} else {
_startNumber = true; // Next thing must be a number
try {
// Get the value from display field, convert it, do prev op
// If this is the first op, _previousOp will be =.
int currentValue =
Integer.parseInt(_displayField.getText());
double currentValuez = Double.parseDouble(_displayField.getText());
//int d=Integer.parseInt(c);
if (_previousOp.equals("=")) {
_resultValue = currentValue;
} else if (_previousOp.equals("+")) {
_resultValue += currentValuez;
} else if (_previousOp.equals("-")) {
_resultValue -= currentValuez;
} else if (_previousOp.equals("*")) {
_resultValue *= currentValuez;
} else if (_previousOp.equals("/")) {
_resultValue /= currentValue;
} else if (_previousOp.equals("%")) {
_resultValue %= currentValue;
}
_displayField.setText(""+_resultValue);
} catch (NumberFormatException ex) {
action_clear();
_displayField.setText("Error");
}
//--- set _previousOp for the next operator.
_previousOp = e.getActionCommand();
}//endif _startNumber
}//endmethod action_op
//======================================================== action_num
// Called by the action listener for numeric keys
private void action_num(ActionEvent e) {
String digit = e.getActionCommand(); // gets text from digitkey
if (_startNumber) {
// This is the first digit, clear field and set
_displayField.setText(digit);
_startNumber = false;
} else {
// Add this digit to the end of the display field
_displayField.setText(_displayField.getText() + digit);
}
}//endmethod action_num
//=============================================== logic action_clear
// Called by the action listener for the Clear button
public void action_clear() {
_startNumber = true;
_displayField.setText("0");
_resultValue = 0.0;
_previousOp = "=";
}//endmethod action_clear
}//endclass CalcGUI
class MyPanel extends JPanel implements KeyListener{
public MyPanel(){
this.setFocusable(true);
this.addKeyListener(this);
}
public void keyTyped(KeyEvent e){
char i = e.getKeyChar();
System.out.println("Key Typed: " + i);
}
public void keyPressed(KeyEvent e){
char i = e.getKeyChar();
System.out.println("Key Pressed: " + i);
}
public void keyReleased(KeyEvent e){
char i = e.getKeyChar();
System.out.println("Key Released: " + i);
}
}
![]() |
•
•
•
•
•
•
•
•
DaniWeb Java Marketplace
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
- adding keylistener (Java)
- How do I deal with multiple button presses with KeyListener? (Java)
- Java.io help!!! (Java)
- Key Press event Restriction (Java)
Other Threads in the Java Forum
- Previous Thread: Precasting in java
- Next Thread: Want help for Dijkstra algorithm




Linear Mode