I'm making a system to convert Morse cord to English alphabet. I'm using JTextfeild called "write" to type text and another JTextfeild call "View" to view which is typed on write.
But I can only set one Morse cord for one time.
As an example if I type A on "Write" textfeild it it is only printing ".-" . And when I type "B" again then view textfeild set "-..." . I want to print number of letters.
Given below is my source cord.
private void writeKeyReleased(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == 65) {
view.setText(".-");
} else if (evt.getKeyCode() == 66) {
view.setText("-...");
} else if (evt.getKeyCode() == 67) {
view.setText("-.-.");
} else if (evt.getKeyCode() == 68) {
view.setText("-..");
} else if (evt.getKeyCode() == 69) {
view.setText(".");
} else if (evt.getKeyCode() == 70) {
view.setText("..-.");
} else if (evt.getKeyCode() == 71) {
view.setText("--.");
} else if (evt.getKeyCode() == 72) {
view.setText("....");
} else if (evt.getKeyCode() == 73) {
view.setText("..");
} else if (evt.getKeyCode() == 74) {
view.setText(".---");
} else if (evt.getKeyCode() == 75) {
view.setText(".-.-");
} else if (evt.getKeyCode() == 76) {
view.setText(".-..");
} else if (evt.getKeyCode() == 77) {
view.setText("--");
} else if (evt.getKeyCode() == 78) {
view.setText("-.");
} else if (evt.getKeyCode() == 79) {
view.setText("---");
} else if (evt.getKeyCode() == 80) {
view.setText(".--.");
} else if (evt.getKeyCode() == 81) {
view.setText("--.-");
} else if (evt.getKeyCode() == 82) {
view.setText(".-.");
} else if (evt.getKeyCode() == 83) {
view.setText("...");
} else if (evt.getKeyCode() == 84) {
view.setText("-");
} else if (evt.getKeyCode() == 85) {
view.setText("..-");
} else if (evt.getKeyCode() == 86) {
view.setText("...-");
} else if (evt.getKeyCode() == 87) {
view.setText(".--");
} else if (evt.getKeyCode() == 88) {
view.setText("-..-");
} else if (evt.getKeyCode() == 89) {
view.setText("-.--");
} else {
view.setText("--..");
}
}
I'm making a system to convert Mose cord to English alphabet. I'm
using jtextfeild called "write" to type text and another jtextfeild
call "View" to view which is typed on write.
use DocumentListener for JTextComponents instead of low_level KeyListener, otheriwise you can't be able to input sequence of chars from (for example) Ctrl+C (SystemClipBoard), or remove selected chars, then output to anther JComponents freeze without any, no changes are made, because KeyListener can firing an Event from single Char only
plus you can use DocumentFilter in the case that you want to replace, remove, modify single char or chars sequence typed by user into JTextField
for example
import java.awt.GridLayout;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class TextLabelMirror {
private JPanel mainPanel = new JPanel();
private JTextField field = new JTextField(20);
private JTextField field1 = new JTextField(20);
public TextLabelMirror() {
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
field1.setText(field.getText());
}
});
}
});
mainPanel.setLayout(new GridLayout(1, 0, 10, 0));
mainPanel.add(field);
mainPanel.add(field1);
}
public JComponent getComponent() {
return mainPanel;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("TextLabelMirror");
frame.getContentPane().add(new TextLabelMirror().getComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowUI();
}
});
}
}
You should not use the event that way. Get the 'write' text as string and work on it:
private void writeKeyReleased(java.awt.event.KeyEvent evt) {
String input = write.getText();
StringBuilder output = new StringBuilder();
for(int cIndx = 0; cIndx < input.length(); ++cIndx){
output.append(convertChar(input.charAt(cIndx)));
}
}
private String convertChar(char c)
{
// TODO Your conversion method, modified a little:
if( c == 'a' || c == 'A') return ".-";
if( c == 'b' || c == 'B') return "-...";
// etc....
return ""; // handle as you like this case.
}
Related
i am trying to take keyboard inputs to change the boolean's value but keylisteners are not working
those bolleans values will be used later in other class
heres the method i am having issues with
public boolean upPressed, downPressed, leftPressed, rightPressed;
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_W){
upPressed = true;}
else if(code == KeyEvent.VK_S){
downPressed = true;}
else if(code == KeyEvent.VK_A){
leftPressed = true;}
else if(code == KeyEvent.VK_D){
rightPressed = true;}
}
i am using a different class which extends JPanel, frame is in a different class and key listener is in a different class and i have this.setFocusable(true);this.addKeyListener(keyH);
and if u want, here's the full code : https://github.com/PROMAN8625/2dGAME
Your code snippet looks fine. Maybe you didn't add KeyListener to the frame.
Here is a working example:
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyListenerExample implements KeyListener
{
public boolean upPressed, downPressed, leftPressed, rightPressed;
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e)
{
int code = e.getKeyCode();
if (code == KeyEvent.VK_W) {
upPressed = true;
}
else if(code == KeyEvent.VK_S){
downPressed = true;}
else if(code == KeyEvent.VK_A){
leftPressed = true;}
else if(code == KeyEvent.VK_D){
rightPressed = true;}
System.out.println("The key Pressed was: " + e.getKeyChar());
System.out.println("upPressed: " + upPressed);
System.out.println("downPressed: " + downPressed);
System.out.println("leftPressed: " + leftPressed);
System.out.println("rightPressed: " + rightPressed);
System.out.println("\n");
}
#Override
public void keyReleased(KeyEvent e) {
}
public static void main(String[] args)
{
//Setting the Frame and Labels
Frame f = new Frame("Demo");
f.setLayout(new FlowLayout());
f.setSize(500, 500);
Label l = new Label();
l.setText("This is a demonstration");
f.add(l);
f.setVisible(true);
//Creating and adding the key listener
KeyListenerExample k = new KeyListenerExample();
f.addKeyListener(k);
}
}
I will only supply the relevant parts of the code as it is quite large. Help me figure out why I never get keyboard events to the GameBoard JPanel. The game code runs just fine until I added the new feature where I wanted it to have a welcome screen.
Edit: If you would like to view the entire project (it's an eclipse project), here is the link to download it Eclipse project, I honestly can't format almost 1000 lines of code here on StackOverflow, that'll be painful even for you.
Main.java
private void initUI() throws IOException {
cardLayout = new CardLayout();
mainPanel = new JPanel(cardLayout);
welcomeMenu = new Welcome(cardLayout, mainPanel);
mainPanel.add(welcomeMenu, "welcome");
game = new GameBoard();
mainPanel.add(game, "game");
add(mainPanel);
setTitle("Pacman");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(380, 420);
setLocationRelativeTo(null);
}
This is the welcome/menu panel (some section of it).
Welcome.java (servers as a menu)
#Override
public void actionPerformed(ActionEvent evt) {
if (evt.getActionCommand() == Actions.EXIT.name()) {
System.exit(0);
} else if (evt.getActionCommand() == Actions.CONFIG.name()) {
JOptionPane.showMessageDialog(null, "Not yet implemented");
} else if (evt.getActionCommand() == Actions.PLAY.name()) {
// The part that switches to game, works as expected.
cl.show(mp, "game");
}
}
GameBoard class has a KeyAdapter class within it that is used to listen to key events, however, in the addition of the new feature using CardLayout, I could not get the key events to the panel so my PacMan is just stuck in one place opening and closing its mouth like a fish.
GameBoard.java
private void initBoard() {
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.black);
initGame();
}
...
class TAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (inGame) {
if (key == KeyEvent.VK_LEFT) {
req_dx = -1;
req_dy = 0;
} else if (key == KeyEvent.VK_RIGHT) {
req_dx = 1;
req_dy = 0;
} else if (key == KeyEvent.VK_UP) {
req_dx = 0;
req_dy = -1;
} else if (key == KeyEvent.VK_DOWN) {
req_dx = 0;
req_dy = 1;
} else if (key == KeyEvent.VK_ESCAPE && timer.isRunning()) {
inGame = false;
} else if (key == KeyEvent.VK_PAUSE) {
if (timer.isRunning()) {
timer.stop();
} else {
timer.start();
}
}
} /*
* else { if (key == 's' || key == 'S') { inGame = true; initGame(); } }
*/
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == Event.LEFT || key == Event.RIGHT || key == Event.UP || key == Event.DOWN) {
req_dx = 0;
req_dy = 0;
}
}
}
The issue was using Key Listener when I should have been using Key Binding in the GameBoard JPanel. So instead of this,
class TAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (inGame) {
...
} else if (key == KeyEvent.VK_UP) {
req_dx = 0;
req_dy = -1;
} else if (key == KeyEvent.VK_DOWN) {
...
}
}
}
I replaced it with this approach (I will only demonstrate Arrow Up scenario),
private class UpAction extends AbstractAction {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (!inGame)
return;
req_dx = 0;
req_dy = -1;
}
}
...
private void setupKeyListeners() {
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "doUp");
...
getActionMap().put("doUp", new UpAction());
...
}
And later on,
private void initBoard() {
setupListeners();
setFocusable(true);
setBackground(Color.black);
initGame();
}
I've got an applet that pops up a dialog to enter credit card details.
I'm using four JFormattedTextField classes to allow the user to input each 4 digit fragment of the credit card. I've got code in place to auto tab to the next field as the user is typing out the CC number. The problem is that when the dialog is launched from an applet running in IE8 using ( I'm restricted to using Java 7 update 13), if the user types in the number quickly, spaces appear to be inserted apparently at random even though a mask is applied to only allow alpha-numerics.
The code below is are the listeners on the the JFormattedTextField class where I suspect the issue resides.
super.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent event) {
EntryField field = (EntryField)event.getSource();
if (_initialPosition > 0) {
// if the initial position is set externally. This will happen when the caret is being set during
// the initial load of the dialog.
field.select(0, 0);
field.setCaretPosition(_initialPosition);
_initialPosition = -1;
}
else if (event.getOppositeComponent() == field.getNextControl()) {
field.select(0, 0);
field.setCaretPosition(field.getMaxCharacters()-1);
}
else {
field.select(0, 0);
field.setCaretPosition(0);
}
}
#Override
public void focusLost(FocusEvent event) {}
});
this.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent keyEvent) {
if(keyEvent.getKeyChar() == KeyEvent.VK_BACK_SPACE) {
EntryField field = (EntryField) keyEvent.getSource();
if (field.getCaretPosition() == 0 && field.hasPreviousControl()) {
field.backtrackFocus(true);
}
}
else if(Character.isLetterOrDigit(keyEvent.getKeyChar())) {
EntryField field = (EntryField) keyEvent.getSource();
if (field.getCaretPosition() == field.getMaxCharacters() - 1) {
field.moveFocus();
}
}
else if(keyEvent.getKeyCode() == KeyEvent.VK_LEFT) {
EntryField field = (EntryField) keyEvent.getSource();
if (field.getCaretPosition() == 0 && field.hasPreviousControl()) {
field.backtrackFocus(false);
}
}
else if(keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) {
EntryField field = (EntryField) keyEvent.getSource();
if(field.getCaretPosition() == field.getMaxCharacters() - 1 && field.hasNextControl()) {
field.moveFocus();
}
}
else if(keyEvent.isControlDown() && keyEvent.getKeyChar() == 'c') {
EntryField field = (EntryField) keyEvent.getSource();
field.paste();
}
}
#Override
public void keyTyped(KeyEvent keyEvent) {
if (_checkAmEx && Character.isLetterOrDigit(keyEvent.getKeyChar())) {
EntryField field = (EntryField)keyEvent.getSource();
int pos = field.getCaretPosition();
if (pos == 2 && creditCardIsAmex()) {
field.moveFocus();
}
}
else if(keyEvent.getKeyChar() == KeyEvent.VK_DELETE) {
EntryField field = (EntryField) keyEvent.getSource();
field.setCaretPosition(field.getCaretPosition() - 1);
field.shiftTextLeft();
}
else if(keyEvent.getKeyChar() == KeyEvent.VK_BACK_SPACE) {
EntryField field = (EntryField) keyEvent.getSource();
field.shiftTextLeft();
}
}
#Override
public void keyReleased(KeyEvent keyEvent) {}
});
I'm trying to use Java's KeyListener to update a JLabel as I type. Essentially, I'm making my own text field. Here's what I have:
/**
* Constructor for objects of class Dictionary
*/
public Dictionary()
{
frame = new JFrame();
frame.setTitle("Shori Dictionary");
frame.setLayout(new GridBagLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createWord()
{
frame.remove(pane);
pane = new PaintPane(field.getImage());
pane.setLayout(new BorderLayout());
frame.add(pane);
frame.pack();
newWord = new JLabel(text);
newWord.setFont(newWord.getFont().deriveFont(Font.BOLD, 28));
newWord.setForeground(Color.BLACK);
newWord.setHorizontalTextPosition(JLabel.LEFT);
newWord.setVerticalAlignment(JLabel.TOP);
newWord.setVerticalTextPosition(JLabel.TOP);
newWord.setBorder(BorderFactory.createEmptyBorder(445, 150, 0, 0));
pane.add(newWord);
frame.pack();
frame.setLocationRelativeTo(null);
pane.setFocusable(true);
updateInteraction();
}
private void keyPress()
{
pane.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent e) {
for(int i = 97; i <= 122; i++){
//Cycles through every lowercase letter
if(e.getKeyChar() == (char)(i)&& pane.returnImage() == field.getImage()){
text += (char)(i);
break;
}
}
//Even in the Debugger, these next if-elses have never worked
if(e.getKeyCode() == KeyEvent.VK_SPACE&& pane.returnImage() == field.getImage()) text += " ";
else if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE&& pane.returnImage() == field.getImage()){
int x = text.length();
text = text.substring(0,x-1); //Not sure if this works, haven't been able to test it yet
}
else if(e.getKeyCode() == KeyEvent.VK_ENTER&& pane.returnImage() == field.getImage()){
//do something with the text
text = "";
//exit the word creator
}
newWord.setText(text);
newWord.repaint(); //Apparently this isn't necessary...
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
);
}
private void mouseAction()
{
pane.addMouseListener(new MouseListener()
{
public void mouseClicked(MouseEvent arg0) {
//cover page
if(open.contains(arg0.getPoint())&& pane.returnImage() == cover.getImage()) displayPages();
else if(search.contains(arg0.getPoint())&& pane.returnImage() == cover.getImage()) searchWord();
else if(enter.contains(arg0.getPoint())&& pane.returnImage() == cover.getImage()) createWord();
//inner pages
else if(nextPage.contains(arg0.getPoint())&& pane.returnImage() == pages.getImage()) pageFlip("next");
else if(prevPage.contains(arg0.getPoint())&& pane.returnImage() == pages.getImage()) pageFlip("previous");
else if(cancel.contains(arg0.getPoint())&& pane.returnImage() == field.getImage()) coverPage();
frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
}
);
}
private void mouseMovement()
{
pane.addMouseMotionListener(new MouseMotionListener()
{
#Override
public void mouseMoved(MouseEvent e) {
if(search.contains(e.getPoint())&& pane.returnImage() == cover.getImage()){
frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else if(enter.contains(e.getPoint())&& pane.returnImage() == cover.getImage()){
frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else if(open.contains(e.getPoint())&& pane.returnImage() == cover.getImage()){
frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else if(nextPage.contains(e.getPoint())&& pane.returnImage() == pages.getImage()){
frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else if(prevPage.contains(e.getPoint())&& pane.returnImage() == pages.getImage()){
frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else if(cancel.contains(e.getPoint())&& pane.returnImage() == field.getImage()){
frame.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
else{
frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
#Override
public void mouseDragged(MouseEvent e) {
}
}
);
}
private void updateInteraction(){
mouseMovement();
mouseAction();
keyPress();
}
public class PaintPane extends JPanel {
private Image background;
private Graphics g2d;
public PaintPane(Image image) {
background = image;
}
#Override
public Dimension getPreferredSize() {
return background == null ? new Dimension(0, 0) : new Dimension(background.getWidth(this), background.getHeight(this));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
Insets insets = getInsets();
int width = getWidth() - 1 - (insets.left + insets.right);
int height = getHeight() - 1 - (insets.top + insets.bottom);
int x = (width - background.getWidth(this)) / 2;
int y = (height - background.getHeight(this)) / 2;
g.drawImage(background, x, y, this);
}
//g.fillRect(654, 798, 358, 77); //for testing rectangle positioning
}
public Image returnImage() {
return background;
}
}
I'm using BluJ to write this, and it has a built in Debugger. I just tried adding keyPress(); before the updateInteraction(); in createWord(), and ran the Debugger to go through each method step by step. Everything worked perfectly. Then I tried without the Debugger, and it wouldn't display any text while I was typing. So, I turned on the Debugger again. It didn't detect any keys being typed at all. I don't know why it only worked that once, but it was definitely working. This is my first time working with KeyListener, MouseListener, and MouseMotionListener. Is there a better way to get this program to run properly?
and it wouldn't display any text while I was typing
A component needs to have focus in order to respond to KeyEvents. A JPanel is not focusable by default.
I'm making my own text field
Why? What functionality is missing from JTextField?
I would just use JTextField and then add a DocumentListener to the document from the text field. Read the section from the Swing tutorial on How to Write a Document Listener for more information.
Your Component must have the focus for keyboard input on Key Event. However, to check it in action, first make your JPanle focus-able by panel.setFocusable(true). Then try with panel.requestFocusInWindow()
to get the focus to panel on application start-up.
However, in your code:
for(int i = 97; i <= 122; i++){
//Cycles through every lowercase letter
if(e.getKeyChar() == (char)(i)&& pane.returnImage() == field.getImage()){
text += (char)(i);
break;
}
}
Why do you have to use a loop here? Just simply putting:
if(evt.getKeyChar() >=97 && evt.getKeyChar() <=122 && pane.returnImage() == field.getImage())
text += evt.getKeyChar()
Should do the work.
If you are just doing a learning exercise, then it's OK to make your own implementation instead of using JTextField. You can make a JPanel receive key events by calling setFocusable(true) on it.
Even after that, you should be aware of something that will probably trip you up: keyTyped callbacks don't fill out the keyCode property of KeyEvents. This is because it's possible to type in characters that do not have a single associated key. For example, on Windows you can fire keyPressed once by typing ALT+0160. You hit 5 keys but entered one character (a space) and got a single keyPressed callback.
To summarize: keyPressed and keyReleased deliver keyCodes and might deliver keyChar. keyTyped never gets a keyCode, and always gets a keyChar.
public class PanelKeyListener extends JFrame {
private JPanel _contentPane;
StringBuilder _stringBuilder = new StringBuilder();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PanelKeyListener frame = new PanelKeyListener();
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PanelKeyListener() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_contentPane = new JPanel() {
protected void paintComponent(java.awt.Graphics g) {
g.drawString(_stringBuilder.toString(), 10, 20);
}
};
setContentPane(_contentPane);
_contentPane.setFocusable(true);
_contentPane.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped char[" + e.getKeyChar()
+ "] code[" + e.getKeyCode() + "]");
_stringBuilder.append(e.getKeyChar());
_contentPane.repaint();
}
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased char[" + e.getKeyChar()
+ "] code[" + e.getKeyCode() + "]");
}
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed char[" + e.getKeyChar()
+ "] code[" + e.getKeyCode() + "]");
}
});
}
}
You shouldn't reinvent the wheel if you can avoid it. Use/extend JTextField if it's practical to do so and meets your needs.
In java.awt.event.KeyListener, how do I check if the user enters "+" or "- "?
Here's a code example of how to do this:
TextField field = new TextField();
field.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
final char aChar = e.getKeyChar();
if (aChar == '+') {
System.out.println("+ was typed");
}
if (aChar == '-') {
System.out.println("- was typed");
}
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
});