K
k0m0r0w5k1
Hi. I got stucked on the following:
This is a panel that allows line drawing.
I want the line to be green if Ctrl is pressed down.
public MyPanel extends JPanel implements MouseListener, KeyListener {
boolean ctrl = false;
Point fromPoint, toPoint;
(...)
public void paint(Graphics g) {
if (ctrl) {
g.setColor(Color.green);
} else {
g.setColor(Color.red);
}
g.drawLine(fromPoint.x, fromPoint.y, toPoint.x, toPoint.y);
}
public void mouseMoved(MouseEvent e) {
toPoint = e.getPoint();
repaint();
}
public void keyPressed(KeyEvent e) {
ctrl = true;
repaint();
}
public void keyReleased(KeyEvent e) {
ctrl = false;
repaint();
}
}
And... it doesn't work
It looks like MouseEvent consumes KeyEvent, beacuse keyPressed() is NOT
called here
The listeners are set up correctly.
Changing this to:
public void mouseMoved(MouseEvent e) {
if (e.isControlDown) {
(...)
}
(...)
}
is not a solution, because it will only change the color after mouse
was moved.
And I want it to happen instantly on every key press/release.
What's wrong here?
How to make it work?
Thx a lot in advance,
k0m0r
This is a panel that allows line drawing.
I want the line to be green if Ctrl is pressed down.
public MyPanel extends JPanel implements MouseListener, KeyListener {
boolean ctrl = false;
Point fromPoint, toPoint;
(...)
public void paint(Graphics g) {
if (ctrl) {
g.setColor(Color.green);
} else {
g.setColor(Color.red);
}
g.drawLine(fromPoint.x, fromPoint.y, toPoint.x, toPoint.y);
}
public void mouseMoved(MouseEvent e) {
toPoint = e.getPoint();
repaint();
}
public void keyPressed(KeyEvent e) {
ctrl = true;
repaint();
}
public void keyReleased(KeyEvent e) {
ctrl = false;
repaint();
}
}
And... it doesn't work
It looks like MouseEvent consumes KeyEvent, beacuse keyPressed() is NOT
called here
The listeners are set up correctly.
Changing this to:
public void mouseMoved(MouseEvent e) {
if (e.isControlDown) {
(...)
}
(...)
}
is not a solution, because it will only change the color after mouse
was moved.
And I want it to happen instantly on every key press/release.
What's wrong here?
How to make it work?
Thx a lot in advance,
k0m0r