KeyEvents and KeyListener

Hi,
Right now I have a applet that displays a image. I would like to use the arrow keys to pan the image. Using the keylistener (keyPressed, etc)
public void keyPressed(java.awt.event.KeyEvent event)
m_currentlyPressedKey = event.getKeyCode();
switch(m_currentlyPressedKey)
case KeyEvent.VK_RIGHT:
     case KeyEvent.VK_LEFT:
     case KeyEvent.VK_UP:
     case KeyEvent.VK_DOWN:
          onKeyboardPan(event);
          repaint();
          break;
< ... >
This works fine when I just press it once but if I hold the arrow key down it will redraw once (for the first press) then it kind of freezes as it madly tries to perform the multiple key presses that are generated. As a result when I hold it down the image will move once to the first press then freeze for a little bit until it catches up then redraw the image. Is there a way to get around that so that image can be moved/panned slowly depending on how long you hold the key for?

Another method would be to think of it as a state machine. Consider that when a keypressed event gets fired, the machine goes into a "panning left" (or whichever direction) state. You could then initiate a timer, which will periodically fire, notifying you that it's time to pan a little. Then when the keyreleased event fires, you can stop the timer. This way, you won't get ahead of yourself. You just need to find an appropriate value for the timer.

Similar Messages

  • KeyEvents and Events Handling

    Hi
    I'm a beginner in Java and am currently making a basic tetris game. I was trying to set the controls for the game using KeyEvents. BlueJ compiles the program but the controls dont work. Could u possibly tell me what's wrong with my code.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class KeyboardControl extends JPanel implements KeyListener
    public KeyboardControl(Game game)
    this.game = game;
    private Game game;
    public KeyboardControl()
    this.addKeyListener(this);
    public void keyTyped(KeyEvent evt)
    public void keyPressed(KeyEvent evt)
    int key = evt.getKeyCode();
    if (key == KeyEvent.VK_LEFT)
    game.moveLeft();
    else if (key == KeyEvent.VK_RIGHT)
    game.moveRight();
    else if (key == KeyEvent.VK_UP)
    game.rotate();
    else if (key == KeyEvent.VK_DOWN)
    game.drop();
    public void keyReleased(KeyEvent evt)
    }

    Thanks for your help, but it still dosen't work. I'm starting to wonder if it's got something to do with my methods for moveLeft(), moveRight() in the game class etc.
    This is the moveLeft() method I've defined in the game class:
    public void moveLeft()
    currentBlock.moveLeft();
    notifyListeners();
    I've also defined the moveLeft() method in another class called Block
    public void moveLeft()
              if (canMove(-1,0))
                   x--;
         }

  • JWindow KeyEvents and Focus

    Hi!
    I'm a little bit confused, hopefully you can help me out.
    I' have created a JWindow and I want it to receive Keyboard
    Events.
    Is that possible anyway?? If yes how??
    I have read that Windows cannot be focused and receive KeyBoard
    Events.
    My JWindow class implements the KeyListener interface and has
    Focus as well.
    Thankx

    That's my problem, it's obviously not possible for a JWindow (new JWindow())
    without a parent frame which is showing on screen to be focusable
    and therefor not possible to receive keyevents. But that is
    exacptly what I want/need to do.

  • JTextField and keyListener

    I'm trying to create an easy way of inputting data in a JTextField. I have a column of textfields, each requiring fixed-length data-input, and the idea is that the user types series of two digits continuously, without having to press ENTER or TAB between them to go to the next textfield. For this I have created a keyListener, in which the length of the textfield is checked. Strangely enough, the length of the textfield always seems to be lagging one character. For instance, I have entered a "1" (which de keyListener registers without fail), but when I check the length of the textfield in the keyListener, it returns 0, and if you do a system-output of the textfield getText, you get an empty string. If I next enter a "2", the length of the textfield is 1 according to the listener, the system-output shows "1", and so on. I am doing anything wrong?

    Well, my point was to post the code that you tested. People make stupid mistakes like using:
    public void KeyReleased(KeyEvent e)
    Note: the capital "K". If you don't post the code you use then we can't help. Myself and others do not have a problem using the keyReleased() method.
    Here's is some working code. It enables/disables some buttons based on whether text is entered in the "Find" text field:
    http://www.discoverteenergy.com/files/FindReplace.java

  • JSplitPane Active Side and KeyListener

    I have a JSplitPane as my root in a JFrame. The left side is a JTabbedPane and the right is a custom JPanel. The JPanel has its own KeyListener implemented; however key strokes are going to the left JTabbedPane. If i switch the two sides, putting the custom JPanel on the left, the keystrokes work as desired. This is not the most desirable fix though. Does anyone know how to change the "active" side of the JSplitPane?

    The JPanel has its own KeyListener implemented; however key strokes are going to the left JTabbedPane.I find this hard to believe. I'm guessing your have a programming bug and since you didn't post any code I don't know how we can help you.
    Post your [url http://www.physci.org/codes/sscce.jsp]Simple Executable Demo Code so we can see this unwanted behaviour.

  • Issues with ActionListener and KeyListener, what am i doing wrong?

    basically the program will complie, but not run properly, in appletviewer or a browser. The code for the buttons will be added later, but the test code seems to be working ok. The code for KeyListener does not move the square in the applet as it should, and when i close the applet it will dump a long error message to the dos window. if i comment out Action listener then KeyListener will work fine. if i comment out KeyListener then the applet will close with no error message to the dos window.
    i'm new to java and i don't know if i am doing anything wrong. please help, thankyou.
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class Project22 extends Applet implements KeyListener, ActionListener {
    private int score = 0;
    private int speed = 5;
    private int [] frame = {500, 500};
    private int [] sqr_loc = {235, 235};
    private char keyinput;
    private Button new_b = new Button("New Ball");
    private Button ext_app = new Button("Exit");
    private int junk = 0; // debug
    private Label message = new Label("start"); // debug
    public void actionPerformed(ActionEvent event) {
    Object source = event.getSource();
    if(source == new_b) {    // not coded yet
    ++junk;
    message.setText(Integer.toString(junk));
    else if(source == ext_app) {     // not coded yet
    ++junk;
    message.setText(Integer.toString(junk));
    public void keyTyped(KeyEvent event) {}
    public void keyPressed(KeyEvent event) {
         int keycode = event.getKeyCode();
    if(keycode == KeyEvent.VK_RIGHT) {
    if(sqr_loc[0] < 475) {
    sqr_loc[0] += speed;
    repaint();
    else if(keycode == KeyEvent.VK_LEFT) {
    if(sqr_loc[0] > 0) {
    sqr_loc[0] -= speed;
    repaint();
    else if(keycode == KeyEvent.VK_UP) {
    if(sqr_loc[1] > 0) {
    sqr_loc[1] -= speed;
    repaint();
    else if(keycode == KeyEvent.VK_DOWN) {
    if(sqr_loc[1] < 475) {
    sqr_loc[1] += speed;
    repaint();
    public void keyReleased(KeyEvent event) {}
    public void paint(Graphics g) {
    g.drawRect(sqr_loc[0], sqr_loc[1], 25, 25);
    }     // end paint
    public void init() {
    add(new_b);
    add(ext_app);
    add(message);
    new_b.addActionListener(this);
    ext_app.addActionListener(this);
    addKeyListener(this);
    requestFocus();
    }     // end Project22

    Perhaps the error message can help to determine the problem?

  • KeyEvents and JComboBox

    I havn't worked that much with JComboBox and this I can't seem to figure out.
    The JCombobox is editable and I want the user to press delete on it and something will happen.
    My code looks like this:
    ivjComboBox100.getEditor().getEditorComponent().addKeyListener(
    new KeyListener(){
    public void keyPressed(KeyEvent e){
    if (e.getKeyCode() == KeyEvent.VK_DELETE && e.getID() == KeyEvent.KEY_PRESSED){
         Dialog d = new Dialog();
    public void keyReleased(KeyEvent e){
    public void keyTyped(KeyEvent e){
    The KeyListener isn't triggered. What am i doing wrong?

    Hi,
    this code here has just been tested and it works. Hope this help.
    package com.icygen.promoteur.test;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    public class TestClass
        extends JFrame {
      JComboBox box = new JComboBox();
      public TestClass() {
        super();
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(box, BorderLayout.CENTER);
        box.setEditable(true);
        box.setEditor(new CustomComboBoxEditor());
      public class CustomComboBoxEditor
          extends BasicComboBoxEditor
          implements KeyListener {
        protected Thread invoker = new Thread() {
          public void run() {
            int result = JOptionPane.showConfirmDialog(null,
                "Are you sure whatever?", "title", JOptionPane.YES_NO_OPTION);
            System.out.println(result);
        public CustomComboBoxEditor() {
          super();
          editor.addKeyListener(this);
        public void keyPressed(KeyEvent e) {}
        public void keyReleased(KeyEvent e) {
          System.out.println("Released");
          if (e.getKeyCode() == e.VK_DELETE) {
            System.out.println("Delete");
            SwingUtilities.invokeLater(invoker);
        public void keyTyped(KeyEvent e) {}
      public static void main(String[] args) {
        new TestClass().setVisible(true);
    }

  • Thread and KeyListener

    I create a class which extends JFrame named as ShowFrame
    Another class which extends JPanel nameds as IncludePanel
    these two classes are stored in two different files named as ShowFrame.java and IncludePanel.java
    here is the code
    public class ShowFrame extends JFrame implements KeyListener,ActionListener
    IncludePanel CenterPanel;
    public ShowFrame()
    CenterPanel=new IncludePanel();
    this.addKeyListener(this);
    ........................//codes for adding buttons like start
    Container contentpane=getContentPane();
    JPanel EastPanel= new JPanel();
         JPanel WestPanel= new JPanel();
              JPanel NorthPanel= new JPanel();
              JPanel SouthPanel= new JPanel();
    .........................//add all created panels into the ContentPane
    start.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
                        start.setEnabled(false);
    CenterPanel.drawCircle();
    public class IncludePanel extends JPanel Implements Runnable
    public IncludePanel()
    this.addKeyListener(this);
         this.setFocusable(true);
    public void drawCircle( )
         th=new Thread(this);
         th.start();
    public synchronized void run()
              while(true)
    .......................// some logic which will call repaint method
    repaint();
    public void paintComponent(Graphics g)
              super.paintComponent(g);
              draw(g);
    public void draw(Graphics g)
              g.setColor(Color.red);
              g.drawLine(xx,yy,180,yy);
    My Problem is when my thread starts running at that time my KeyListener is not working.

    The code you posted is gibberish. I don't understand how you expect anyone to be able to help you from that.
    For instance: Your ShowFrame class implements KeyListener:
    public class ShowFrame extends JFrame implements KeyListener,ActionListenerbut it does not provide implementations for the KeyListener methods (as pointed out by the previous poster).
    Another example: Your IncludePanel does not implement KeyListener:
    public class IncludePanel extends JPanel Implements Runnablebut in its constructor you do this:
    public IncludePanel()
    this.addKeyListener(this);  // <------- "this" is not a KeyListenerSo, why don't you help us helping you by posting a short, compilable example program that demonstrates the problems you are having?

  • JMF and keylistener

    I guys, i'm new in jmf (fobs)world. I have coding a simple video player. My question is:
    is it possible to stop/play/pause the video whit keyboard? I'm thinking about keylistener but while the video is playing i can't I am not able to access the function to stop the video flow (is JMF blocking?).
    thanks in advance and sorry for my bad English
    regards.
    emanuele

    post your JMF question on that forum:
    http://forum.java.sun.com/forum.jspa?forumID=28

  • Using KeyEvents and Listener

    I am using JTextFields and i want when enter is pushed to check to see if the username and password is right. How do i do this i have read the api but i still don't understand.
    Here is my code and thanx for any help (note i have no features yet it is just a interface):
    *Diary
    *@Collin Doering
    *Version 1.00
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class diary extends JFrame implements KeyListener, ActionListener {
         private JLabel user, pass;
         private JTextField username;
         private JPasswordField password;
         private JMenuBar menu = new JMenuBar();
         private JMenu file, edit, font, background, tcolor, help;
         private JMenuItem open, save, saveas, exit, b8, b10, b12, b14, b16, b18, b20, b24, b30, bblue, bred, bgreen, cblue, cred, cgreen, using, about;
         public diary() {
              setSize(new Dimension(500, 500));
              setTitle("Diary 1.00");
              file = new JMenu("File");
              menu.add(file);
              open = new JMenuItem("Open");
              open.addActionListener(this);
              file.add(open);
              save = new JMenuItem("Save");
              save.addActionListener(this);
              file.add(save);
              saveas = new JMenuItem("Save as");
              saveas.addActionListener(this);
              file.add(saveas);
              exit = new JMenuItem("exit");
              exit.addActionListener(this);
              file.add(exit);
              edit = new JMenu("Edit");
              menu.add(edit);
              font = new JMenu("font");
              edit.add(font);
              b8 = new JMenuItem("8");
              b8.addActionListener(this);
              font.add(b8);
              b10 = new JMenuItem("10");
              b10.addActionListener(this);
              font.add(b10);
              b12 = new JMenuItem("12");
              b12.addActionListener(this);
              font.add(b12);
              b14 = new JMenuItem("14");
              b14.addActionListener(this);
              font.add(b14);
              b16 = new JMenuItem("16");
              b16.addActionListener(this);
              font.add(b16);
              b18 = new JMenuItem("18");
              b18.addActionListener(this);
              font.add(b18);
              b20 = new JMenuItem("20");
              b20.addActionListener(this);
              font.add(b20);
              b24 = new JMenuItem("24");
              b24.addActionListener(this);
              font.add(b24);
              b30 = new JMenuItem("24");
              b30.addActionListener(this);
              font.add(b30);
              background = new JMenu("background");
              edit.add(background);
              bblue = new JMenuItem("blue");
              bblue.addActionListener(this);
              background.add(bblue);
              bred = new JMenuItem("red");
              bred.addActionListener(this);
              background.add(bred);
              bgreen = new JMenuItem("green");
              bgreen.addActionListener(this);
              background.add(bgreen);
              tcolor = new JMenu("text color");
              edit.add(tcolor);
              cblue = new JMenuItem("blue");
              cblue.addActionListener(this);
              tcolor.add(cblue);
              cred = new JMenuItem("red");
              cred.addActionListener(this);
              tcolor.add(cred);
              cgreen = new JMenuItem("green");
              cgreen.addActionListener(this);
              tcolor.add(cgreen);
              help = new JMenu("Help");
              menu.add(help);
              using = new JMenuItem("Using");
              using.addActionListener(this);
              help.add(using);
              about = new JMenuItem("About");
              about.addActionListener(this);
              help.add(about);
              user = new JLabel("username:");
              pass = new JLabel("password:");
              username = new JTextField("");
              password = new JPasswordField("");
              password.addKeyListener(this);
              JPanel southpane = new JPanel(new GridLayout(2, 2));
              southpane.add(user);
              southpane.add(pass);
              southpane.add(username);
              southpane.add(password);
              JPanel main = new JPanel(new GridLayout(0, 1));
              getContentPane().add(menu, BorderLayout.NORTH);
              getContentPane().add(southpane, BorderLayout.SOUTH);
        public void keyTyped(KeyEvent e) {
             //coming
        public void keyPressed(KeyEvent e) {
             //coming
        public void keyReleased(KeyEvent e) {
             //coming
         public void actionPerformed(ActionEvent e) {
              //coming
         public static void main(String args[]) {
              new diary().setVisible(true);
    }

    here's a rough login
    the username/password is hard-coded, modify this to whatever you intend having
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Login extends JDialog
      String validUsername = "collin";
      String validPassword = "java";
      public Login()
        setTitle("Log in");
        setSize(250,125);
        setLocation(400,300);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        getContentPane().setLayout(new GridLayout(3,2));
        getContentPane().add(new JLabel("User name: "));
        final JTextField username = new JTextField();
        getContentPane().add(username);
        getContentPane().add(new JLabel("Password: "));
        final JPasswordField password = new JPasswordField(10);
        getContentPane().add(password);
        final JButton okBtn = new JButton("OK");
        getContentPane().add(okBtn);
        final JButton cancelBtn = new JButton("Cancel");
        getContentPane().add(cancelBtn);
        okBtn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            if(username.getText().trim().toLowerCase().equals(validUsername) &&
               (new String(password.getPassword())).trim().toLowerCase().equals(validPassword))
              new Diary().setVisible(true);
              dispose();
            else JOptionPane.showMessageDialog(getContentPane(),"invalid username/password");}});
        cancelBtn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            System.exit(0);}});
      public static void main(String[] args){new Login().setVisible(true);}
    class Diary extends JFrame implements ActionListener
      private JLabel user, pass;
      private JMenuBar menu = new JMenuBar();
      private JMenu file, edit, font, background, tcolor, help;
      private JMenuItem open, save, saveas, exit, b8, b10, b12, b14, b16, b18, b20,
                  b24, b30, bblue, bred, bgreen, cblue, cred, cgreen, using, about;
      public Diary()
        setSize(new Dimension(500, 500));
        setTitle("Diary 1.00");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(300,100);
        file = new JMenu("File");
        menu.add(file);
        open = new JMenuItem("Open");
        open.addActionListener(this);
        file.add(open);
        save = new JMenuItem("Save");
        save.addActionListener(this);
        file.add(save);
        saveas = new JMenuItem("Save as");
        saveas.addActionListener(this);
        file.add(saveas);
        exit = new JMenuItem("exit");
        exit.addActionListener(this);
        file.add(exit);
        edit = new JMenu("Edit");
        menu.add(edit);
        font = new JMenu("font");
        edit.add(font);
        b8 = new JMenuItem("8");
        b8.addActionListener(this);
        font.add(b8);
        b10 = new JMenuItem("10");
        b10.addActionListener(this);
        font.add(b10);
        b12 = new JMenuItem("12");
        b12.addActionListener(this);
        font.add(b12);
        b14 = new JMenuItem("14");
        b14.addActionListener(this);
        font.add(b14);
        b16 = new JMenuItem("16");
        b16.addActionListener(this);
        font.add(b16);
        b18 = new JMenuItem("18");
        b18.addActionListener(this);
        font.add(b18);
        b20 = new JMenuItem("20");
        b20.addActionListener(this);
        font.add(b20);
        b24 = new JMenuItem("24");
        b24.addActionListener(this);
        font.add(b24);
        b30 = new JMenuItem("24");
        b30.addActionListener(this);
        font.add(b30);
        background = new JMenu("background");
        edit.add(background);
        bblue = new JMenuItem("blue");
        bblue.addActionListener(this);
        background.add(bblue);
        bred = new JMenuItem("red");
        bred.addActionListener(this);
        background.add(bred);
        bgreen = new JMenuItem("green");
        bgreen.addActionListener(this);
        background.add(bgreen);
        tcolor = new JMenu("text color");
        edit.add(tcolor);
        cblue = new JMenuItem("blue");
        cblue.addActionListener(this);
        tcolor.add(cblue);
        cred = new JMenuItem("red");
        cred.addActionListener(this);
        tcolor.add(cred);
        cgreen = new JMenuItem("green");
        cgreen.addActionListener(this);
        tcolor.add(cgreen);
        help = new JMenu("Help");
        menu.add(help);
        using = new JMenuItem("Using");
        using.addActionListener(this);
        help.add(using);
        about = new JMenuItem("About");
        about.addActionListener(this);
        help.add(about);
        //getContentPane().add(menu, BorderLayout.NORTH);//this will cause you problems later on
        setJMenuBar(menu);
      public void actionPerformed(ActionEvent ae){}
    }

  • JTextField and keylistener HELP`!

    Hi, guys. I am working on my first java project. What i would like to have is a keylistener which detects if the key pressed is a numerical value or character. i hope you guys understand what i mean. A validation check restricting JTextFields to only accept numerical or either charaters and not both.
    Hope someone may help...
    `bluez.

    Hi ,
    just a hint: try a forum search before you post a new question was answered many times. A forum search with "numeric textfield" found this:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=107812
    Might help.
    Phil

  • JSpinner and KeyListener

    Hi...
    I have a problem with the JSpinner... How I can add a KeyEvent???
    I try this way, but it don't work:        ((JSpinner.DefaultEditor)spn_Cantidad.getEditor()).getTextField().addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e){
                    JOptionPane.showMessageDialog(null,e.getSource().toString());
            });Please help... I try different ways... but don't work...
    Regards...

    I try to run the code in a sample, and it's work fine... no problems...
    But when I try to put it in my application, it don't work... and I don't know why...
    My code is very long... up to 2300 lines... but it's not generated by NetBeans...
    The code where I have the problem is this:import java.util.*;
    import java.util.Date;
    import java.text.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
        public class Bar_Main extends JDialog implements ActionListener, KeyListener{
        JPanel Panel_Main;
        JLabel lbl_Fecha;
        JLabel lbl_Fecha_Actual;
        JLabel lbl_Producto;;
        JLabel lbl_Cantidad;
        JLabel lbl_Precio;
        JLabel lbl_Total;
        JComboBox cmb_Prod_Nom, cmb_Prod_Cod;
        JSpinner spn_Cantidad;
        JTextField txt_Precio;
        JTextField txt_Total;
        //javax.swing.Timer tmr_Reloj;
        java.util.Date Fecha;
        DateFormat frmt_Fecha;
        //SimpleDateFormat frmt_Hora;
        Connection conec;
        Statement state;
        ResultSet rec;
        public Bar_Main(){
            setTitle("Consumo de Bar");
            setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            try{
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                conec = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/POOL/Data/BaseDat.MDB");
                state = conec.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            }catch(Exception e){}
            frmt_Fecha = DateFormat.getDateInstance(DateFormat.FULL);
            Fecha = new java.util.Date();
            Panel_Main = new JPanel(null);
            Panel_Main.setBackground(Color.GREEN.darker());              
            lbl_Fecha = new JLabel("Fecha");
            lbl_Fecha.setBounds(20,20,80,20);
            lbl_Fecha_Actual = new JLabel(frmt_Fecha.format(Fecha).toUpperCase());
            lbl_Fecha_Actual.setBounds(130,20,230,20);
            lbl_Producto = new JLabel("Elija Producto");
            lbl_Producto.setBounds(20,50,80,20);
            cmb_Prod_Nom = new JComboBox(Cargar_Combo_Nom());
            cmb_Prod_Nom.setBounds(130,50,230,20);
            cmb_Prod_Nom.addActionListener(this);
            cmb_Prod_Cod = new JComboBox(Cargar_Combo_Cod());
            lbl_Cantidad = new JLabel("Cantidad");
            lbl_Cantidad.setBounds(20,80,80,20);
            spn_Cantidad = new JSpinner();
            spn_Cantidad.setBounds(130,80,50,20);
                    ((JSpinner.DefaultEditor)spn_Cantidad.getEditor()).getTextField().addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e){
                    JOptionPane.showMessageDialog(null,e.getKeyChar());
            lbl_Precio = new JLabel("Valor Unitario");
            lbl_Precio.setBounds(20,110,80,20);
            txt_Precio = new JTextField("");
            txt_Precio.setBounds(130,110,50,20);
            txt_Precio.setHorizontalAlignment(JTextField.RIGHT);
            txt_Precio.setEnabled(false);
            txt_Precio.setDisabledTextColor(Color.DARK_GRAY);
            try{
                rec = state.executeQuery("Select * from Productos where prod_id = " + cmb_Prod_Cod.getSelectedItem());
                rec.absolute(1);
                spn_Cantidad.setModel(new SpinnerNumberModel(1,1,rec.getInt("prod_cant"),1));
                txt_Precio.setText(Integer.toString(rec.getInt("prod_precio")));
            }catch(Exception e){JOptionPane.showMessageDialog(null,e.getMessage());}
            Panel_Main.add(lbl_Fecha); Panel_Main.add(lbl_Fecha_Actual);
            Panel_Main.add(lbl_Producto); Panel_Main.add(cmb_Prod_Nom);
            Panel_Main.add(lbl_Cantidad); Panel_Main.add(spn_Cantidad);
            Panel_Main.add(lbl_Precio); Panel_Main.add(txt_Precio);
            setLayout(new BorderLayout());
            add(Panel_Main,BorderLayout.CENTER);
            setSize(600,400);
            setLocationRelativeTo(null);
            setModal(true);
            setVisible(true);
        public DefaultComboBoxModel Cargar_Combo_Nom(){
            DefaultComboBoxModel model = new DefaultComboBoxModel();
            try{           
                rec = state.executeQuery("Select * from Productos where prod_cant > 0 order by prod_nom");
                rec.first();
                while(rec.isAfterLast() == false){
                    model.addElement(rec.getString("prod_nom"));
                    rec.next();
            }catch(Exception e){}
            return model;
        public DefaultComboBoxModel Cargar_Combo_Cod(){
            DefaultComboBoxModel model = new DefaultComboBoxModel();
            try{
                rec = state.executeQuery("Select * from Productos where prod_cant > 0 order by prod_nom");
                rec.first();
                while(rec.isAfterLast() == false){
                    model.addElement(rec.getString("prod_id"));
                    rec.next();
            }catch(Exception e){}
            return model;
        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource().equals(cmb_Prod_Nom)){
                cmb_Prod_Cod.setSelectedIndex(cmb_Prod_Nom.getSelectedIndex());
                try{
                    rec = state.executeQuery("Select * from Productos where prod_id = " + cmb_Prod_Cod.getSelectedItem());
                    rec.absolute(1);
                    spn_Cantidad.setModel(new SpinnerNumberModel(1,1,rec.getInt("prod_cant"),1));
                    txt_Precio.setText(Integer.toString(rec.getInt("prod_precio")));
                }catch(Exception e){}
        public void keyPressed(KeyEvent e) {
        public void keyReleased(KeyEvent e) {
        public void keyTyped(KeyEvent e) {
    }Please help me...
    Regards...

  • Jfilechooser and keylistener

    hi,
    I'm a noob in java. I have a simple application to open file with JFileChooser. When I press down key on keyboard the selection go down etc. For istance, if want to obtain the same thing pressing "p" key, what could I do??
    Is it possible?
    sorry for my bad english and for the dummy question
    regards

    1) for exercise and understand how keyboard and jfilechooser interactsWell, the key board and jfilechooser don't interact. JFileChooser is simply a panel consisting of other components added to the panel. So the keyboard interacts with the other components added to the panel.
    So start with something simpler if you want to understand how KeyStrokes and Actions are used in Swing. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings.
    Since the JFileChooser appears to be using a JList you would then need to understand how the key bindings are used on the list. You would then need to somehow access the list from the UI or simply iterate through all the components added to the JFileChooser until you find a JList. Once you find the JList you can then assign the "P" keystroke to the same action as is being used by the "down" keystroke.

  • Big JTextArea and KeyListener problem

    Hi guys. I am using a key listener on a JTextArea to ckeck for the enter key pressed as follows:
    ta_userMessage.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent ke) {
                        int thisKey = ke.getKeyCode();
                        if (thisKey == KeyEvent.VK_ENTER) {
                             ta_userMessage.setText("");                    }
    When i press the enter key, after the text area is cleared, the caret is automatically positioned on the second line. how do i avoid this? I tried replaceSelection() and setCaretPosition(). (Does not work). Is there any way to solve this or use any other listener to test for the enter key pressed?

    try consuming the event in order for it not to be taken into account :
    ke.consume();
    If that does not work, you may want to work on the document associated with the field.

  • Map KeyEvents to proper char in all locales

    I am trying to create a mini VI clone. As such, I need to intercept KeyEvents and take actions based on those keys. So for instance, when a user hits the '@' key (eg SHIFT-2 on the US keyboard) I want to have a '@' printed to the display when I am in Insert mode. This is easy on the US keyboard because I know that a SHIFTED KeyEvent.VK_2 should produce a '@'. Unfortunately this only works on the US keyboard layout. If I choose the Spanish keyboard layout the SHIFT-2 key produces a '!' There are many other examples of this disjoint.
    So how do I get a mapping of the keys so I can identify from a KeyListener what key they actually pressed in their locale? (eg if the spanish user pressed his SHIFT-2 he expects a '!' not a '@' but the KeyEvent I get is a SHIFTED VK_2 and I have no idea what keystroke he intended that to be.)

    I'm having the same problem!
    I'm using the javascript API and calling RH_ShowHelp(0, helpPath + "/CSH/iSupportHelp.htm>SecondaryWindow", HH_HELP_CONTEXT, mapId);
    Which generates this url and opens it in a new window: http://localhost/rep/Help/CSH/iSupportHelp.htm#<id=16>>wnd=SecondaryWindow
    The new window then does more script processing and ends up with this url: http://localhost/rep/help/CSH/iSupportHelp.htm#<id=16%3E%3Ewnd%3DSecondaryWindow&t=Overvie w%2FiSupport_Overview.htm
    It doesnt matter what mapId I pass in, I always get the default topic.
    We just upgraded from RH10 to RH11 and we're trying to use the new responsive html5 output.

Maybe you are looking for

  • Firefox crashes all the time, even in safe mode. Unable to even bring up profile manager

    This just started a few days ago, when it updated to 33.0. Windows 7 on a laptop I have run a malware scan and it found nothing. I've tried uninstalling and reinstalling, still crashes I've tried to create a new profile, and profile manager won't sta

  • Ap_selected_invoices_all Payment_Priority

    Hi All, I am selecting payment_priority and one more column for check printing from table ap_selected_invoices_all. However this table does not return any record when I am paying single invoice thorugh Quick Pay. Please tell me which tables are popul

  • Can I filter a liked photo from a lightroom mobile public link?

    New to Lightroom so maybe I'm missing it but when someone likes a photo from a lightroom mobile public link how can I have a smart collection filter it? I understand how to if they add a comment but that is time consuming for them, liking a photo and

  • Question Outbound Price Catalogue (VPRICAT) - Scales

    Hi to all, does anybody now how to activate scales in Outbound Price Catalogue (TCode VPRICAT)? Although we have maintained scale for price condition in TCode VK11/VK12, scales are not determined in Price Catalogue. Thank you for your help. BR, Simon

  • C7 - Problem with text messages - Help please!

    I have had my Nokia C7 since November and have not been able to use it! When I send a text message less than 160 characters I am charged between 2 and 3 times on my bill. The text message is being sent once and the recipient is receiving the text onc