Question

I have this class. This class paints 3 buttons, and I have an event associated with each button. I need to create an event for the keyboard, pressing a key will be the same as pressing one of the buttons. This is my class:

public class ShapedDialog extends JDialog implements KeyListener, ActionListener {

private final MainWindow parent;

public ShapedDialog(MainWindow parent, String title) {
    super(parent, title, true);
    this.parent = parent;

    if (parent != null) {
        Dimension parentSize = parent.getSize();
        Point p = parent.getLocation();
        setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4);
    }

    JPanel messagePane = new JPanel();
    messagePane.add(new JLabel());
    getContentPane().add(messagePane);

    JPanel buttonPane = new JPanel();

    //JButton1
    JButton jButton1 = new JButton();
    try {
        Image img = ImageIO.read(getClass().getResource("logo.png"));
        jButton1.setIcon(new ImageIcon(img));
    } catch (IOException ex) {
    }
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    //JButton2
    JButton jButton2 = new JButton();
    try {
        Image img = ImageIO.read(getClass().getResource("logo.png"));
        jButton2.setIcon(new ImageIcon(img));
    } catch (IOException ex) {
    }
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    //JButton3
    JButton jButton3 = new JButton();
    try {
        Image img = ImageIO.read(getClass().getResource("logo.png"));
        jButton3.setIcon(new ImageIcon(img));
    } catch (IOException ex) {
    }
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    //Add buttons in the panel
    buttonPane.setLayout(new GridLayout(3, 3));
    buttonPane.add(jButton1);
    buttonPane.add(jButton2);
    buttonPane.add(jButton3);

    getContentPane().add(buttonPane, BorderLayout.SOUTH);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    pack();
    setVisible(true);
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here
    setVisible(false);
    parent.setMyPackage("Type 1");
    dispose();
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here
    setVisible(false);
    parent.setMyPackage("Type 2");
    dispose();
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here
    setVisible(false);
    parent.setMyPackage("Type 3");
    dispose();
}

@Override
public void actionPerformed(ActionEvent e) {
    setVisible(false);
    parent.setMyPackage("Type Package");
    dispose();
}

    public static void main(String[] a) {
        JTextField component = new JTextField();
        component.addKeyListener(new MyKeyListener());

        ShapedDialog dlg = new ShapedDialog((MainWindow) new JFrame(), "title");
    }

    @Override
    public void keyTyped(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyPressed(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyReleased(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

class MyKeyListener extends KeyAdapter {
    public void keyPressed(KeyEvent evt) {
        if (evt.getKeyChar() == 'a') {
            System.out.println("Check for key characters: " + evt.getKeyChar());
        }
        if (evt.getKeyCode() == KeyEvent.VK_HOME) {
            System.out.println("Check for key codes: " + evt.getKeyCode());
        }
    }
}

Someone can help me??

Was it helpful?

Solution

I need to create an event for the keyboard, pressing a key will be the same as pressing one of the buttons.

You need to:

  1. Create an Action to be used by each button. See How to Use Actions
  2. Create the JButton using the Action
  3. Create Key Bindings for the Action and KeyStroke. See How to Use Key Bindings

Simple example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                display.setCaretPosition( display.getDocument().getLength() );
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0, 5) );
        add(buttonPanel, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(50, 50) );
            buttonPanel.add( button );

            KeyStroke pressed = KeyStroke.getKeyStroke(text);
            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(pressed, text);
            button.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
//      UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );

        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top