Witam, mam po raz kolejny problem ze swingiem. Mianowicie jeżeli oprogramuję sobie KeyListenera do spacji to mam pewien problem, mianowicie ostatni komponent używany przez użytkownika również wywołuje swoją akcje .... prosty przykład
package javaapplication4;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* @author w.maciejewski
*/
public class JavaApplication4 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Klasa();
}
}
class Klasa extends JFrame implements ActionListener,KeyListener{
private JButton button1,button2,button3;
private JLabel labelka;
Klasa(){
this.setSize(600, 200);
GridLayout gl = new GridLayout(0,4);
gl.setHgap(5);
this.setLayout(gl);
this.addKeyListener(this);
button1=new JButton("Zolty");
button1.addActionListener(this);
button1.addKeyListener(this);
button2=new JButton("zielony");
button2.addActionListener(this);
button3=new JButton("czerwony");
button3.addActionListener(this);
labelka=new JLabel("Kolorowy");
labelka.setForeground(Color.black);
labelka.addKeyListener(this);
this.add(button1);
this.add(button2);
this.add(button3);
this.add(labelka);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent ae) {
Object source=ae.getSource();
if(source==button1){
labelka.setForeground(Color.yellow);
}else
if(source==button2) {
labelka.setForeground(Color.green);
}else
if(source==button3){
labelka.setForeground(Color.red);
}
}
@Override
public void keyTyped(KeyEvent ke) {
if(ke.getKeyCode()==KeyEvent.VK_SPACE){
labelka.setForeground(Color.MAGENTA);
}
}
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
}
teraz po naciśnięciu button1 a później spacji wykona się to co miało się wykonać pod spacją jak również pod button1... nie pożądany to efekt specjalnie.
Piszę w NetBeansie może to jakaś opcja w nim która tak zapisuje swinga?
z góry dzięki za pomoc