How to use KeyEvent - java

I'm writing small graphics editor and I want catch event when I press Ctrl+A
I use such code (this is test version):
#Override
public void keyPressed(KeyEvent e) {
System.out.println("Press");
switch (e.getKeyCode()){
case KeyEvent.VK_A :
System.out.println("A");
break;
}
}
but I don't know how to catch Ctrl+a
I tryed something like this
case KeyEvent.VK_CONTROL+KeyEvent.VK_A :
System.out.println("A+CTRL");
break;
but this code KeyEvent.VK_CONTROL+KeyEvent.VK_A returns int and maybe another key combination returns the same number
So can someone can help me

You can use isControlDown() method:
switch (e.getKeyCode())
{
case KeyEvent.VK_A :
if(e.isControlDown())
System.out.println("A and Ctrl are pressed.");
else
System.out.println("Only A is pressed");
break;
...
}

Try this.....
f.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if ((e.getKeyCode() == KeyEvent.VK_A) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
System.out.println("woot!");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});

Try isControlDown method on KeyEvent: http://docs.oracle.com/javase/6/docs/api/java/awt/event/InputEvent.html#isControlDown%28%29

Related

Replace many "else if" with something else

I am using an ActionListener and have lots of else if statements in order to know which button is pressed and run some code depending on the button.
Is there a way to make the code nicer? I have nearly 10 else if statements following each other, is there something else I could use instead?
Sample of code:
class BtnListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menu.getOpen()) {
getFile();
} else if (e.getSource() == btnPlay) {
} else if (e.getSource() == btnQuit)) {
}
}
Thanks.
You can fill Map<Object, Consumer<ActionEvent>> before using of listener, for example in constructor, where key is source and value is a consumer for action event. In action perform just get consumer by key and invoke it.
class BtnListener implements ActionListener {
Map<Object, Consumer<ActionEvent>> eventsMap = new HashMap<>();
public BtnListener() {
eventsMap.put(menu.getOpen(), actionEvent -> this.getFile());
eventsMap.put(btnPlay, actionEvent -> { //do something
});
eventsMap.put(btnQuit, actionEvent -> { //do something else
});
}
#Override
public void actionPerformed(ActionEvent e) {
Optional.of(e)
.map(ActionEvent::getSource)
.map(eventsMap::get)
.ifPresent(
actionEventConsumer -> actionEventConsumer.accept(e)
);
}
}
You may use the action command of the button, and a switch-case block :
public void actionPerformed(ActionEvent e){
switch(e.getActionCommand()) {
case "Open":
open();
break;
case "Delete":
delete();
break;
default :
break;
}
}
Of course you will have to set the action command of each button first, like :
openButton.setActionCommand("Open");
Note that switch-case with String objects only exists since JDK 7 : Strings in switch Statements
You can switch statement instead lot of else if ladder.
class BtnListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == menu.getOpen()) {
getFile();
}
switch( e.getSource() ){
case btnPlay:
break;
case btnQuit:
break;
default:
}
}
}
the best way to avoid all the "overheads" is to Lambda-Expressioned the buttons. Example:
JButton b1 = new JButton("Play");
b1.addActionListener(e -> play());
...
JButton bn = new JButton("Stop");
bn.addActionListener(e -> stop());
...
private void play() {
....// playing codes
}
...
private void stop() {
...// stopping codes
}
...

Clear textField immediately after entering char in Java Swing

After entering into textField one of this letters: "e,E,f,F,g,G", the comboBox in my app is changing. I want to clear my textField immediately after entering one of this letters but i can't do this. I use :
tekstField.setText("");
but it doesn't work. Probably it because that i can't eat listener in Swing.
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
updateLog(e);
}
public void removeUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
updateLog(e);
}
public void updateLog(DocumentEvent e) {
Document doc = (Document) e.getDocument();
int docLength = doc.getLength();
String key;
try {
key = e.getDocument().getText(0, docLength);
if (docLength == 1 && !key.matches("^[0-9]$")) {
char labSymbol = key.charAt(0);
switch (labSymbol) {
case 'E' :
case 'e' :
labTypeComboBox.setSelectedIndex(0);
break;
case 'F' :
case 'f' :
labTypeComboBox.setSelectedIndex(1);
break;
case 'G' :
case 'g' :
labTypeComboBox.setSelectedIndex(2);
break;
default :
break;
}
tekstField.setText("");
}
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Anybody know how to solve this problem?

Java Event listeners (mouse and keyboard)

So everything in my program works, except for the mouse and the keyboard listeners.
I've got a couple actionListeners working on Jbuttons that do exactly what I'm trying to do here, but the assignment says it has to work with all three.
So I would like to know why it compiles, but doesn't work. Am I doing something wrong?
panel.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
shape.addSides();
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
shape.subSides();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
);
panel.addMouseListener(new MouseListener(){
#Override
public void mouseEntered(MouseEvent e){
if(e.getButton() == MouseEvent.BUTTON1){
shape.addSides();
}
if(e.getButton() == MouseEvent.BUTTON3){
shape.subSides();
}
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
);
Regarding KeyListener: it won't work unless the listened-to component is focusable and has focus. So you will want to call setFocusable(true) and requestFocusInWindow() on your JPanel. As for the MouseListener -- something else may be taking the mouse event and preventing it from reaching your JPanel. To debug this you need to post a minimal, compilable, runnable example program.
Also regarding your MouseListener, you're checking getButton() in a mouseEntered event which makes no sense. The buttons are not involved in this type of event. Are you instead meaning to check mouseDragged(...) of a MouseMotionListener?

addKeyListener to Jpanel

I want to addKeyListener to a JPanel but when I press two keys at the same time, just one of them executes. What is the solution to this problem - press two keys at the same time?
I have a class that extends JPanel
this.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
upPlayer2();
} if (e.getKeyCode() == KeyEvent.VK_A ){
leftPlayer2();
}
}
});
Thanks.
Don't use a KeyListener. Swing was designed to be used with Key Bindings.
See Motion Using the Keyboard for more information and solutions.

How can i prevent CTRL+C on a JTextField in java?

How can i prevent a user from copying the contents of a JTextField?
i have the following but i cannot figure a way to get multiple keys at the same time?
myTextField.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!Character.isDigit(c)) {
e.consume();
}
}
});
For this, you will have to modify your KeyAdapter so that it can register when a key was pressed and when it was released, so that we may know when both keys were pressed simultaneously, the following code should do the trick:
textfield.addKeyListener(new KeyAdapter() {
boolean ctrlPressed = false;
boolean cPressed = false;
#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_C:
cPressed=true;
break;
case KeyEvent.VK_CONTROL:
ctrlPressed=true;
break;
}
if(ctrlPressed && cPressed) {
System.out.println("Blocked CTRl+C");
e.consume();// Stop the event from propagating.
}
}
#Override
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_C:
cPressed=false;
break;
case KeyEvent.VK_CONTROL:
ctrlPressed=false;
break;
}
if(ctrlPressed && cPressed) {
System.out.println("Blocked CTRl+C");
e.consume();// Stop the event from propagating.
}
}
});
i was just adding this to one of my JTextFields.

Categories