Valhalla Legends Forums Archive | Java Programming | Detecting Keyboard Events

AuthorMessageTime
Dyndrilliac
I'm having trouble detecting keyboard events in my program. I'm implementing KeyListener in my JFrame, and I'm registering it in my constructor, but I don't get any hits on my JOptionPanes when in Debug Mode despite banging on the keyboard. What am I doing wrong? My end goal in this regard is to enable the Enter key to activate a mouse click on the Throw button when pressed, and add keyboard shortcuts to the menu.

[code]
package games.dicebag.gui;

import games.dicebag.*;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;

public class DiceBagDemo extends JFrame implements ActionListener, KeyListener
{
private static final int WINDOW_WIDTH  = 800;
private static final int WINDOW_HEIGHT = 600;

private boolean  bDebugMode  = false;
private String    strFilePath = null;
private JButton  btnThrow    = null;
private JComboBox txtInput    = null;
private JTextPane txtOutput  = null;

private SimpleDateFormat dateFormat = new SimpleDateFormat("MM.dd.yyyy hh:mm:ss a z");

public static void main(String[] args)
{
DiceBagDemo diceBag = null;
int intDebugChoice = JOptionPane.showConfirmDialog(null, "Do you wish to activate debug mode?", "Debug Mode", JOptionPane.YES_NO_OPTION);

if (intDebugChoice == JOptionPane.YES_OPTION)
{
diceBag = new DiceBagDemo(true);
}
else if (intDebugChoice == JOptionPane.NO_OPTION)
{
diceBag = new DiceBagDemo(false);
}
else
{
return;
}

diceBag.setVisible(true);
}

public DiceBagDemo(boolean bDebugMode)
{
super("Dice Bag");
this.bDebugMode = bDebugMode;
this.setSize(new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.addKeyListener(this);
this.drawGUI();
}

public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();

if (this.bDebugMode)
{
JOptionPane.showMessageDialog(this, "What: " + actionCommand + "\nWhere: " + e.getSource().getClass().getSimpleName() + " (" + e.getSource().getClass().getCanonicalName() + ")" + "\nWhen: " + this.getDateTimeStamp(), "Event Occurred", JOptionPane.INFORMATION_MESSAGE);
}

if (actionCommand.equals("Throw"))
{
if (((String)this.txtInput.getSelectedItem() != null) && (checkInput((String)this.txtInput.getSelectedItem())))
{
if (this.bDebugMode)
{
JOptionPane.showMessageDialog(this, "Input: " + (String)this.txtInput.getSelectedItem() + "\nWhen: " + this.getDateTimeStamp(), "Input Received", JOptionPane.INFORMATION_MESSAGE);
}

this.processInput((String)this.txtInput.getSelectedItem());

if (this.txtInput.getSelectedIndex() == -1)
{
this.txtInput.addItem((String)this.txtInput.getSelectedItem());
}

this.txtInput.setSelectedIndex(-1);
this.txtInput.grabFocus();
}
else
{
JOptionPane.showMessageDialog(this, "Improperly formatted input. Please check your input and try again.\n", "Input Invalid", JOptionPane.ERROR_MESSAGE);

this.txtInput.setSelectedIndex(-1);
this.txtInput.grabFocus();
}
}

if (actionCommand.equals("Clear"))
{
this.resetOutput();
this.txtInput.grabFocus();
}

if (actionCommand.equals("Open"))
{
this.fileOperation(actionCommand);
this.txtInput.grabFocus();
}

if (actionCommand.equals("Save"))
{
this.fileOperation(actionCommand);
this.txtInput.grabFocus();
}
}

public void keyPressed(KeyEvent e)
{
if (this.bDebugMode)
{
JOptionPane.showMessageDialog(this, "What: " + e.getKeyCode() + "\nWhere: " + e.getSource().getClass().getSimpleName() + " (" + e.getSource().getClass().getCanonicalName() + ")" + "\nWhen: " + this.getDateTimeStamp(), "Key Pressed", JOptionPane.INFORMATION_MESSAGE);
}
}
public void keyTyped(KeyEvent e)
{
if (this.bDebugMode)
{
JOptionPane.showMessageDialog(this, "What: " + e.getKeyCode() + "\nWhere: " + e.getSource().getClass().getSimpleName() + " (" + e.getSource().getClass().getCanonicalName() + ")" + "\nWhen: " + this.getDateTimeStamp(), "Key Typed", JOptionPane.INFORMATION_MESSAGE);
}
}

public void keyReleased(KeyEvent e)
{
if (this.bDebugMode)
{
JOptionPane.showMessageDialog(this, "What: " + e.getKeyCode() + "\nWhere: " + e.getSource().getClass().getSimpleName() + " (" + e.getSource().getClass().getCanonicalName() + ")" + "\nWhen: " + this.getDateTimeStamp(), "Key Released", JOptionPane.INFORMATION_MESSAGE);
}
}

private void drawGUI()
{
Container contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout());

JMenu fileMenu = new JMenu("File");
JMenuItem m;

m = new JMenuItem("Clear");
m.addActionListener(this);
fileMenu.add(m);

m = new JMenuItem("Open");
m.addActionListener(this);
fileMenu.add(m);

m = new JMenuItem("Save");
m.addActionListener(this);
fileMenu.add(m);

JMenuBar mBar = new JMenuBar();
mBar.add(fileMenu);
this.setJMenuBar(mBar);

this.txtOutput = new JTextPane();
this.resetOutput();
this.txtOutput.setFocusable(false);
this.txtOutput.setEditable(false);
this.txtOutput.setFont(new Font("Lucida Console", Font.PLAIN, 14));
JScrollPane outputPanel = new JScrollPane(this.txtOutput);

JPanel inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());

this.txtInput = new JComboBox();
this.txtInput.setFont(new Font("Lucida Console", Font.PLAIN, 14));
this.txtInput.setEditable(true);
this.txtInput.setPreferredSize(new Dimension(600, 20));
this.txtInput.addActionListener(this);
inputPanel.add(this.txtInput);

this.btnThrow = new JButton("Throw");
this.btnThrow.setPreferredSize(new Dimension(100, 20));
this.btnThrow.addActionListener(this);
inputPanel.add(this.btnThrow);

contentPane.add(outputPanel, BorderLayout.CENTER);
contentPane.add(inputPanel, BorderLayout.SOUTH);
}

private void fileOperation(String strType)
{
int intChoice = 0;

JFileChooser fc = new JFileChooser();

if (strType.equals("Open"))
{
intChoice = fc.showOpenDialog(this);
}
else if (strType.equals("Save"))
{
intChoice = fc.showSaveDialog(this);
}
else
{
return;
}

if (intChoice == JFileChooser.APPROVE_OPTION)
{
try
{
this.strFilePath = fc.getSelectedFile().getCanonicalPath();

if (strType.equals("Open"))
{
FileIO.openOutputFile(this.txtOutput, this.strFilePath);
}
else if (strType.equals("Save"))
{
FileIO.saveOutputFile(this.txtOutput, this.strFilePath);
}
else
{
return;
}

if (this.bDebugMode)
{
JOptionPane.showMessageDialog(this, "File Path: " + this.strFilePath + "\nWhen: " + this.getDateTimeStamp(), "File Accessed", JOptionPane.INFORMATION_MESSAGE);
}
}
catch(Exception err)
{
JOptionPane.showMessageDialog(this, "Unable to access file.\nSource File: " + err.getStackTrace()[0].getFileName() + "\nLine Number: " + err.getStackTrace()[0].getLineNumber(), "Internal Error", JOptionPane.ERROR_MESSAGE);
err.printStackTrace();
}
}
}

private boolean checkInput(String strInput)
{
return strInput.matches("[0-9]+d[0-9]+");
}

private void processInput(String strInput)
{
String[] strParamArray  = strInput.split("d");
int[]    intResultsArray = DiceBag.throwDice(Integer.parseInt(strParamArray[0]), Integer.parseInt(strParamArray[1]));

StringBuilder output = new StringBuilder();

for (int i = 0; i < intResultsArray.length-1; i++) { output.append(intResultsArray[i] + " "); }

this.appendOutput(Color.GRAY, "Results: ", Color.RED, output.toString() + "\n", Color.GRAY, "Sum:    ", Color.BLUE, intResultsArray[intResultsArray.length-1] + "\n\n");
}

private void appendOutput(Object... oArgs)
{
if ((oArgs.length % 2) != 0)
{
JOptionPane.showMessageDialog(this, "appendOutput(Object[] oArgs) recieved a bad list of arguments.\n", "Internal Error", JOptionPane.ERROR_MESSAGE);
return;
}

this.appendOutput(this.txtOutput, Color.BLACK, "[" + this.getDateTimeStamp() + "]\n");

for (int i = 0; i < oArgs.length; i += 2) { this.appendOutput(this.txtOutput, (Color)oArgs[i], oArgs[i+1].toString()); }
}

private void appendOutput(JTextPane o, Color c, String s)
{
StyleContext sc = StyleContext.getDefaultStyleContext();

AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

try
{
o.getDocument().insertString(o.getDocument().getLength(), s, aset);
}
catch (BadLocationException e)
{
JOptionPane.showMessageDialog(this, "BadLocationException thrown in appendOutput(JTextPane o, Color c, String s).\nSource File: " + e.getStackTrace()[0].getFileName() + "\nLine Number: " + e.getStackTrace()[0].getLineNumber(), "Internal Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}

private void resetOutput()
{
StyledEditorKit sek = new StyledEditorKit();
this.txtOutput.setEditorKit(sek);
this.txtOutput.setDocument(sek.createDefaultDocument());
}

private String getDateTimeStamp()
{
return this.dateFormat.format(new Date());
}
}
[/code]

Edit:

FileIO static class:
[code]
package games.dicebag.gui;

import java.io.*;
import javax.swing.JTextPane;
import javax.swing.text.Document;

public class FileIO
{
public static final void openOutputFile(JTextPane pane, String strFilePath)
{
ObjectInputStream inputStream = null;

try
{
inputStream = new ObjectInputStream(new FileInputStream(strFilePath));
pane.setDocument((Document)inputStream.readObject());
inputStream.close();
}
catch(Exception e)
{
System.out.println("Reading from the file failed.\n");
e.printStackTrace();
}
}

public static final void saveOutputFile(JTextPane pane, String strFilePath)
{
ObjectOutputStream outputStream = null;

try
{
outputStream = new ObjectOutputStream(new FileOutputStream(strFilePath));
outputStream.writeObject(pane.getDocument());
outputStream.close();
}
catch(Exception e)
{
System.out.println("Writing to the file failed.\n");
e.printStackTrace();
}
}
}
[/code]

DiceBag static class:
[code]
package games.dicebag;

import java.util.Random;

public class DiceBag
{
public static final int[] throwDice(int intNumberOfDice, int intNumberOfSides)
{
int[] intResultsArray = new int[intNumberOfDice+1];

for (int i = 0; i < intNumberOfDice; i++) { intResultsArray[i] = getRandomInteger(1, intNumberOfSides, true); }

intResultsArray[intNumberOfDice] = getSumFromIntegerArray(intResultsArray);

return intResultsArray;
}

private static final int getRandomInteger(int intMin, int intMax, boolean bIsRangeInclusive)
{
Random rand = new Random(System.nanoTime());

if (bIsRangeInclusive)
{
return (rand.nextInt(intMax - intMin + 1) + intMin);
}
else
{
return (rand.nextInt(intMax - intMin) + intMin);
}
}

private static final int getSumFromIntegerArray(int[] ArrayOfIntegers)
{
int intSum = 0;

for (int i = 0; i < ArrayOfIntegers.length; i++) { intSum += ArrayOfIntegers[i]; }

return intSum;
}
}
[/code]
March 13, 2012, 2:33 AM

Search