KeyAdapter listener, nothing happening - java

I am currently writing a small program where I'm supposed to use basic transformations. Right now, I'm working on being able to move the polygon by using the arrow keys. Right now I can move it to the right by pressing the mouse, but I'd rather be able to use the right arrow key. However, I haven't been able to no matter which method I tried.
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
class PolygonPanel extends JPanel implements MouseListener{
Polygon p;
public PolygonPanel(){
p = new Polygon();
p.addPoint(10, 10);
p.addPoint(100,50);
p.addPoint(50,100);
addMouseListener(this);
addKeyListener(new MKeyListener());
}
class MKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode==e.VK_RIGHT){
System.out.println("FFFFUUUUU");
}
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.white);
g.fillPolygon(p);
}
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("hei");
for (int i = 0; i < p.npoints; i++) {
p.xpoints[i] = p.xpoints[i]+10;
repaint();
}
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class PolygonFrame extends JFrame{
public PolygonFrame(){
setTitle("Polygoner");
setSize(700, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.add(new PolygonPanel());
}
}
public class Polygonfun {
public static void main(String[] args) {
JFrame frame = new PolygonFrame();
frame.setVisible(true);
}
}
Nothing happens when I press the right arrow key. I also tried implementing it like this:
class PolygonPanel extends JPanel implements MouseListener,KeyAdapter
And then adding the unimplemented methods, but that didn't work either. I know i've probably overlooked something, but I cant seem to figure it out. Any advice?
Thanks

set this.setFocusable(true); for your panel.
Should be:
public PolygonPanel(){
p = new Polygon();
p.addPoint(10, 10);
p.addPoint(100,50);
p.addPoint(50,100);
addMouseListener(this);
this.setFocusable(true);
this.addKeyListener(new MKeyListener());
}

Related

Regarding adding of Rectangle when mouse is clicked on JFrame

I am a beginner. I am trying to add filled rectangle or any other graphic on JFrame using multiple inner classes. I am getting debugging errors. What are the problems here?. If this is a wrong way. Please tell me how to do the same using JFrame and JPanel only.
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class RainBow{
JFrame frame;
public static void main(String[] args){
RainBow bow = new RainBow();
bow.go();
}
public class Paint extends JPanel{
public void paintComponent(Graphics g){
g.setColor(Color.red);
g.fillRect(100, 100, 100, 100);
}
}
public void go(){
frame.addMouseListener(new ListenMouse());
frame.setSize(400, 400);
frame.setVisible(true);
}
public class ListenMouse implements MouseListener{
public void mosueClicked(MouseEvent a){
Paint p = new Paint();
frame.getContentPane().add(p);
frame.setVisible(true);
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
}
The code posted has multiple problems. See this working example with explanations in comments.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class RainBow {
JFrame frame;
boolean paintRectangle = false;
public static void main(String[] args) {
RainBow bow = new RainBow();
bow.go();
}
public class Paint extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g); // should always be done
if (paintRectangle) {
g.setColor(Color.red);
g.fillRect(100, 100, 100, 100);
}
}
}
public void go() {
frame = new JFrame(); // otherwise NPE
Paint paint = new Paint();
paint.addMouseListener(new ListenMouse()); // add listner to paint
frame.add(paint); // add paint at start-up
frame.setSize(400, 400);
frame.setVisible(true);
// ensures JVM shuts down when frame is closed.
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public class ListenMouse extends MouseAdapter {
// this method is incorrectly spelled!
public void mosueClicked(MouseEvent a) {
}
#Override
public void mouseClicked(MouseEvent arg0) {
/* requires special handling to add components on the fly */
//Paint p = new Paint();
paintRectangle = true;
frame.repaint(); // forces the Paint to be painted as well.
}
}
}

Java repaint method do not working ,why?

Well my English is not so good but i will try to explain.
I was make two class,First Class and Second Class(Second was named "Grafika").
I want that my rectangle move to position where i was clicked , but obviously he dont move and i cant understand why, please help .
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class Grafika extends JPanel implements MouseListener{
static int x=0,y=0;
#Override
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(x, y, 20, 30);
}
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub``
x=arg0.getX();
y=arg0.getY();
this.repaint(x, y, 20, 30);
}
i will show you a full code, it was small .This was second class.And my(i think) only problem is repaint() method . Why i dont know :D .
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class Grafika extends JPanel implements MouseListener{
static int x=0,y=0;
#Override
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(x, y, 20, 30);
}
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
x=arg0.getX();
y=arg0.getY();
this.repaint(x, y, 20, 30);
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
Now i will show you first class from where i was calling second class.
import java.awt.*;
import javax.swing.*;
public class Glavna extends Grafika {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Grafika g=new Grafika();
JFrame wi=new JFrame("Grafika");
wi.setBounds(50, 50, 500, 600);
wi.add(g);
wi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wi.setVisible(true);
}
}
You've several problems in that code:
You're sort of creating a MouseListener (you're still missing several of the interface's methods), but I don't see anywhere that you've added it to your GUI. You must somewhere have addMouseListener(this); in your code for the listener to work.
Repaint by itself doesn't move the rectangle. Changing the X and Y does, but again, not without adding the MouseListener first.
You probably want to call repaint(); without parameters to paint the whole component. Otherwise the old rectangle might not get erased.
Your paintComponent method should call the super.paintComponent(g); as the first method call of your override method. Without this you won't erase the old rectangle, and you break the painting chain which could have painting side effects in child components.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class Grafika extends JPanel {
private static final int RECT_W = 20;
private static final int RECT_H = 30;
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color MY_COLOR = Color.RED;
private int myX = 0;
private int myY = 0;
public Grafika() {
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse); // add MouseListener
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // **MUST** call this
g.setColor(MY_COLOR);
g.fillRect(myX, myY, RECT_W, RECT_H);
}
private class MyMouse extends MouseAdapter {
public void mousePressed(MouseEvent e) {
myX = e.getX();
myY = e.getY();
repaint(); // repaint the whole JPanel
}
}
#Override // to make the GUI larger
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Grafika mainPanel = new Grafika();
JFrame frame = new JFrame("Grafika");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
If you want to get fancier and start dragging the square around:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Grafika extends JPanel {
private static final int RECT_W = 20;
private static final int RECT_H = RECT_W;
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color MY_COLOR = Color.RED;
private int myX = 0;
private int myY = 0;
public Grafika() {
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(MY_COLOR);
g.fillRect(myX, myY, RECT_W, RECT_H);
}
private class MyMouse extends MouseAdapter {
public void mousePressed(MouseEvent e) {
moveRect(e);
}
#Override
public void mouseDragged(MouseEvent e) {
moveRect(e);
}
#Override
public void mouseReleased(MouseEvent e) {
moveRect(e);
}
private void moveRect(MouseEvent e) {
myX = e.getX() - RECT_W / 2;
myY = e.getY() - RECT_H / 2;
repaint();
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Grafika mainPanel = new Grafika();
JFrame frame = new JFrame("Grafika");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
you have to add mouse listener to component porobably
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class Grafika extends JPanel implements MouseListener{
static int x=0,y=0;
public Grafika(){
super();
addMouseListener(this); // add to constructor
}
#Override
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.fillRect(x, y, 20, 30);
}
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub``
x=arg0.getX();
y=arg0.getY();
this.repaint(x, y, 20, 30);
}

MouseExited not fired when mouse exits button

I have a JPanel in a GridLayout that I add buttons to. I want to implement some kind of effect on buttons when the mouse is entered and when the mouse exits the button . The mouseEntered event is correctly fired when the mouse hovers over the button , however , when the mouse leaves the button the mouseExited event is not fired. How can I fix this issue?
Custom JButton
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class CustomButton extends JButton implements MouseListener{
Dimension scaled;
public CustomButton(String text){
super(text);
setContentAreaFilled(false);
setBorderPainted(false);
addMouseListener(this);
}
#Override
public void invalidate() {
super.invalidate();
scaled = getSize();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 20, 20);
g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 20, 20);
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("entered the view");
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("exited the view");
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
Don't use a MouseListener, rather add a ChangeListener to the JButton's model and react to changes in its rollover state,... isRollover()
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestRollover extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
JButton button = new JButton("Button");
public TestRollover() {
add(button);
button.getModel().addChangeListener(new ChangeListener() {
private boolean rollover = false;
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isRollover() != rollover) {
System.out.println("Rollover: " + model.isRollover());
rollover = model.isRollover();
}
}
});
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
System.out.println("mouse entered");
}
#Override
public void mouseExited(MouseEvent e) {
System.out.println("mouse exited");
}
});
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
TestRollover mainPanel = new TestRollover();
JFrame frame = new JFrame("TestRollover");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Mouse doesn't maintain it's position when frame is moved across the screen

Here is the code.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class Paint extends JPanel implements MouseMotionListener, MouseListener {
public Paint() {
setBackground(Color.RED);
addMouseMotionListener(this);
addMouseListener(this);
}
private boolean clicked = false;
public void paintComponent (Graphics g) {
super.paintComponent(g);
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int) b.getX() - 3;
int y = (int) b.getY() - 23;
if (clicked) {
g.drawLine(x, y-5000, x,y+5000);
g.drawLine(x+5000,y,x-5000,y);
g.setColor(Color.white);
}
g.drawLine(x, y-5000, x,y+5000);
g.drawLine(x+5000,y,x-5000,y);
g.setColor(Color.black);
// . . .
}
#Override
public void mouseDragged(MouseEvent e) {
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
clicked = true;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
clicked = false;
repaint();
}
}
public class Frame extends JFrame {
public Frame() {
this.setSize(500,500);
this.setTitle("Test painting");
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
Paint panel = new Paint();
this.add(panel);
this.setVisible(true);
}
public static void main (String[] args) {
new Frame();
}
}
When I run the program, it looks like it works fine when the application is in the default position, but once I move the applet to where I like on the screen, the lines don't maintain the current mouse position on screen.
Can someone show me where I've gone wrong or how to fix this?
Painting is done from the context of the component. The Graphics context for any given component is translated so that the top, left corner is 0x0.
MouseInfo.getPointerInfo().getLocation() is returning the location of the mouse on the screen, not the position relative to the component.
While there is a way to fix it, a better solution would be to simply use a MouseMotionListener instead. The MouseEvent sent to this method has already been translated to the component coordinate space...
public void mouseMoved(MouseEvent me) {
myPoint = me.getPoint();
}
Then in you paintComponent method, simple refer to myPoint instead of trying to use MouseInfo
I think that you will be better off to change your class's state in the MouseAdapter, call repaint() and then have your paintComponent(...) method use this state to help it draw. This seems cleaner and safer to me than using MouseInfo in paintComponent(...).
Other than that, if you need more specific help, consider
telling us more about what it is exactly you're trying to do and how your program isn't working.
creating and posting an sscce, a small compilable and runnable program that demonstrates your problem for us.

Can't use repaint()?

//I want to paint a ball in a animation
//I can't seem to find a way to repaint the ball
// Any help or tips on how to use repaint here?
//
// Ball class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Ball implements Runnable {
protected Point loc;
protected int dx;
protected int dy;
protected Color color;
protected boolean flag;
private Graphics gra;
public Ball(Point loc,int dx,int dy,Graphics st)
{
this.loc=loc;
this.dx=1;
this.dy=1;
color=Color.blue;
this.gra=st;
flag=false;
}
public void paint(Graphics g)
{
g.fillOval((int)this.loc.getX(),(int)this.loc.getY(),20,20);
}
public void move()
{
this.loc.translate(this.dx,this.dy);
}
#Override
public void run() {
while(flag==false)
{
this.paint(gra);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
move();
}
}
}
//Myframe class
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class myframe extends JFrame {
private Ball b;
public myframe()
{
super("My Frame");
setSize(800,600);
}
public void run()
{
b=new Ball(new Point(100,100),10,10,getGraphics());
b.run();
}
}
//Main class
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame
{
/**
* #param args
*/
public static void main(String[] args) {
myframe jwin = new myframe();
jwin.setSize(600, 600);
jwin.setVisible(true);
jwin.run();
}
}
You should try using repaint() instead of this.paint(gra), and put it inside the thread, you also need to add the component to you graphic interface
You need to override the paintComponent() method of the JComponent class. Have it do your painting and add that component to your GUI.

Categories

Resources