KeyListener anomoly: delay in firing KeyEvent

Hello,
I've implemented a KeyListener that's exhibiting some anomolies. I'm using it in a video game. I'm using it to control the main character's movement. It determines his movement based on strokes of the arrow keys. I've programmed it so that only one key has an effect at a time. That is, so long as (say) the up arrow was pressed first and held down, the character moves up, and no other key has an effect. Other keys only have an effect if the up arrow is released.
The anomoly comes about when two keys are held down (only one of them determining the movement of the character - which ever was first), and then the first is released. When the first is released (but the second is still held down), the character freezes for about a second, and only after that second does he move in the direction of the second key which is still held down.
It's this second-long delay which is the anomoly. I'm guessing it results from the fact that the KeyEvent is not being fired constantly or immediately after the release of the first key. Even though the second key is held down, it takes a second to fire the KeyEvent after the first key is released (though it seems to fire immediately upon depressing the key).
I'm wondering if there's a way to get rid of the delay or at least shorten it so it's not noticeable.
Here's my KeyListener code:
import java.awt.event.*;
public class InputProcessor implements KeyListener {
    // key codes
    public static final int      LEFT  = 37;
    public static final int      UP    = 38;
    public static final int      RIGHT = 39;
    public static final int      DOWN  = 40;
    private boolean      left_arrow_down  = false;
    private boolean      right_arrow_down = false;
    private boolean      up_arrow_down    = false;
    private boolean      down_arrow_down  = false;
    // flag to mark when a key (any key) is pressed
    private boolean     key_pressed      = false;
    public InputProcessor() {}
    public void keyPressed (KeyEvent KE) {
     if (key_pressed) return; // all other keys disabled if one key is down
     switch (KE.getKeyCode()) {
         case LEFT:
          left_arrow_down true;
          key_pressed = true;
          break;
         case RIGHT:
          right_arrow_down = true;
          key_pressed = true;
          break;
         case UP:
          up_arrow_down = true;
          key_pressed = true;
          break;
         case DOWN:
          down_arrow_down = true;
          key_pressed = true;
          break;
    public void keyReleased (KeyEvent KE) {
     switch (KE.getKeyCode()) {
         case LEFT:
          left_arrow_down = false;
          break;
         case RIGHT:
          right_arrow_down = false;
          break;
         case UP:
          up_arrow_down = false;
          break;
         case DOWN:
          down_arrow_down = false;
          break;
     // only set key_pressed to false if all keys have been released
     if (!left_arrow_down &&
       !right_arrow_down &&
       !up_arrow_down &&
       !down_arrow_down)
         key_pressed = false;
    public void keyTyped (KeyEvent KE) {}
    public boolean isLeftArrowDown()  {return left_arrow_down;}
    public boolean isUpArrowDown()    {return up_arrow_down;}
    public boolean isRightArrowDown() {return right_arrow_down;}
    public boolean isDownArrowDown()  {return down_arrow_down;}
    public static void main (String[] args) {
     InputProcessor IP = new InputProcessor();
}I'm wondering if there might be a command I can execute at the end of the keyReleased() method, something like this:
    public void keyReleased (KeyEvent KE) {
     switch (KE.getKeyCode()) {
         case LEFT:
          left_arrow_down = false;
          break;
         case RIGHT:
          right_arrow_down = false;
          break;
         case UP:
          up_arrow_down = false;
          break;
         case DOWN:
          down_arrow_down = false;
          break;
     // only set key_pressed to false if all keys have been released
     if (!left_arrow_down &&
       !right_arrow_down &&
       !up_arrow_down &&
       !down_arrow_down)
         key_pressed = false;
     checkForKeyPressed();
    }Let me know if you'd like a SSCCE.
Thanks

It's this second-long delay which is the anomoly. I'm guessing it results from the fact that the KeyEvent is not being fired constantly or immediately after the release of the first key.That's the usual key-repeat behavior on most OSs.
I'm wondering if there's a way to get rid of the delay Probably by setting booleans in the keyPressed(...) / keyReleased(...) and polling those booleans at equal intervals using a Timer.
db

Similar Messages

  • Key events are not fired for  SwingTextField

    No event is fired when a key is typed/pressed. Am I missing something here?
    import javafx.stage.Stage;
    import javafx.scene.Scene;
    import javafx.ext.swing.SwingTextField;
    import javafx.scene.input.KeyEvent;
    Stage {
    title: "MyApp"
    scene: Scene {
    width: 200
    height: 200
    content: [
    SwingTextField {
    columns: 20
    text: " "
    editable: true
    onKeyPressed: function( e: KeyEvent ):Void {
    println("on key pressed");
    onKeyTyped: function( e: KeyEvent ):Void {
    println("on key pressed");
    onKeyReleased: function( e: KeyEvent ):Void {
    println("on key released");
    }

    ya it wont work. just try this one,
    use the keyListener function for all key listener.
    * FxTextField.fx
    * Created on Jan 21, 2009, 9:29:49 AM
    package com.sb.javafx.comp;
    import javafx.ext.swing.SwingComponent;
    import javax.swing.JTextField;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JComponent;
    * @author Admin
    public class FxTextField extends SwingComponent{
        var textField:JTextField;
        public var text:String on replace{
            textField.setText(text);
        public var keyListener:function(key:KeyEvent);
        init{
            textField.addKeyListener(KeyListener{
                 public override function keyPressed(e:KeyEvent)
                    text = textField.getText();
                    keyListener(e);
                 public override function keyTyped(e:KeyEvent)
                    text = textField.getText();
                    keyListener(e);
                 public override function keyReleased(e:KeyEvent)
                    text = textField.getText();
                    keyListener(e);
        public override function createJComponent():JComponent
            textField = new JTextField();
            return textField;
    }

  • KeyListener Help Needed for Tetris Game!

    * Tetris - Java Enhacned
    * By: Kunnel Zachariah, Johnathan Smith, Johnathan Adkins
    import javax.swing.JFrame;
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.Timer;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import static java.lang.Character.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;
    import java.lang.Math;
    import java.lang.System;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
    import java.awt.event.KeyAdapter;
    public class TetrisMain extends JFrame implements KeyListener
         int s;
         int p;
         int xPos;
         int yPos;
         int level = 1;
         int lines = 0;
         int score = 0;
         int switchPiece;
         private boolean[] keys;
         private int SLEEP = 50; //bigger # = slower animation
         private Timer timer;
         int bologna = 11;
        int posX[], posY[];
         Color color;
         boolean isSquare = false;
         public TetrisMain()
              setSize(550,710);
              setBackground(Color.black);
              setVisible(true);
              getContentPane();
         public static void main( String args[] )
              TetrisMain pongLab = new TetrisMain();
        public void paint (Graphics g)
              s=0;
              keys = new boolean[4];
              this.addKeyListener(this);
              g.setColor(Color.blue);
              g.fillRect(0,0,550,710);
              g.setColor(Color.black);
              g.fillRect(0,0,460,600);          
              g.setColor(Color.blue);
              g.setColor (Color.black);          
              g.setFont(new Font("Helvetica",Font.BOLD,14));
            g.drawString ("Level: " + level, 485, 40);
            g.drawString ("Lines: " + lines, 485, 80);
            g.drawString ("Score: " + score, 485, 120);
             ActionListener paintCaller = new ActionListener(){
                   public void actionPerformed(ActionEvent event)
                        repaint();  //recalls paint every SLEEP milliseconds
              timer = new Timer(SLEEP, paintCaller);
              timer.start();
              while (bologna <= 30)
             if ( keys[0] == true )
                   //move left paddle up and draw it on the window
                   s+=3;
              if ( keys[1] == true )
              //move left paddle down and draw it on the window
                   p+=3;
              if ( keys[2] == true )
                   s-=3;
              if ( keys[3] == true )
                   p-=3;
                        displayRandomPiece(g);
                        bologna++;
      public void drawGridVertical(Graphics g)
             for(xPos = 0; xPos <=460; xPos+=23)
             for(yPos=0; yPos <=600; yPos+=23)
                  g.drawLine(xPos,yPos,xPos,yPos);
        public void drawBlock(Graphics g)
         ImageIcon animatedIcon1 = new ImageIcon("untitled.gif");
         for(p =0; p <=530; p+=2)
          animatedIcon1.paintIcon(this,g,s,p);
          delay(100000);
        public void drawTpiece(Graphics g)
           ImageIcon animatedIcon = new ImageIcon("tpiece.gif");
          for(p =0; p <=530; p+=2)
          animatedIcon.paintIcon(this,g,s,p);
          delay(100000);
        public void drawZigZagpiece(Graphics g)
         ImageIcon animatedIcon2 = new ImageIcon("zigzagpiece.gif");
         for(p =0; p <=530; p+=2)
          animatedIcon2.paintIcon(this,g,s,p);
          delay(100000);
        public void Rectanglepiece(Graphics g)
             ImageIcon animatedIcon3 = new ImageIcon("rectangle.gif");
         for(p =0; p <=530; p+=2)
          animatedIcon3.paintIcon(this,g,s,p);
          delay(100000);
        public void Unknownpiece(Graphics g)
             ImageIcon animatedIcon4 = new ImageIcon("unknownpiece.gif");
         for(p =0; p <=530; p+=2)
          animatedIcon4.paintIcon(this,g,s,p);
          delay(100000);
        public void otherZigZagpiece(Graphics g)
             ImageIcon animatedIcon5 = new ImageIcon("otherzigzagpiece.gif");
          for(p =0; p <=530; p+=2)
          animatedIcon5.paintIcon(this,g,s,p);
          delay(100000);
         public void otherUnknownpiece(Graphics g)
             ImageIcon animatedIcon6 = new ImageIcon("otherunknownpiece.gif");
         for(p =0; p <=530; p+=2)
          animatedIcon6.paintIcon(this,g,s,p);
          delay(100000);
        public static void delay(double n)
              for (double x = 0; x <= n; x += .01);
          public boolean keyPressed(Event e, int key)
          if (key == Event.LEFT)
            s=-1;
          else if (key == Event.RIGHT)
            s+=1;
          else if (key == Event.UP)
            p-=1;
          else if (key == Event.DOWN)
          //  fast=true;
          else if (key == Event.ESCAPE)
           // ingame=false;
        return true;
         public void keyPressed(KeyEvent e)
              System.out.println("keypressed");
              switch(toUpperCase(e.getKeyChar()))
                   case 'W' : keys[0]=true;System.out.println("W keypressed"); break;
                   case 'Z' : keys[1]=true; System.out.println("z keypressed");break;
                   case 'I' : keys[2]=true; System.out.println("i keypressed");break;
                   case 'M' : keys[3]=true; System.out.println("m keypressed");break;
         public void keyReleased(KeyEvent e)
              System.out.println("released");
              switch(toUpperCase(e.getKeyChar()))
                   case 'W' : keys[0]=true; System.out.println("W realeased");break;
                   case 'Z' : keys[1]=true; System.out.println("Z realeased");break;
                   case 'I' : keys[2]=true; System.out.println("i realeased");break;
                   case 'M' : keys[3]=true; System.out.println("m realeased");break;
         public void keyTyped(KeyEvent e)
              //no code needed here
      public void displayRandomPiece(Graphics g)
           Random rand = new Random();
           int c = rand.nextInt((7)+1);
           switch(c)
                case 1:
                drawBlock(g);
                break;
                case 2:
                drawTpiece(g);
                break;
                case 3:
                drawZigZagpiece(g);
                break;
                case 4:
                Rectanglepiece(g);
                break;
                case 5:
                Unknownpiece(g);
                break;
                case 6:
                otherZigZagpiece(g);
                break;
                case 7:
                otherUnknownpiece(g);
                break;
    }This is my code so far for Tetris. I am having issues with my keylisteners! I keep pressing the specified keys and the println statements wont show up or the piece wont move! i really need major help. can anyone give me some advice
    Much Thanks,
    Chris!

    http://forum.java.sun.com/thread.jspa?threadID=5175447
    Don't double post! No help for you!

  • Problem with the keylistener

    Hi ,
    I am strucking with keylistener problem. I need the date in yyyy/mm/dd and no other letter it should allow me that means 2008/12/21.(i .e.,only digits and / at 5 and 8 postion) and the total length of the field is not more than 10.
    i have done to accept only digits and max length of the date field is 10 by using the below code but unable valide / at chart 5 and 8 position.
    Seek urgent help and reply would greately be appreciated.
    public class DateListener extends JTextField implements KeyListener
         /* (non-Javadoc)
         * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
         public void keyPressed(KeyEvent arg0) {
              // TODO Auto-generated method stub
         /* (non-Javadoc)
         * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
         public void keyReleased(KeyEvent arg0) {
              // TODO Auto-generated method stub
         public void keyTyped(KeyEvent e)
              final char c = e.getKeyChar();
              System.out.println("this.getText() value is" +this.getText());
              if( this.getText().length()> 9)
                   e.consume();
              System.out.println(this.getCaretPosition());
              if((c < '0' || c > '9') )
                   e.consume();
              }else if(this.getText().length() < 4 && this.getText().length() > 5 && c != '/' )
                   e.consume();
    Thank you,

    Hi, I struk with Maskformatter. I am validating the date entered my user. I have made the date using
    mft = new MaskFormatter("####/##/##");
    mft.setPlaceholderCharacter('_');
    activeDateTF = new avax.swing.JFormattedTextField(mft); where activeDateTF is a format text field . I have added the keylistener to that
    DateListener dateListener = new DateListener();
    this.activeDateTF.addKeyListener(dateListener);
    and datelistener has the following.
    public void keyReleased(KeyEvent e)
    { // TODO Auto-generated method stub
    System.out.println("you are in key released");
    final char c = e.getKeyChar();
    if(c!='\b') {
    al.add(c);
    JTextField ft =(JTextField)
    e.getSource(); if(al.size()== 8 )
    { System.out.println("ft.text value is " +ft.getText());
    al.clear();
    } where al is a arraylist used to know how many digits have been entered by user since the date contains only 8 (2008/12/12) excluding /. But the validations are becoming very difficult since the user may just enter 2008 and leave. my question is how do i get the value without _(placeholder) from the formatted text filed and how to validate the digits entered by user. Plesae help srini

  • KeyEvent.consume() doesn't work

    I have JFormattedTextField subclassed and implement a KeyListener to avoid typing invalid characters. so i implemented:
         * Implements KeyListener.
        public void keyPressed(KeyEvent event) {
            System.out.println("keyPressed: "+event);
            //verify:
            int keyCode = event.getKeyCode();
            switch (keyCode) {
            case KeyEvent.VK_T :
                System.out.println("valid: "+keyCode);
                break;
            default:
                System.out.println("invalid: "+keyCode);
                event.consume();
                break;
        }//keyPressed()The system out's are correct ("valid", "invalid"), but the invalid characters are still typed in the textfield - even though i call event.consume(). ?

    i had to introduce a class variable as a flag and also implement the other methods of KeyListener:
         * Implements KeyListener.
        public void keyPressed(KeyEvent event) {
            //verify:
            int keyCode = event.getKeyCode();
            switch (keyCode) {
            case KeyEvent.VK_T :
            case KeyEvent.VK_ESCAPE :
                isKeyConsumed = false;
                break;
            default:
                event.consume();
                isKeyConsumed = true;
                break;
        }//keyPressed()
         * Implements KeyListener.
        public void keyTyped(KeyEvent event) {
            if (isKeyConsumed) {
                event.consume();
        }//keyTyped()
         * Implements KeyListener.
        public void keyReleased(KeyEvent event) {
           if (isKeyConsumed) {
               event.consume();
        }//keyReleased()not pretty, but it works as expected.

  • Output stream with a keylistener

    Hello,
    I have a program that basically runs .class and .jar console based programs, using JFileChooser to open them and such. I have managed to capture the System.out and System.err streams from running processes and using p.getInputStream() and p.getErrorStream(), just appending a JTextArea with each character in the stream. Now I'm trying to get the System.in stream connected.
    I have a keylistener attached to my JFrame, like this
    String line;
    frame.addKeyListener(new KeyListener() {
         @Override
         public void keyPressed(KeyEvent e) {}
         @Override
         public void keyReleased(KeyEvent e) {
              Character key = e.getKeyChar();
              //Delete the last character in both the JTextArea and the current line
              if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
                   if (output.getText().charAt(output.getText().length()-1) != '\n') {
                        String text = output.getText().substring(0, output.getText().length()-1);
                        output.setText(text);
                        line = line.substring(0, line.length()-1);
                   //Write line to OutputStream and put a new line in the JTextArea                              
              } else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                       //writeToOutput("\n-------\nLine reads: " + line + "\n--------\n");
                   writeToOutput("\n");
                   line = "";
              //Add any other characters to the line and show them in the JTextArea
              } else if (e.getKeyCode() != KeyEvent.VK_SHIFT) {
                   writeToOutput(key + "");
                   line = line + key;
         @Override
         public void keyTyped(KeyEvent e) {}                         
    });What happens is that the user types a line of characters, then presses enter. What I want is for when enter is pressed that the line is written to some sort of OutputStream in such a way that I can use it to provide input to a process with p.getOutputStream(OutputStream);
    Which OutputStream do I have to use and how? It's all a bit confusing :S
    Thanks,
    Jack
    Edited by: jackCharlez on Nov 23, 2009 1:25 PM
    Edited by: jackCharlez on Nov 23, 2009 1:33 PM

    Solved, using
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    Out.write in my keylistener and out.newline(); out.flush(); when the user presses enter.
    ^ For anyone googling this problem :P

  • Events to detect change in physical keyboard key state

    I would like my application to respond in one way to a keyboard key being pressed, and then another way to the key being released. That is, I want my application to be able to reflect the actual physical state of the keyboard key.
    The obvious use of the (several) Java API's for keyboard events rapidly fires repeated KEY_PRESSED and KEY_RELEASED events if the key is held down for any time. This unfortunately obscures the actual state of the physical key (how do you know which was the last KEY_RELEASED?)
    Is it possible to turn off the key repeat feature, just for component, say?
    This would seem to be an obvious thing to do, but I can't find sample code anywhere. The code I find in the Sun Java API manuals all shows the above problem with key repetition.
    I would be also pleased to know that the solution of this problem is well known, on some FAQ or something, but I have looked through several FAQ's and searched this formum and have found nothing that helps. Also, I have had the misfortune of having to build messy and non-robust solutions for the equivalent problem in other development environments. I hope it is already there somewhere in Java and I'm just missing it.
    Thanks!

    "If two subsequent KEY_RELEASED and KEY_PRESSED
    events have the same
    timestamp, they are caused by autorepeat"
    This sounds good. But unfortunately the repeated
    KEY_RELEASED and KEY_PRESSED caused by key autorepeat
    on my system (Linux, java 1.5.0_09) have
    timestamps that increase with each repetition.I think this means only that the pair of pressed/release events have the
    same timestamp, not that every such pair has the same timestamp.
    That is, if you have the sequence PRESS,RELEASE,PRESS,RELEASE,
    the first two would have the same timestamp, and then the second two
    would have the same timestamp, but different than the first. Regardless,
    I found that also to not be the case; the PRESS and RELEASE did not have
    the same timestamp even between pairs.
    That said, this seems to work on both Windows and Linux, with the caveat
    that releases may lag.
    import java.awt.event.*;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.*;
    public class LinuxKeyTest extends JPanel implements KeyListener {
         int delay = 750; // Must be > than your 500ms start delay.
         int delayRepeat = 75; // Must be greater than keyboard repeat interval.
         Map timers = new HashMap();
         int m_keyCode = -1;
         public static void main( String[] args ) {
              Runnable doRun = new Runnable() {
                   public void run() {
                        new LinuxKeyTest();
              SwingUtilities.invokeLater( doRun );
         public LinuxKeyTest() {
              JPanel panel = new JPanel();
              panel.setFocusable( true );
              panel.requestFocusInWindow();
              panel.addKeyListener( this );
              JFrame f = new JFrame();
              f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              f.getContentPane().add( panel );
              f.setSize( 200, 100 );
              f.setLocation( 200, 200 );
              f.setVisible( true );
         public void keyPressed( KeyEvent e ) {
              int keyCode = e.getKeyCode();
              m_keyCode = keyCode;
              Integer timerKey = new Integer( keyCode );
              Timer timer = (Timer) timers.get( timerKey );
              if ( timer == null ) {
                   KeyTimeout keyTimeout = new KeyTimeout( timerKey, e.getWhen() );
                   timer = new Timer( delay, keyTimeout );
                   timers.put( timerKey, timer );
                   timer.start();
                   pressed( keyCode );
              } else {
                   ( (KeyTimeout) timer.getActionListeners()[0] ).setPressed( e.getWhen() );
                   timer.restart();
         public void keyReleased( KeyEvent e ) {
              int keyCode = e.getKeyCode();
              Integer timerKey = new Integer( keyCode );
              Timer timer = (Timer) timers.get( timerKey );
              if ( timer != null ) {
                   ( (KeyTimeout) timer.getActionListeners()[0] ).setReleased( e.getWhen() );
                   timer.setInitialDelay( delayRepeat );
                   m_keyCode = ( m_keyCode == keyCode ? -1 : keyCode );
              } else if ( m_keyCode != keyCode ) {
                   released( keyCode );
         public void keyTyped( KeyEvent e ) {
         public void pressed( int keyCode ) {          
              System.out.println( keyCode + " pressed" );
         public void released( int keyCode ) {
              System.out.println( keyCode + " released" );
         public class KeyTimeout implements ActionListener {
              private Integer timerKey;
              private int keyCode;
              private long firstPressed;
              private long pressed;
              private long released;
              public KeyTimeout( Integer key, long time ) {
                   this.timerKey = key;
                   this.keyCode = timerKey.intValue();
                   this.firstPressed = time;
                   this.pressed = time;
                   this.released = time;
              public void actionPerformed( ActionEvent e ) {
                   if ( released != firstPressed && released != pressed ) {
                        released( keyCode );
                        stop();
                   } else if ( m_keyCode != keyCode ) {
                        if ( m_keyCode == -1 ) {
                             released( keyCode );
                        stop();
              public void stop() {
                   Timer timer = (Timer) timers.get( timerKey );
                   timer.stop();
                   timers.remove( timerKey );
              public void setPressed( long time ) {
                   this.pressed = time;
              public void setReleased( long time ) {
                   this.released = time;
    }

  • Need Help with Java Space Invaders Game!

    Hi, im new to these forums so forgive if i dont follow the right way on laying things out. Im trying to create space invaders game but im stuck when im trying to create multiple aliens/ invaders. I have a class called Aliens (which is the invaders), and i can create an instance of an Alien. But when I try to create multiple instances they are not showing up on screen. I am not getting any error message though (which im hoping is a good sign, lol).
    GamePanel is where all the action is and Alien is the alien (invaders) class.
    Here is the code:
    import java.awt.; import javax.swing.; import java.awt.Image; import java.awt.event.KeyListener; import java.awt.event.KeyEvent;
    public class GamePanel extends JComponent implements KeyListener { SpaceInvaders game; static Player player1; Aliens alien1; static public Image spaceship2R; static public Image spaceship2L;
    public GamePanel(SpaceInvaders game)
         this.game = game;
         player1 = new Player(this);
         player1.start();
                   ///// trying to create multiple instances of aliens here
         for(int i=0; i<4; i++)
              alien1 = new Aliens(this);
              alien1.setX(i*100);
              alien1.start();
        this.setFocusable(true);
        this.addKeyListener(this);
    public void paintComponent(Graphics g)
         Image pic1 = player1.getImage();
         Image pic2 = alien1.getImage();
         super.paintComponent(g);
         g.drawImage(pic1, player1.getX(), player1.getY(), 50, 50,this);
         g.drawImage(pic2, alien1.getX(), alien1.getY(), 50, 50,this);
    }//end class
    import java.awt.Image; import java.awt.*;
    class Aliens extends Thread { //variables GamePanel parent; private boolean isRunning; private int xPos = 0, yPos = 0; Thread thread; static char direction = 'r'; Aliens alien; static public Image alien1; static public Image alien2;
    public Aliens(GamePanel parent)
         this.parent = parent;
         isRunning = true;
    public void run()
         while(isRunning)
              Toolkit kit = Toolkit.getDefaultToolkit();
              alien1 = kit.getImage("alien1.gif");
              alien2 = kit.getImage("alien2.gif");
              try
                      thread.sleep(100);
                 catch(InterruptedException e)
                      System.err.println(e);
                 updateAliens();
                 parent.repaint();
    public static Image getImage()
         Image alienImage = alien1;
        switch(direction){
             case('l'):
                  alienImage = alien1;
                  break;
             case('r'):
                  alienImage = alien1;
                  break;
        return alienImage;     
    public void updateAliens()
         if(direction=='r')
              xPos+=20;
              if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
                   yPos+=50;
                   xPos-=20;
                   direction='l';
         else
              xPos-=20;
              if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
                   yPos+=50;
                   xPos+=20;
                   direction='r';
    public void setDirection(char c){ direction = c; }
    public void setX(int x){ xPos = x; }
    public void setY(int y){ yPos = y; }
    public int getX(){ return xPos; }
    public int getY(){ return yPos; }
    }//end classEdited by: deathwings on Oct 19, 2009 9:47 AM
    Edited by: deathwings on Oct 19, 2009 9:53 AM

    Maybe the array I have created is not being used in the paint method, or Im working with 2 different objects as you put it? Sorry, Im just learning and I appreciate your time and help. Here is my GamePanel Class and my Aliens class:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Image;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferStrategy;
    public class GamePanel extends JComponent implements KeyListener
         SpaceInvaders game;
         static Player player1;
         static Bullets bullet;
         //static public Image spaceship2R;
         //static public Image spaceship2L;
         private BufferStrategy strategy;
         static int alienNum =0;
         static Aliens[] aliens;
         public GamePanel(SpaceInvaders game)
              this.game = game;
              player1 = new Player(this);
              player1.start();
              Aliens[] aliens = new Aliens[10];
              for(int i=0; i<4; i++)
                   aliens[i] = new Aliens(this);
                   aliens.setX(i*100);
                   aliens[i].start();
                   alienNum++;
              initialiseGame();
              this.setFocusable(true);
    this.addKeyListener(this);
         public void paintComponent(Graphics g)
              Image pic1 = player1.getImage();
              Image pic2 = aliens[0].getImage();
              Image bulletPic = bullet.getImage();
              super.paintComponent(g);
              g.drawImage(pic1, player1.getX(), player1.getY(), 50, 50,this);
              for ( int i = 0; i < alienNum; i++ )
                   g.drawImage(pic1, aliens[0].getX(), aliens[0].getY(), 50, 50,this);
              //if (bullet.fired==true){
              //     g.drawImage(bulletPic, bullet.getX(), bullet.getY(), 20, 20,this);
         public void keyPressed(KeyEvent k)
              switch (k.getKeyCode()) {
              case (KeyEvent.VK_KP_DOWN):
              case (KeyEvent.VK_DOWN):
                   player1.setDirection('d');
                   break;
              case (KeyEvent.VK_KP_UP):
              case (KeyEvent.VK_UP):
                   player1.setDirection('u');
              break;
              case (KeyEvent.VK_KP_RIGHT):
              case (KeyEvent.VK_RIGHT):
                   player1.setDirection('r');
              break;
              case (KeyEvent.VK_KP_LEFT):
              case (KeyEvent.VK_LEFT):
                   player1.setDirection('l');
              break;
              case (KeyEvent.VK_SPACE):
                   fireBullet();
              break;
         public void keyTyped(KeyEvent k) {}//empty
         public void keyReleased(KeyEvent k)
              player1.setDirection('n');
         public void initialiseGame()
         public static void checkCollision()
              Rectangle playerRec = new Rectangle(player1.getBoundingBox());
              for(int i=0; i<alienNum; i++)
                   //if(playerRec.intersects(aliens[i].getBoundingBox()))
                        //collisionDetected();
         public static void collisionDetected()
              System.out.println("COLLISION");
         public void fireBullet()
              Bullets bullet = new Bullets(player1.getX(),player1.getY());
              bullet.fired=true;
    }//end GamePanelimport java.awt.Image;
    import java.awt.*;
    class Aliens extends Thread
         //variables
         GamePanel parent;
         private boolean isRunning;
         private int xPos = 0, yPos = 0;
         Thread thread;
         static char direction = 'r';
         Aliens alien;
         static public Image alien1;
         static public Image alien2;
         public Aliens(GamePanel parent)
              this.parent = parent;
              isRunning = true;
         public void run()
              while(isRunning)
                   Toolkit kit = Toolkit.getDefaultToolkit();
                   alien1 = kit.getImage("alien1.gif");
                   //alien2 = kit.getImage("alien2.gif");
                   try
              thread.sleep(100);
         catch(InterruptedException e)
              System.err.println(e);
              updateAliens();
              parent.repaint();
         public static Image getImage()
              Image alienImage = alien1;
         switch(direction){
              case('l'):
                   alienImage = alien1;
                   break;
              case('r'):
                   alienImage = alien1;
                   break;
         return alienImage;     
         public void updateAliens()
              if(direction=='r')
                   xPos+=20;
                   if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
                        yPos+=50;
                        xPos-=20;
                        direction='l';
              else
                   xPos-=20;
                   if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
                        yPos+=50;
                        xPos+=20;
                        direction='r';
         public Rectangle getBoundingBox()
              return new Rectangle((int)xPos, (int)yPos, 50, 50);
         public void setDirection(char c){ direction = c; }
         public void setX(int x){ xPos = x; }
         public void setY(int y){ yPos = y; }
         public int getX(){ return xPos; }
         public int getY(){ return yPos; }
    }//end class                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • JTable Deletions

    I am using JTable to display a series of simple text strings. Every cell contains the same kind of data; it isn't querying a database or anything like that. The user must be able to delete these cells quickly, so the design of the application is such that the delete key can be pressed several times in succession to delete successive elements. I am using the standard construct to accomplish this:
    if (keyEvent.getKeyCode() == java.awt.event.KeyEvent.VK_DELETE) {...}
    This is a 2 year old app that has run fine in production under JDK 1.1.8. However, when moving to 1.3.1, pressing the delete key causes the currently selected element only to be deleted. While the table updates correctly and the next element is highlighted, nothing happens upon subsequent presses of DELETE. If a cursor key or the mouse is used to select an element -- even the currently highlighted one -- then that element may be deleted, but the cycle repeats itself.
    After combing the JDK docs, Sun's tutorials, and the Forums, I am at a loss. I've tried using editCellAt(), setEditingColumn/Row(), clearSelection(), & changeSelection() after firing the deletion event. Any ideas?

    OK, here's a complete example. Why don't you see what you can do with it?
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableTest implements KeyListener, TableModel
        public TableTest()
            tableData.add(new String[] { "a", "aa", "aaa", "aaaa" });
            tableData.add(new String[] { "b", "bb", "bbb", "bbbb" });
            tableData.add(new String[] { "c", "cc", "ccc", "cccc" });
            tableData.add(new String[] { "d", "dd", "ddd", "dddd" });
            table = new JTable(this);
            table.addKeyListener(this);
        String columnHeader[] = { " ", "Name", "Type", "Node" };
        JTable table;
        Vector tableData = new Vector();
        Vector tableModelListeners = new Vector();
        // TableModel methods.
        public void addTableModelListener(TableModelListener listener)
            synchronized (tableModelListeners)
                if (!tableModelListeners.contains(listener))
                    tableModelListeners.add(listener);
        public void removeTableModelListener(TableModelListener listener)
            synchronized (tableModelListeners)
                tableModelListeners.remove(listener);
        public Class getColumnClass(int column) { return ((Object[]) tableData.elementAt(0))[column].getClass(); }
        public String getColumnName(int column) { return columnHeader[column]; }
        public int getColumnCount() { return columnHeader.length; }
        public int getRowCount() { return tableData.size(); }
        public Object getValueAt(int r, int c) { return ((Object[]) tableData.elementAt(r))[c]; }
        public void setValueAt(Object value, int r, int c) { ((Object[]) tableData.elementAt(r))[c] = value; }
        public boolean isCellEditable(int r, int c) { return false; }
        private void tableChanged()
            TableModelEvent event = new TableModelEvent(this);
            synchronized (tableModelListeners)
                for (int count = tableModelListeners.size(), i = 0; i < count; i++)
                    ((TableModelListener) tableModelListeners.elementAt(i)).tableChanged(event);
        // KeyListener methods.
        public void keyPressed(KeyEvent ev) { }
        public void keyTyped(KeyEvent ev) { }
        public void keyReleased(KeyEvent ev)
            if (ev.getKeyCode() == KeyEvent.VK_DELETE)
                int row = table.getSelectedRow();
                if (row != -1)
                    tableData.remove(row);
                    tableChanged();
                    if (row < table.getRowCount()) table.setRowSelectionInterval(row, row);
        public static void main(String[] arg)
            TableTest test = new TableTest();
            JFrame frame = new JFrame("Table Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);
            frame.setLocation(200, 200);
            frame.getContentPane().add(new JScrollPane(test.table));
            frame.show();

  • JInternalFrame listeners stops working if more than one opened ?

    Hi all, I'm trying to write some kind of chat program for my term project
    I'm really stucked at this point.
    I connect to a server, get chat room lists, join to a chat room, there's no problem at this first chat room ( internalFrame ), everything is fine ( I can refresh user list with pressing F5, send messages through send message button ), when I join another chat room ( second internalFrame ), problems start to occur, I can refresh with pressing F5, but I cannot send messages to server, server recieves my messages as null messages, still I can send messages with the first internal frame I opened but cannot refresh with pressing F5 in the first frame !
    here are my codes for certain parts
    main class
    public class ChatClientMain extends JFrame
                                   implements ActionListener {
    // items etc here
        public ChatClientMain() {
            super("project");
            connectedToServer=false;
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            desktopPane = new JDesktopPane(); //a specialized layered pane
            setContentPane(desktopPane);
            desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        public void actionPerformed(ActionEvent event)
           if ( event.getSource() == connectMenuItem )
                       try
                            connectionSocket = new Socket(serverName,serverPort);
                                    inFromServer = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                            outToServer = new PrintStream(connectionSocket.getOutputStream());
                       catch (IOException e)
                            JOptionPane.showMessageDialog(null, "Cannot connect to server\nProgram will exit", "Cannot connect", JOptionPane.ERROR_MESSAGE);
                            e.printStackTrace();
                            System.exit(1);
                       createServerFrame(outToServer);
                       new ConnectionToServer(nickName,connectionSocket,inFromServer,outToServer).start();
                    // other actions etc.
        protected static void createChatFrame(String roomName)
            ChatFrame frame = new ChatFrame(roomName);
            frame.setVisible(true);
            desktopPane.add(frame);
            try
                frame.setSelected(true);
            catch (java.beans.PropertyVetoException e) {}
            outToServer.println("GET USER LIST"+roomName);
    here's thread for connection to server
    public class ConnectionToServer extends Thread
         public ConnectionToServer(String nick,Socket socket,BufferedReader bf,PrintStream ps)
              nickName=nick;
              inFromServer = bf;
              outToServer = ps;
              connectionSocket=socket;
              ChatClientMain.connectedToServer=true;
              outToServer.println("CONNECTION INITIALIZATION"+nickName);
         public void run()
              try
                   while(true)
                        recievedMessage = inFromServer.readLine();
                        System.out.println(recievedMessage);
                        if (recievedMessage.startsWith("CHATROOM")) // problem here ( in split function ), cannot parse since recieves null message
                             String[] chatRoomMessageParts = recievedMessage.split("#");
                             String chatRoomName = chatRoomMessageParts[1];
                             String chatRoomMessage = chatRoomMessageParts[2];
                             System.out.println("room name : " + chatRoomName + " message : " + chatRoomMessage);
                                    //some other protocols I implemented here
                        if (!roomListRecieving || ! userListRecieving)
                             ServerFrame.serverConversation.append(recievedMessage + "\n");
              catch (IOException e)
                   e.printStackTrace();
    code for chat frame, which works for one, but not for two :S
    public class ChatFrame extends JInternalFrame
         private static final long serialVersionUID = 1L;
         static int openFrameCount = 0;
         static int xOffset = 60;
         static int yOffset = 60;
         JPanel chatRoomContent;
         JLabel chatRoom;
         JLabel users;
         JTextArea roomConversation;
         static JList roomUserList;
         JScrollPane conversationScroll;
         JScrollPane userListScroll;
         JTextField roomMessage;
         JButton roomMessageButton;
         static DefaultListModel userListModel;
         ListSelectionListener userListListener;
         public ChatFrame(final String roomName)
              super("Chat Room : " + roomName,
                        true, //resizable
                        true, //closable
                        true, //maximizable
                        true);//iconifiable
              openFrameCount++;
              chatRoomContent = new JPanel();
              chatRoomContent.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
              chatRoomContent.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
    // I set proper values for c everytime I add new item to pane
              chatRoom = new JLabel("Now chatting in : " + roomName);
              chatRoomContent.add(chatRoom,c);
              users = new JLabel("User List");
              chatRoomContent.add(users,c);
              roomConversation = new JTextArea();
              roomConversation.setEditable(false);
              conversationScroll = new JScrollPane();
              conversationScroll.setViewportView(roomConversation);
              chatRoomContent.add(conversationScroll,c);
              userListModel = new DefaultListModel();
              userListListener = new ListSelectionListener(){
                   public void valueChanged(ListSelectionEvent event) {
                        JList lsm = (JList) event.getSource();
                        if(event.getValueIsAdjusting())
                             roomConversation.append("Starting chat with " + lsm.getSelectedValue() + "\n");
                             String chatName = (String) lsm.getSelectedValue();
                             ChatClientMain.createPrivateChatFrame(chatName);
              roomUserList = new JList();
    //list props set here
              chatRoomContent.add(userListScroll,c);
              roomMessage = new JTextField();
              chatRoomContent.add(roomMessage,c);
              roomMessageButton = new JButton("Send Message");
              roomMessageButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        if (!roomMessage.getText().equals(""))
                             String message = ChatClientMain.nickName + " : " + roomMessage.getText() + "\n"; // message person wrote
                             roomConversation.append(message);
                             roomMessage.setText("");
                             ChatClientMain.outToServer.println("CHATROOM#"+roomName+"#"+message);  // message I'm sending to server
              chatRoomContent.add(roomMessageButton,c);
              this.setFocusable(true);
              this.addKeyListener(new KeyListener() {
                   @Override
                   public void keyPressed(KeyEvent arg0) {
                        int keyNo = arg0.getKeyCode();
                        if ( keyNo == KeyEvent.VK_F5)
                             ChatClientMain.outToServer.println("GET USER LIST"+roomName);       //refresh part with works just for the last internal frame I opened
                   //other methods
              this.addInternalFrameListener(new InternalFrameListener() {
                   public void internalFrameClosed(InternalFrameEvent arg0) {
                        ChatClientMain.leaveRoom(roomName);
                            //other methods here
              add(chatRoomContent);
              setSize(525,525);
              setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }I would really be thankful if you help..

    Hi all, I'm trying to write some kind of chat program for my term project
    I'm really stucked at this point.
    I connect to a server, get chat room lists, join to a chat room, there's no problem at this first chat room ( internalFrame ), everything is fine ( I can refresh user list with pressing F5, send messages through send message button ), when I join another chat room ( second internalFrame ), problems start to occur, I can refresh with pressing F5, but I cannot send messages to server, server recieves my messages as null messages, still I can send messages with the first internal frame I opened but cannot refresh with pressing F5 in the first frame !
    here are my codes for certain parts
    main class
    public class ChatClientMain extends JFrame
                                   implements ActionListener {
    // items etc here
        public ChatClientMain() {
            super("project");
            connectedToServer=false;
            int inset = 50;
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds(inset, inset,
                      screenSize.width  - inset*2,
                      screenSize.height - inset*2);
            desktopPane = new JDesktopPane(); //a specialized layered pane
            setContentPane(desktopPane);
            desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        public void actionPerformed(ActionEvent event)
           if ( event.getSource() == connectMenuItem )
                       try
                            connectionSocket = new Socket(serverName,serverPort);
                                    inFromServer = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                            outToServer = new PrintStream(connectionSocket.getOutputStream());
                       catch (IOException e)
                            JOptionPane.showMessageDialog(null, "Cannot connect to server\nProgram will exit", "Cannot connect", JOptionPane.ERROR_MESSAGE);
                            e.printStackTrace();
                            System.exit(1);
                       createServerFrame(outToServer);
                       new ConnectionToServer(nickName,connectionSocket,inFromServer,outToServer).start();
                    // other actions etc.
        protected static void createChatFrame(String roomName)
            ChatFrame frame = new ChatFrame(roomName);
            frame.setVisible(true);
            desktopPane.add(frame);
            try
                frame.setSelected(true);
            catch (java.beans.PropertyVetoException e) {}
            outToServer.println("GET USER LIST"+roomName);
    here's thread for connection to server
    public class ConnectionToServer extends Thread
         public ConnectionToServer(String nick,Socket socket,BufferedReader bf,PrintStream ps)
              nickName=nick;
              inFromServer = bf;
              outToServer = ps;
              connectionSocket=socket;
              ChatClientMain.connectedToServer=true;
              outToServer.println("CONNECTION INITIALIZATION"+nickName);
         public void run()
              try
                   while(true)
                        recievedMessage = inFromServer.readLine();
                        System.out.println(recievedMessage);
                        if (recievedMessage.startsWith("CHATROOM")) // problem here ( in split function ), cannot parse since recieves null message
                             String[] chatRoomMessageParts = recievedMessage.split("#");
                             String chatRoomName = chatRoomMessageParts[1];
                             String chatRoomMessage = chatRoomMessageParts[2];
                             System.out.println("room name : " + chatRoomName + " message : " + chatRoomMessage);
                                    //some other protocols I implemented here
                        if (!roomListRecieving || ! userListRecieving)
                             ServerFrame.serverConversation.append(recievedMessage + "\n");
              catch (IOException e)
                   e.printStackTrace();
    code for chat frame, which works for one, but not for two :S
    public class ChatFrame extends JInternalFrame
         private static final long serialVersionUID = 1L;
         static int openFrameCount = 0;
         static int xOffset = 60;
         static int yOffset = 60;
         JPanel chatRoomContent;
         JLabel chatRoom;
         JLabel users;
         JTextArea roomConversation;
         static JList roomUserList;
         JScrollPane conversationScroll;
         JScrollPane userListScroll;
         JTextField roomMessage;
         JButton roomMessageButton;
         static DefaultListModel userListModel;
         ListSelectionListener userListListener;
         public ChatFrame(final String roomName)
              super("Chat Room : " + roomName,
                        true, //resizable
                        true, //closable
                        true, //maximizable
                        true);//iconifiable
              openFrameCount++;
              chatRoomContent = new JPanel();
              chatRoomContent.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
              chatRoomContent.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
    // I set proper values for c everytime I add new item to pane
              chatRoom = new JLabel("Now chatting in : " + roomName);
              chatRoomContent.add(chatRoom,c);
              users = new JLabel("User List");
              chatRoomContent.add(users,c);
              roomConversation = new JTextArea();
              roomConversation.setEditable(false);
              conversationScroll = new JScrollPane();
              conversationScroll.setViewportView(roomConversation);
              chatRoomContent.add(conversationScroll,c);
              userListModel = new DefaultListModel();
              userListListener = new ListSelectionListener(){
                   public void valueChanged(ListSelectionEvent event) {
                        JList lsm = (JList) event.getSource();
                        if(event.getValueIsAdjusting())
                             roomConversation.append("Starting chat with " + lsm.getSelectedValue() + "\n");
                             String chatName = (String) lsm.getSelectedValue();
                             ChatClientMain.createPrivateChatFrame(chatName);
              roomUserList = new JList();
    //list props set here
              chatRoomContent.add(userListScroll,c);
              roomMessage = new JTextField();
              chatRoomContent.add(roomMessage,c);
              roomMessageButton = new JButton("Send Message");
              roomMessageButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent event) {
                        if (!roomMessage.getText().equals(""))
                             String message = ChatClientMain.nickName + " : " + roomMessage.getText() + "\n"; // message person wrote
                             roomConversation.append(message);
                             roomMessage.setText("");
                             ChatClientMain.outToServer.println("CHATROOM#"+roomName+"#"+message);  // message I'm sending to server
              chatRoomContent.add(roomMessageButton,c);
              this.setFocusable(true);
              this.addKeyListener(new KeyListener() {
                   @Override
                   public void keyPressed(KeyEvent arg0) {
                        int keyNo = arg0.getKeyCode();
                        if ( keyNo == KeyEvent.VK_F5)
                             ChatClientMain.outToServer.println("GET USER LIST"+roomName);       //refresh part with works just for the last internal frame I opened
                   //other methods
              this.addInternalFrameListener(new InternalFrameListener() {
                   public void internalFrameClosed(InternalFrameEvent arg0) {
                        ChatClientMain.leaveRoom(roomName);
                            //other methods here
              add(chatRoomContent);
              setSize(525,525);
              setLocation(xOffset*openFrameCount, yOffset*openFrameCount);
    }I would really be thankful if you help..

  • Anybody know of a SIMPLE highlighting editor?

    I've been trying to understand the Swing text classes by writing a syntax highlighting editor but I'm continually frustrated by the difficulty of understanding the examples I've found.
    The Prinzing example on the Sun site is sort of understandable but I don't understand it well enough to extend it.
    SimplyHTML is wonderfully documented but WAY beyond my ability.
    The Ostermiller example is easy to understand does not use the 'plug-in' design that the text classes seem to be designed for. In addition Ostermiller uses setCharacterAttributes() which does not work for me.
    Any suggestions for other examples?
    Thanks,
    --beeky                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Pasted below is the code of the editor u require. Should u need further information, feel free to get in touch with me.
    I hope this code will help u
    Sachin
    import com.pg.sourceone.gdet.util.ValidateUIData;
    import javax.swing.JTextField;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.TableColumn;
    import javax.swing.DefaultCellEditor;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.FocusEvent;
    import java.awt.Toolkit;
    import java.awt.Color;
    import java.text.NumberFormat;
    import java.text.ParseException;
    import java.util.Hashtable;
    import java.util.Vector;
    import java.util.Locale;
    public class CellHighlightEditor implements KeyListener, CellEditorListener
    /** integer holding the length of the column name */
    int intLength = 0;
    /** integer holding the column index */
    int intEditCol = -1;
    /** integer holding the row index */
    int intEditRow = -1;
    /** boolean holding the status after the validation function */
    boolean blnValid = true;
    /** TableColumn Object */
    TableColumn tcEditCol;
    /** DefaultCellEditor Object */
    DefaultCellEditor dceCols;
    /** HighlightTableCellRenderer Object */
    HighlightTableCellRenderer highlightTableCellObj;
    /** String holding the column name */
    String strEditCol = "";
    /** String holding the previous value of the cell */
    String strOldCellValue = null;
    /** String holding the current cell value */
    String strNewCellValue = null;
    /** String holding the cell number */
    String strCellNo = "";
    /** String holding the data retrived from the Hashtable hshType */
    String strDataType = "";
    /** Hashtable Object */
    Hashtable hshOldValues;
    /** Hashtable Object */
    Hashtable hshType;
    /** Hashtable Object */
    Hashtable hshLength;
    /** TableComponent Object */
    BldrTableComponent tblTemp = null;
    /** JTextField Object */
    public JTextField txfEditor;
    /** NumberFormat Object */
    NumberFormat nfData;
    /** Vector Object */
    Vector vctRows;
    /** Vector Object */
    Vector vctCols;
    /** ValidateUIData Object */
    ValidateUIData vld;
    * Constructor CellHighlightEditor.
    * @param TableComponent tblEditor
    * @param Vector vctRowEditor
    * @param Vector vctColsEditor
    public CellHighlightEditor(BldrTableComponent tblEditor, Vector vctRowEditor,
    Vector vctColsEditor)
    tblTemp = tblEditor;
    /* instantiate the ValidateUIData object */
    vld = new ValidateUIData();
    /* instantiate the hshType object */
    hshType = new Hashtable();
    /* instantiate the hshOldValues object */
    hshOldValues = new Hashtable();
    /* instantiate the hshLength object */
    hshLength = new Hashtable();
    /* instantiate the txfEditor object */
    txfEditor = new JTextField();
    /* instantiate the vctRows object */
    vctRows = new Vector();
    /* instantiate the vctCols object */
    vctCols = new Vector();
    /* instantiate the highlightTableCellObj object */
    highlightTableCellObj = new HighlightTableCellRenderer();
    txfEditor.addKeyListener(this);
    tblTemp.table.addKeyListener(this);
    nfData = NumberFormat.getInstance(Locale.US);
    for (int i = 0; i < vctRowEditor.size(); i++)
    vctRows.addElement(((Vector) vctRowEditor.elementAt(i)).clone());
    } // end of for
    for (int i = 0; i < vctColsEditor.size(); i++)
    vctCols.addElement(vctColsEditor.elementAt(i));
    } // end of for
    } // end of constructor
    * Method sets the data type and its length of the data present
    * in the JTable.
    * @param String strCol
    * @param int intLength
    * @param String strType
    public void setTypeNLength(String strCol, int intLength, String strType)
    hshLength.put(strCol, String.valueOf(intLength));
    hshType.put(strCol, strType);
    highlightTableCellObj.setTypeNLngth(hshType);
    } // end of setTypeNLength method
    * Method sets the JTable Column editable.
    * @param String strCol
    public void setColEditor(String strCol)
    dceCols = new DefaultCellEditor(txfEditor);
    dceCols.setClickCountToStart(1);
    dceCols.addCellEditorListener(this);
    tcEditCol =
    tblTemp.table.getColumnModel().getColumn(tblTemp.getColumnIndex(strCol));
    tcEditCol.setCellEditor(dceCols);
    tcEditCol.setCellRenderer(highlightTableCellObj);
    intEditCol = tblTemp.getColumnIndex(strCol);
    strEditCol = strCol;
    } // End of setColEditor method
    * Method used for removing highlighting.
    public void removeHighlighting()
    tblTemp.dataModel.resetHighlighting();
    } // End of removeHighlighting method
    * Method Invoked when a key has been Typed.
    * @param KeyEvent keyEvent
    public void keyTyped(KeyEvent keyEvent)
    intEditRow = tblTemp.table.getEditingRow();
    intEditCol = tblTemp.table.getEditingColumn();
    if ((intEditRow != -1) && (intEditCol != -1))
    strEditCol = tblTemp.table.getColumnName(intEditCol);
    strDataType =
    hshType.get(tblTemp.table.getColumnName(intEditCol)).toString();
    if (strDataType.equalsIgnoreCase("INTEGER"))
    blnValid = vld.staticIntegerValidation(keyEvent);
    else if (strDataType.equalsIgnoreCase("DECIMAL"))
    blnValid =
    vld.decimalValidation(dceCols.getCellEditorValue().toString(),keyEvent);
    else if (strDataType.equalsIgnoreCase("FILTERED_STRING"))
    blnValid = vld.charValidation("-_ ",keyEvent);
    if (blnValid == true)
    strNewCellValue = dceCols.getCellEditorValue().toString();
    if ((strNewCellValue != null) &&!strNewCellValue.equals(""))
    intLength =
    Integer
    .parseInt(hshLength.get(tblTemp.table.getColumnName(intEditCol))
    .toString());
    if ((strNewCellValue.indexOf('.') >= 0) && (keyEvent.getKeyChar() == '.'))
    keyEvent.consume();
    vld.staticLengthValidation(strNewCellValue, intLength, keyEvent);
    } // end of if ((strNewCellValue != null) &&!strNewCellValue.equals(""))
    } //end of boolean
    } // end of if ((intEditRow != -1) && (intEditCol != -1))
    } // end of keyTyped method
    * Method Invoked when a key has been pressed.
    * @param KeyEvent keyEvent
    public void keyPressed(KeyEvent keyEvent)
    } // end of keyPressed method
    * Method Invoked when a key has been pressed.
    * @param KeyEvent keyEvent
    public void keyReleased(KeyEvent keyEvent)
    strNewCellValue = dceCols.getCellEditorValue().toString();
    } // end of keyReleased method
    * Method editingCanceled.
    * @param ChangeEvent chngEvent
    public void editingCanceled(ChangeEvent chngEvent)
    } // end of editingCanceled metod
    * Method to notify that the user has finished editing the JTable
    * data.
    * @param ChangeEvent chngEvent
    public void editingStopped(ChangeEvent chngEvent)
    if ((intEditRow != -1) && (intEditCol != -1))
    strOldCellValue =
    ((Vector) vctRows.elementAt(intEditRow))
    .elementAt(vctCols.indexOf(strEditCol)).toString();
    if (!(strNewCellValue.equals(strOldCellValue)))
    // tblTemp.dataModel.setCellBackground(highlightTableCellObj, intEditRow,
    // strEditCol);
    else
    // tblTemp.dataModel.resetCellBackground(highlightTableCellObj,
    // intEditRow, strEditCol);
    } // end of else
    } // end of if ((intEditRow != -1) && (intEditCol != -1))
    tblTemp.table.editingStopped(chngEvent);
    } // end of editingStopped method
    }// end of CellHighlightEditor class

  • What classes do I need to make this "if" statement?

    what classes do I use or how do write code that basically says:
    if ( the key typed was not enter) {
    I couldn't figure it out using the keylistener.
    Thanks in advance.

    Use a KeyListener like this:
    JTextField textField = new JTextField();
    textField.addKeyListener(new KeyListener() {
         @Override
         public void keyPressed(KeyEvent e) {
              if (e.getKeyCode() == KeyEvent.VK_ENTER)
                   System.out.println("Enter pressed");
         @Override
         public void keyReleased(KeyEvent e) {
         @Override
         public void keyTyped(KeyEvent e) {
    });in keyPressed() and keyReleased() you can check for e.getKeyCode() == KeyEvent.VK_ENTER
    in keyTyped() you should check for e.getKeyChar() == '\n'

  • Extending JComponent  and creating new derived class

    <!--[if gte mso 9]><xml>
    Normal
    0
    false
    false
    false
    EN-US
    X-NONE
    X-NONE
    MicrosoftInternetExplorer4
    </xml><![endif]--><!--[if gte mso 9]><xml>
    </xml><![endif]-->
    <!--[if gte mso 10]>
    <style>
    /* Style Definitions */
    table.MsoNormalTable
    {mso-style-name:"Table Normal";
    mso-tstyle-rowband-size:0;
    mso-tstyle-colband-size:0;
    mso-style-noshow:yes;
    mso-style-priority:99;
    mso-style-qformat:yes;
    mso-style-parent:"";
    mso-padding-alt:0in 5.4pt 0in 5.4pt;
    mso-para-margin-top:0in;
    mso-para-margin-right:0in;
    mso-para-margin-bottom:10.0pt;
    mso-para-margin-left:0in;
    line-height:115%;
    mso-pagination:widow-orphan;
    font-size:11.0pt;
    font-family:"Calibri","sans-serif";
    mso-ascii-font-family:Calibri;
    mso-ascii-theme-font:minor-latin;
    mso-fareast-font-family:"Times New Roman";
    mso-fareast-theme-font:minor-fareast;
    mso-hansi-font-family:Calibri;
    mso-hansi-theme-font:minor-latin;}
    </style>
    <![endif]-->
    Dear Friends,
    I developed new component SwingComponent and I extends it
    from JComponent and also implements
    the interfaces like
    KeyListener and MouseListener .. but when I press ctrl+b and ctrl +n  it wont recognize in the KeyEvent but it works fine if i press  individual keys. Please give me an idea
    public class SwingComponent extends JComponent implements
    KeyListener,
    MouseListener{

    This one working fine for individual character for example if i press 'A' in keyborad it was working but how to activate if i press ctrl + n or ctrl + b in the JComponent or Component. did you got my question?
    private KeyListener keyListener;
         public void addKeyListener(KeyListener listener) {
                  keyListener = AWTEventMulticaster.add(keyListener, listener);
              enableEvents(AWTEvent.KEY_EVENT_MASK);
         public void removeKeyListener(KeyListener listener) {
              keyListener = AWTEventMulticaster.remove(keyListener, listener);
         public void processKeyEvent(KeyEvent evt) {
              if (keyListener != null) {
                   System.err.println("" + evt.getKeyChar() + " " +                                    
                                        evt.getKeyCode());
                   switch (evt.getID()) {
                   case KeyEvent.KEY_PRESSED:
                        keyListener.keyPressed(evt);
                        break;
                   case KeyEvent.KEY_RELEASED:
                        keyListener.keyReleased(evt);
                        break;
                   case KeyEvent.KEY_TYPED:
                        keyListener.keyTyped(evt);
                        break;
              super.processKeyEvent(evt);
           public void keyTyped(KeyEvent e) {
                     System.out.println(e.getKeyChar());
         public void keyPressed(KeyEvent e) {
                System.out.println(e.getKeyCode());
         public void keyReleased(KeyEvent e) {
                 System.out.pirntln(e.getKeyCode());
              }

  • JTabbedPane with JSplitPane - HELP !!!

    What am I missing??? I have a JSplitPane in a TabbedPane. The topComponent contains a JComboBox with Key values, the Bottom Component will display details based on the key value passed. The bottomComponent has 2 constructors: one default and one accepting an Argument. The default constructor instantiate the class that would represent the data and formats the bottomComponent. The second constructor retrieves the data from the Oracle database and formats the BottomComponent using the same method. I put System.out messages and the values are showing using the Second constructor. Your help is greatly appreciated.

    This is the complete set of code. I hope you can follow the logic. I tried your last suggestion without any success. Maybe by reviewing the code you can see a problem. I appreciate your help greatly. Thanks.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Management extends JPanel implements ChangeListener{
    //private JFrame dlframe;
    private JTabbedPane propPane;
    public Management(){
    propPane = new JTabbedPane(SwingConstants.TOP);
    propPane.setSize(795, 550);
    propPane.addChangeListener(this);
    populateTabbedPane();
    // getContentPane().add(propPane);
    add(propPane);
    } // end of constructor
    // create tabs with titles
    private void populateTabbedPane(){
         propPane.addTab("Management", null, new Mgmt(), "Management");
         propPane.addTab("Management Contact", null,
    new Management_Contact(), "Management Contact");
    } // end of populateTabbedPane
    public void stateChanged(ChangeEvent e){
         System.out.println("\n\n ****** Management.java " + propPane.getSelectedIndex() + " " + propPane.getTabPlacement());
    public static void main(String[] args){
    Home dl = new Home();
    dl.pack();
    dl.setSize(800, 620);
    dl.setBackground(Color.white);
    dl.setVisible(true);
    } // end of class Management
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Management_Contact extends JPanel {
         Mgmt_Class mgmt = null;
         Mgmt_Contact mgmtContact = null;
         public Management_Contact() {
              JSplitPane split = new JSplitPane();
              split.setOrientation(JSplitPane.VERTICAL_SPLIT);
              Mgmt_Header hdr = new Mgmt_Header();
              split.setTopComponent(hdr);
              Mgmt_Contact mgmtContact = new Mgmt_Contact();
              JScrollPane scrollPane = new JScrollPane(mgmtContact,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
              JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scrollPane.setPreferredSize(new Dimension(650,300));
              split.setBottomComponent(scrollPane);
              add(split);
    } // end of Management class
    import java.util.Vector;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Mgmt_Header extends JPanel implements ActionListener{
    private JComboBox cmbMgmt;
    private JTextField txtMgmtCode;
    private JTextField txtMgmtAddr1;
    private JTextField txtMgmtAddr2;
    private JTextField txtMgmtCity;
    private JButton sel;
    private JLabel lblBlk;
    private JPanel pWork;
    private Box vertBox;     
    private Box topBox;     
    private Box midBox;     
    private Box botBox;     
    JToolTip toolTip = null;
    private Mgmt_Class mClass = null;
    private Mgmt_Contact cnt = null;
    Vector mgmtVct = null;
    public Mgmt_Header(){
         vertBox = Box.createVerticalBox();
         topBox = Box.createHorizontalBox();
         midBox = Box.createHorizontalBox();
         botBox = Box.createHorizontalBox();
    mClass = new Mgmt_Class();
    mgmtVct = new Vector();
         cmbMgmt = new JComboBox();
         cmbMgmt.addItem(" ");
         mgmtVct = mClass.bldMgmtHeader();
         for (int x1=0; x1<mgmtVct.size() ;x1++ )
         mClass = (Mgmt_Class)mgmtVct.get(x1);
         cmbMgmt.addItem(mClass.getManagementName());
    System.out.println("MgmtHeader " + mgmtVct.size() + " " + cmbMgmt.getItemCount());
         cmbMgmt.setEditable(false);
         cmbMgmt.setBackground(Color.white);
         cmbMgmt.setName("cmbMgmt");
         cmbMgmt.setPreferredSize(new Dimension(250,27));
         cmbMgmt.setFont(new Font("Times-Roman",Font.PLAIN,12));
         cmbMgmt.addActionListener(this);
         pWork = new JPanel();
         pWork.setLayout(new FlowLayout(FlowLayout.CENTER));
         pWork.setBorder(BorderFactory.createTitledBorder(" Select Management Name "));
         pWork.add(new JLabel("Name: "));
         pWork.add(cmbMgmt);
         topBox.add(pWork);
         txtMgmtAddr1 = new JTextField("Address line 1",15);
         txtMgmtAddr1.setEditable(false);
         txtMgmtAddr2 = new JTextField("Address line 2",15);
         txtMgmtAddr2.setEditable(false);
         txtMgmtCity = new JTextField("City",15);
         txtMgmtCity.setEditable(false);
         midBox.add(midBox.createVerticalStrut(10));
         botBox.add(new JLabel("Address:"));
         botBox.add(topBox.createHorizontalStrut(15));
         botBox.add(txtMgmtAddr1);
         botBox.add(topBox.createHorizontalStrut(15));
         botBox.add(txtMgmtAddr2);
         botBox.add(topBox.createHorizontalStrut(15));
         botBox.add(txtMgmtCity);
         vertBox.add(topBox);
         vertBox.add(midBox);
         vertBox.add(botBox);
         add(vertBox);
    } // end of constructor
         public void actionPerformed(ActionEvent evt){
         if (evt.getSource() instanceof JComboBox){
         if (((JComboBox)evt.getSource()).getName() == "cmbMgmt"){
         int sel = ((JComboBox)evt.getSource()).getSelectedIndex();
         System.out.println("ActionListener " + sel + " " + ((JComboBox)evt.getSource()).getItemAt(sel) + " " + cmbMgmt.getItemAt(sel));
         Mgmt_Class mClass = (Mgmt_Class)mgmtVct.get(sel - 1);
         System.out.println("From Vector " + mClass.getAddress1() + " " + mClass.getAddress2() + " " + mClass.getManagementCode());
         txtMgmtAddr1.setText(mClass.getAddress1());
         txtMgmtAddr2.setText(mClass.getAddress2());
         txtMgmtCity.setText(City.getCityName(mClass.getCityCode()));
         System.out.println("\n\nListener " + ((JComboBox)evt.getSource()).getSelectedItem() + " " + (((JComboBox)evt.getSource()).getSelectedIndex()) );
         int mCode = mClass.getManagementCode();
         cnt = new Mgmt_Contact(mCode);
    System.out.println("\n After new Mgmt_Contact constructor");
         } // end of JComboBox
    } // end of actionPerformed
    } // end of Mgmt_Header
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.io.*;
    public class Mgmt_Contact extends JPanel implements KeyListener{
         private Mgmt_Contact_Class contact = null;
         private DefaultFocusManager mgr = null;
         private JTextField txtFName = null;
         private JTextField txtLName = null;
         private JTextField txtAddr1 = null;
         private JTextField txtAddr2 = null;
         private JButton btnUpd = null;
         private JButton btnNew = null;
         private JButton btnDel = null;
         private JButton btnNext = null;
         private JButton btnPrior = null;
         private JButton btnSel = null;
         private JPanel cntct = null;
         private JPanel pWork = null;
         private JPanel pWest = null;
         private JPanel pEast = null;
         private JPanel pNorth = null;
         private JPanel pSouth = null;
         private JPanel pCenter = null;
         public Mgmt_Contact() {
         System.out.println("\n MgmtContact default constructor");
              contact = new Mgmt_Contact_Class();
              bldPage();
         System.out.println("\n ******* After bldPage() routine");
         public Mgmt_Contact(int mCode) {
    System.out.println("\n MgmtContact second constructor " + mCode);
         Vector mgmtVct = new Vector();
         contact = new Mgmt_Contact_Class();
         mgmtVct = contact.bldMgmtContactTbl(mCode);
         contact =(Mgmt_Contact_Class)mgmtVct.get(0);
    System.out.println("\n ******* Management Contact Table *** " + contact.getFirstName());          
         bldPage();
    System.out.println("\n ******* After bldPage() routine");
         public void bldPage(){
    System.out.println("\n MgmtContact bldPage ");
              cntct = new JPanel();
              cntct.setLayout(new BorderLayout());
              pWest = new JPanel();
              pWest.setLayout(new GridLayout(0,1));
              pCenter = new JPanel();
              pCenter.setLayout(new GridLayout(0,1));
              pNorth = new JPanel();
              pNorth.setLayout(new FlowLayout(FlowLayout.CENTER));
              pSouth = new JPanel();
              pSouth.setLayout(new FlowLayout());
              pWork = new JPanel();
              pWork.setLayout(new FlowLayout(FlowLayout.LEFT));
              pWest.add(new JLabel("First :"));
              txtFName = new JTextField(15);
              txtFName.setText(contact.getFirstName());
    System.out.println("\n First Name " + txtFName.getText() + " " + contact.getFirstName());
              txtFName.setPreferredSize(new Dimension(200,27));
              txtFName.addKeyListener(this);
              txtFName.setName("txtFName");
              pWork.add(txtFName);
              pWork.add(new JLabel("Last :"));
              txtLName = new JTextField(15);
              txtLName.setText(contact.getLastName());
              txtLName.setPreferredSize(new Dimension(200,27));
              txtLName.setName("txtLName");     
              txtLName.addKeyListener(this);
              pWork.add(txtLName);
              pCenter.add(pWork);
              pWork = new JPanel();
              pWork.setLayout(new FlowLayout(FlowLayout.LEFT));
              pWest.add(new JLabel("Address :"));
              txtAddr1 = new JTextField(15);
              txtAddr1.setText(contact.getAddress1());
              txtAddr1.setPreferredSize(new Dimension(200,27));
              txtAddr1.addKeyListener(this);
              txtAddr1.setName("txtAddr1");
              pWork.add(txtAddr1);
              pWork.add(new JLabel(" "));
              txtAddr2 = new JTextField(15);
              txtAddr2.setText(contact.getAddress2());
              txtAddr2.setPreferredSize(new Dimension(200,27));
              txtAddr2.setName("txtAddr2");
              txtAddr2.addKeyListener(this);
              pWork.add(txtAddr2);
              pCenter.add(pWork);
              pWork = new JPanel();
              pWork.setLayout(new FlowLayout(FlowLayout.LEFT));
              btnUpd = new JButton("Update");
              btnUpd.addActionListener(new ButtonListener());
              btnDel = new JButton("Delete");
              btnDel.addActionListener(new ButtonListener());
              btnNew = new JButton(" Add ");
              btnNew.addActionListener(new ButtonListener());
              btnNext = new JButton(" Next ");
              btnNext.addActionListener(new ButtonListener());
              btnPrior = new JButton(" Prior ");
              btnPrior.addActionListener(new ButtonListener());
              btnSel = new JButton(" Select ");
              btnSel.addActionListener(new ButtonListener());
              pSouth.add(btnNew);
              pSouth.add(btnUpd);
              pSouth.add(btnDel);
              pSouth.add(btnNext);
              pSouth.add(btnPrior);
              pSouth.add(btnSel);
              cntct.add("West", pWest);
              cntct.add("Center", pCenter);
              cntct.add("South", pSouth);
              add(cntct);
         class ButtonListener implements ActionListener{
         public void actionPerformed(ActionEvent e){
    System.out.println("ButtonListener " + e.getActionCommand() + " " +
              contact.getString());
    // KeyListener Interface
         public void keyPressed(KeyEvent e){
         public void keyReleased(KeyEvent e){
              mgr = new DefaultFocusManager();
              Component comp = e.getComponent();
              Object obj = ((JTextField)e.getSource());
              if ((ColUtils.isMaxField(obj))){
              mgr.focusNextComponent(comp);
         } // end of KeyReleased
         public void keyTyped(KeyEvent e){
              char num = e.getKeyChar();
              Object obj = ((JTextField)e.getSource());
              if (ColUtils.isDataValid(num, obj)){
              else {
              e.consume();
              System.out.println(num + " Rejected Data");
         } // end of keyTyped
    } // end of Mgmt_Contact class

  • Anyone have/know of a method that would format a textbox?

    Hi all,
    I'm currently trying to make a java tax program. It's not finished, obviously. I'm using ready to program. Here is what I want to do. I want to take the amount in the subtotal box, and as the user is typing, after the key is pressed, the program will check to see if it is an actual number, and if there are strings in it, the computer will automatically knock them out and leave a number. Now, this is supposed to be a currency amount... Any suggestions? Here is my code:
    // The "JavaTax" class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.text.DecimalFormat;
    public class JavaTax extends JFrame
        private Container contents;
        private JLabel amount, total, gsttotal, psttotal, hsttotal, qsttotal;
        private JTextField amountBox, totalBox, gsttotalBox, psttotalBox, hsttotalBox, qsttotalBox;
        private JPanel totals, selection;
        private JButton calc;
        private JCheckBox gst, hst, pst, qst;
        private JComboBox pstProvinces, hstProvinces;
        private String provincesPST[] = new String [5];
        private String provincesHST[] = new String [3];
        private double QSTRATE = 7.5;
        double subTotal = 0;
        public JavaTax ()
            super ("Java Tax");
            contents = getContentPane ();
            contents.setLayout (new BorderLayout ());
            provincesPST [0] = "British Columbia (7%)";
            provincesPST [1] = "Saskatchewan (5%)";
            provincesPST [2] = "Manitoba (7%)";
            provincesPST [3] = "Ontario (8%)";
            provincesPST [4] = "Prince Edward Island (10%)";
            provincesHST [0] = "New Brunswick (13%)";
            provincesHST [1] = "Newfoundland (13%)";
            provincesHST [2] = "Nova Scotia (13%)";
            hsttotal = new JLabel ("HST Total:", JLabel.RIGHT);
            qsttotal = new JLabel ("QST Total:", JLabel.RIGHT);
            gsttotal = new JLabel ("GST Total:", JLabel.RIGHT);
            psttotal = new JLabel ("PST Total:", JLabel.RIGHT);
            total = new JLabel ("Total:", JLabel.RIGHT);
            amount = new JLabel ("Amount:", JLabel.RIGHT);
            psttotalBox = new JTextField ("", 10);
            psttotalBox.setEditable (false);
            hsttotalBox = new JTextField ("", 10);
            hsttotalBox.setEditable (false);
            gsttotalBox = new JTextField ("", 10);
            gsttotalBox.setEditable (false);
            qsttotalBox = new JTextField ("", 10);
            qsttotalBox.setEditable (false);
            totalBox = new JTextField ("", 10);
            amountBox = new JTextField ("", 10);
            calc = new JButton ("Calculate");
            gst = new JCheckBox ("GST");
            pst = new JCheckBox ("PST");
            hst = new JCheckBox ("HST");
            qst = new JCheckBox ("QST");
            pstProvinces = new JComboBox (provincesPST);
            hstProvinces = new JComboBox (provincesHST);
            //HST only in NB, Newfoundland and NS (all 13%)
            //QST only in Quebec (7.5%)
            // sample = new JLabel (new ImageIcon("file.jpg"))
            hsttotal.setForeground (Color.BLACK);
            psttotal.setForeground (Color.BLACK);
            gsttotal.setForeground (Color.BLACK);
            total.setForeground (Color.BLACK);
            amount.setForeground (Color.BLACK);
            hsttotal.setOpaque (true);
            gsttotal.setOpaque (true);
            psttotal.setOpaque (true);
            total.setOpaque (true);
            amount.setOpaque (true);
            totals = new JPanel ();
            totals.setLayout (new GridLayout (6, 2, 2, 10));
            contents.add (totals, BorderLayout.WEST);
            totals.add (amount);
            totals.add (amountBox);
            totals.add (gsttotal);
            totals.add (gsttotalBox);
            totals.add (psttotal);
            totals.add (psttotalBox);
            totals.add (hsttotal);
            totals.add (hsttotalBox);
            totals.add (qsttotal);
            totals.add (qsttotalBox);
            totals.add (total);
            totals.add (totalBox);
            selection = new JPanel (new GridLayout (7, 1, 2, 10));
            contents.add (selection, BorderLayout.EAST);
            selection.add (gst);
            selection.add (pst);
            selection.add (pstProvinces);
            selection.add (hst);
            selection.add (hstProvinces);
            selection.add (qst);
            selection.add (calc);
            setSize (500, 350);
            setVisible (true);
            NormalTaxHandler nth = new NormalTaxHandler ();
            SpecialTaxHandler sth = new SpecialTaxHandler ();
            TextFieldHandler tfh = new TextFieldHandler ();
            gst.addItemListener (nth);
            pst.addItemListener (nth);
            hst.addItemListener (sth);
            qst.addItemListener (sth);
            amountBox.addKeyListener (tfh);
        public static void main (String[] args)
            JavaTax guey = new JavaTax ();
            guey.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        } // main method
        public class TextFieldHandler implements KeyListener
            //implementation of KeyListener methods
            public void keyPressed (KeyEvent e)
            public void keyReleased (KeyEvent e)
                check (e);
            public void keyTyped (KeyEvent e)
            public void check (KeyEvent e)
                try
                    subTotal = Double.parseDouble (amountBox.getText ());
                    DecimalFormat df = new DecimalFormat ("#.##");
                    //subTotal =
                    //subTotal = subTotal * 100;
                    //subTotal = ((int)subTotal)/100;
                    amountBox.setText (String.valueOf (df.format (subTotal)));
                    subTotal = Double.parseDouble (amountBox.getText ());
                catch (NumberFormatException nfe)
                    DecimalFormat df = new DecimalFormat ("#.##");
                    amountBox.setText (String.valueOf (df.format (subTotal)));
                    subTotal = Double.parseDouble (amountBox.getText ());
                subTotal = Double.parseDouble (amount);
                subTotal = subTotal * 100;
                subTotal = (int) subTotal / 100;
        private class NormalTaxHandler implements ItemListener
            public void itemStateChanged (ItemEvent ie)
                JCheckBox source = (JCheckBox) ie.getSource ();
                // If the object is selected . . .
                if (ie.getStateChange () == ItemEvent.SELECTED)
                    qst.setVisible (false);
                    hst.setVisible (false);
                    hstProvinces.setVisible (false);
                else
                    if (pst.isSelected () == false && gst.isSelected () == false)
                        qst.setVisible (true);
                        hst.setVisible (true);
                        hstProvinces.setVisible (true);
        private class SpecialTaxHandler implements ItemListener
            public void itemStateChanged (ItemEvent ie)
                JCheckBox source = (JCheckBox) ie.getSource ();
                if (ie.getStateChange () == ItemEvent.SELECTED)
                    gst.setVisible (false);
                    pst.setVisible (false);
                    pstProvinces.setVisible (false);
                    if (qst.isSelected () == true && hst.isSelected () == false)
                        hst.setVisible (false);
                        hstProvinces.setVisible (false);
                    else if (hst.isSelected () == true && qst.isSelected () == false)
                        qst.setVisible (false);
                else
                    if (hst.isSelected () == false || qst.isSelected () == false)
                        gst.setVisible (true);
                        pst.setVisible (true);
                        pstProvinces.setVisible (true);
                        hst.setVisible (true);
                        qst.setVisible (true);
                        hstProvinces.setVisible (true);
         * Create a MaskFormatter for FormattedTextFields
        protected MaskFormatter createFormatter (String s)
            MaskFormatter formatter = null;
            try
                formatter = new MaskFormatter (s);
            } // try
            catch (java.text.ParseException exc)
            } // catch
            return formatter;
        } // MaskFormatter method
    } // GUI class

    You can use Integer.parseInt(String) (or Double.parseDouble(String), etc.) to check if the String represents a number.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
    If it doesn't, you can use Character.isDigit(char) to check each char, and substring them out if they aren't digits. Then parse it again.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#isDigit(char)

Maybe you are looking for

  • Report builder doesn't connect

    Hi All, I ran into a problem where I can not connect the report builder and forms runtime to database. I am using oracle 10g 10.1.0.2.0 and forms and reports 6.0. and I am trying to connect through NT 4.0. I am able to connect to database through for

  • PDFMaker bookmarks broken or extra characters

    My configuration: Windows XP SP2 Acrobat 8 Pro Word 2000 When I attempt to create bookmarks automatically using the options in PDFMaker, the resulting bookmarks are broken and the bookmarked headings have extra characters in front of them. By broken,

  • SAP-MRS, What is capacity pots

    Hi All We have  implemented SAP MRS/ Multi Resource scheduling along with SAP-Plant Maintenance in EHP6 SAP GUI. I 've a doubt & 'm not getting clarified on some certain areas reagrding MRS / Will anyone update us with the below given queries? What a

  • Pls answer my questions

    HI gurus my questions are 1.Difference between billing and invoice? 2.How to stop PGI? 3.What do you mean by drop shipment? if any one can help me out thanks and regards

  • Anyone else having issues with AppleTV and 10.7

    My AppleTV is continuously breaking connections when watching movies since I'ne downloaded 10.7. I have to go back in to the setup and renew the computer connection to correct it.  Sometimes it holds for 30 minutes and other times it breaks the conne