I'm attempting to use KeyListener to interact with the arrow keys, when I run it, it doesn't give me an error, but the rectangle I am trying to move left or right does not move. Am I missing something? I'm trying to simulate the game for bricks, so My only issue right now is getting the panel to move across the screen
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
import org.w3c.dom.css.Rect;
public class tools extends JPanel implements KeyListener, ActionListener {
Timer t = new Timer(5,this);
double x = 350, y=920,velx=0,vely=0;
public tools() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2 = (Graphics2D)g;
g.setColor(Color.BLUE);
g2.fill(new Ellipse2D.Double(x, y, 300, 10));
//ball
/*
g.setColor(Color.WHITE);
g.fillOval(350, 700, 20, 20);
*/
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
x+= velx;
y+= vely;
}
public void left() {
velx = -1.5;
vely=0;
}
public void right() {
velx=1.5;
vely=0;
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_RIGHT)
{
right();
}
else if(keyCode == KeyEvent.VK_LEFT)
{
left();
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
You need to call repaint() to redraw the canvas. Have a look at the example below.
public class Bricks extends JPanel implements KeyListener, ActionListener {
Timer t = new Timer(5, this);
double x = 150, y = 320, velx = 0, vely = 0;
public Bricks() {
t.start();
setFocusable(true);
requestFocus();
addKeyListener(this);
//setFocusTraversalKeysEnabled(false);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.BLUE);
g2.fill(new Ellipse2D.Double(x, y, 300, 10));
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
x += velx;
y += vely;
}
public void left() {
velx = -1.5;
vely = 0;
}
public void right() {
velx = 1.5;
vely = 0;
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_RIGHT) {
System.out.println("RIGHT");
right();
repaint();
} else if (keyCode == KeyEvent.VK_LEFT) {
System.out.println("LEFT");
left();
repaint();
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Bricks bricks = new Bricks();
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(1078, 800);
frame.getContentPane().add(bricks, BorderLayout.CENTER);
}
});
}
}
Related
Beginner here,
I am trying to make a simple application using java where a rectangle is created and can be moved using the keys "w,a,s,d". And also to increase or decrease size of the rectangle using the scroll button in a mouse. Now the object can be moved using the keys but I don't know how to do the scroll function. Somebody Help?
import java.awt.*;
import java.awt.event.*;
public class Animation extends Frame implements KeyListener, MouseWheelListener {
int x, y, a, b;
char choice1;
Animation() {
setSize(500, 500);
setVisible(true);
x = 50;
y = 50;
a = 20;
b = 50;
addKeyListener(this);
addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
});
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
choice1 = e.getKeyChar();
if (choice1 == 'w') {
y = y - 1;
}
if (choice1 == 's') {
y = y + 1;
}
if (choice1 == 'a') {
x = x - 1;
}
if (choice1 == 'd') {
x = x + 1;
}
repaint();
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
}
public void paint(Graphics g) {
g.drawRect(x, y, a, b);
g.setColor(Color.red);
g.fillRect(x, y, 20, 50);
}
public static void main(String[] args) {
Animation animation = new Animation();
}
}
To be specific I want to know what should be written inside the mouseWheelMoved() method and how using that I can make the rectangle bigger or smaller.
Thanks
If somebody faces the same problem.
Use the getPreciseWheelRotation() method to get values. If the value is greater than 0, the scroller is being scrolled towards you and vice versa.
I'm entering the code also here,
double p = e.getPreciseWheelRotation();
if(p>0){
a=a+5;
b=b+5;
} else{
a=a-5;
b=b-5;
}
repaint();
This is my code, I want to add functionality to the Rect that I made, like when you click on it, a window pops up
public class codetwo extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.LIGHT_GRAY);
g.setColor(Color.RED);
g.fillRect(110,110, 120, 120);
}
public static void main(String args[]) {
codetwo cd = new codetwo();
JFrame frame = new JFrame("Title");
frame.add(cd);
frame.setSize(440,350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You need to use Mouselistener for this.
public class codetwo extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.LIGHT_GRAY);
g.setColor(Color.RED);
g.fillRect(110,110, 120, 120);
}
public static void main(String args[]) {
codetwo cd = new codetwo();
cd.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if (e.getX() >= 110 && e.getX() <= 230 && e.getY() >= 110 && e.getY() <= 230) {
JOptionPane.showMessageDialog(cd, "Some one clicked here ?", "Listening", JOptionPane.INFORMATION_MESSAGE);
}
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(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
}
JFrame frame = new JFrame("Title");
frame.add(cd);
frame.setSize(440,350);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I'm having some issues with my code.
I want to fix the background image to stay there fixed, meanwhile other components can move.
It's a simple a game where a circle avoid the squares but the istruction about the game will be added further.
Here's my code
import java.applet.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Line2D;
import java.net.URL;
import javax.swing.*;
public class Main extends Applet implements Runnable,KeyListener{
Thread r;
Image bg = null;
int a,b;
int x = 600;
int y = 400;
public void init(){
setSize(600,600);
try
{
MediaTracker tr = new MediaTracker (this);
bg = getImage
(new URL("file:D:/workspace/Game/bin/image.jpg")); //set image
tr.addImage(bg, 0);
} catch (Exception e) { System.out.println(e.toString());
}
}
public void start(){
if(r == null){
r = new Thread(this);
r.start();
}
}
public void paint(Graphics g){
g.drawImage(bg,0,0,this);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(20));
g2.draw(new Line2D.Float(0, 500, 600, 500));
g.fillRect(x, y, 20, 20);
}
public void pp(Graphics g){
}
public void run() {
Thread Th = Thread.currentThread();
while(r == Th) {
if(a < 600) {
a = a+10;
x = x-10;
repaint();
}else{
repaint();
a = 30;
x = 600;
}
try {
Thread.sleep(100);
} catch(InterruptedException e) { }
}
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
if you run the code, you'll see that the line and the background will be loaded a lot of time...
I'm a beginner in learning this.Doing a test by drawing a triangle and now I want to move it.it's not working so I want to ask what's my mistake.Sorry it's long.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
public class Test extends JFrame {
private Triangle triangle;
private final int step = 10;
private Triangle keyboardPanel = new Triangle();
public static void main(String[] args)
{
Test t = new Test();
}
public Test()
{
setTitle("TRY TRY TRY");
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
JPanel tripanel = new JPanel();
add(tripanel);
triangle = new Triangle();
tripanel.addKeyListener(null);
tripanel.addMouseListener(null);
tripanel.addMouseMotionListener(null);
setVisible(true);
}
static class move extends JPanel implements KeyListener,MouseListener, MouseMotionListener{
private int x = 210;
private int y = 210;
private Color color = Color.BLACK;
move()
{
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void keyPressed(KeyEvent ke) {
int KeyCode = ke.getKeyCode();
System.out.println("key code is" +KeyCode);
/*switch (KeyCode)
{
case KeyEvent.VK_UP:
triangle.moveTriangle(-10, 0);
break;
case KeyEvent.VK_DOWN:
triangle.moveTriangle(10, 0);
break;
case KeyEvent.VK_LEFT:
triangle.moveTriangle(0, -10);
break;
case KeyEvent.VK_RIGHT:
triangle.moveTriangle(0, 10);
break;
}
repaint();*/
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#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 e) {
System.out.println("hello");
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
System.out.println("hello123");
if(e.isControlDown())
color = Color.RED;
else
color = Color.BLACK;
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println(e.getPoint());
}
}
public void paint(Graphics g)
{
super.paint(g);
triangle.drawTriangle(g);
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
triangle.drawTriangle(g);
}
}
import java.awt.Graphics;
import javax.swing.JPanel;
public class Triangle {
private Point p1;
private Point p2;
private Point p3;
int numX;
int numY;
public Triangle()
{
p1 = new Point(200,200);
p2 = new Point(170,230);
p3 = new Point(230,230);
}
public void moveTriangle(int dx, int dy)
{
p1.move(dx, dy);
p2.move(dx, dy);
p3.move(dx, dy);
}
public void drawTriangle(Graphics g)
{
g.drawLine(p1.getX(), p1.getY(),p2.getX(),p2.getY());
g.drawLine(p2.getX(),p2.getY(),p3.getX(),p3.getY());
g.drawLine(p3.getX(), p3.getY(),p1.getX(),p1.getY());
}
}
public class Point {
private int x;
private int y;
public Point(int X, int Y)
{
x = X;
y = Y;
}
public void setX(int X)
{
x = X;
}
public void setY(int Y)
{
x = Y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void move(int dx, int dy)
{
x +=dx;
y +=dy;
}
public String toString()
{
return("X = "+x+" Y= "+y);
}
}
there are lot of problems in your code .when you coding always test current code before go further.
you create a panel and add to the jframe .
JPanel tripanel = new JPanel();
add(tripanel);
but your graphical mechanism has written in move panel so you need to make a move panel instead of jpanel.
keylistners has added to panel but keylisners not get triggered because keylistners work when component is focused . it works for component like jtextfiled . but not for panels .you have to use keybinding .i have added keybind for rightarrow key ..you have to add it to other keys up ,down etc..
also move your paint method from jframe to move jpanel .
example code (run this code and press right arrow ->)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Test extends JFrame {
private Triangle triangle;
private final int step = 10;
private Triangle keyboardPanel = new Triangle();
public static void main(String[] args) {
Test t = new Test();
}
public Test() {
setTitle("TRY TRY TRY");
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
JPanel tripanel = new move();
add(tripanel);
triangle = new Triangle();
setVisible(true);
}
class move extends JPanel implements MouseListener, MouseMotionListener {
private int x = 210;
private int y = 210;
private Color color = Color.BLACK;
move() {
addMouseListener(move.this);
addMouseMotionListener(move.this);
this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "moveright");
this.getActionMap().put("moveright", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
triangle.moveTriangle(10, 0);
repaint();
}
});
}
#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 e) {
System.out.println("hello");
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
System.out.println("hello123");
if (e.isControlDown()) {
color = Color.RED;
} else {
color = Color.BLACK;
}
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
//System.out.println(e.getPoint());
}
#Override
public void paint(Graphics g) {
super.paint(g);
triangle.drawTriangle(g);
}
}
class Triangle {
private Point p1;
private Point p2;
private Point p3;
int numX;
int numY;
public Triangle() {
p1 = new Point(200, 200);
p2 = new Point(170, 230);
p3 = new Point(230, 230);
}
public void moveTriangle(int dx, int dy) {
p1.move(dx, dy);
p2.move(dx, dy);
p3.move(dx, dy);
}
public void drawTriangle(Graphics g) {
g.drawLine(p1.getX(), p1.getY(), p2.getX(), p2.getY());
g.drawLine(p2.getX(), p2.getY(), p3.getX(), p3.getY());
g.drawLine(p3.getX(), p3.getY(), p1.getX(), p1.getY());
}
}
class Point {
private int x;
private int y;
public Point(int X, int Y) {
x = X;
y = Y;
}
public void setX(int X) {
x = X;
}
public void setY(int Y) {
x = Y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void move(int dx, int dy) {
x += dx;
y += dy;
}
public String toString() {
return ("X = " + x + " Y= " + y);
}
}
}
output >>
package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class test_bmp extends JPanel implements MouseListener,MouseMotionListener,ActionListener
{
static BufferedImage image;
Color color;
Point start=new Point();
Point end =new Point();
JButton elipse=new JButton("Elipse");
JButton rectangle=new JButton("Rectangle");
JButton line=new JButton("Line");
String selected;
public test_bmp()
{
color = Color.black;
setBorder(BorderFactory.createLineBorder(Color.black));
addMouseListener(this);
addMouseMotionListener(this);
}
public void paintComponent(Graphics g)
{
//super.paintComponent(g);
g.drawImage(image, 0, 0, this);
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.black);
if(selected=="elipse")
{
g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
System.out.println("Start : "+start.x+","+start.y);
System.out.println("End : "+end.x+","+end.y);
}
if(selected=="line")
g2.drawLine(start.x,start.y,end.x,end.y);
}
//Draw on Buffered image
public void draw()
{
Graphics2D g2 = image.createGraphics();
g2.setPaint(color);
System.out.println("draw");
if(selected=="line")
g2.drawLine(start.x, start.y, end.x, end.y);
if(selected=="elipse")
{
g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y));
System.out.println("Start : "+start.x+","+start.y);
System.out.println("End : "+end.x+","+end.y);
}
repaint();
g2.dispose();
}
public JPanel addButtons()
{
JPanel buttonpanel=new JPanel();
buttonpanel.setBackground(color.lightGray);
buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS));
elipse.addActionListener(this);
rectangle.addActionListener(this);
line.addActionListener(this);
buttonpanel.add(elipse);
buttonpanel.add(Box.createRigidArea(new Dimension(15,15)));
buttonpanel.add(rectangle);
buttonpanel.add(Box.createRigidArea(new Dimension(15,15)));
buttonpanel.add(line);
return buttonpanel;
}
public static void main(String args[])
{
test_bmp application=new test_bmp();
//Main window
JFrame frame=new JFrame("Whiteboard");
frame.setLayout(new BorderLayout());
frame.add(application.addButtons(),BorderLayout.WEST);
frame.add(application);
//size of the window
frame.setSize(600,400);
frame.setLocation(0,0);
frame.setVisible(true);
int w = frame.getWidth();
int h = frame.getHeight();
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setPaint(Color.white);
g2.fillRect(0,0,w,h);
g2.dispose();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#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 event)
{
start = event.getPoint();
}
#Override
public void mouseReleased(MouseEvent event)
{
end = event.getPoint();
draw();
}
#Override
public void mouseDragged(MouseEvent e)
{
end=e.getPoint();
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==elipse)
selected="elipse";
if(e.getSource()==line)
selected="line";
draw();
}
}
I need to create a paint application. When I draw ellipse by dragging mouse from left to right it displays nothing. Why? Should I use any other function here?
Your program does draw an ellipse when you drag the mouse down and to the right. It's dragging up and/or left that does not work, because Graphics.drawOval does not work with a negative width or height.
Try adding a method like this:
private Shape createEllipse() {
Ellipse2D e = new Ellipse2D.Double();
e.setFrameFromDiagonal(start, end);
return e;
}
Then call it from draw and paintComponent like this:
if(selected=="elipse") {
g2.draw(createEllipse());
}
Also you probably do not need the call to draw() at the end of actionPerformed. If you switch between line and ellipse mode it will draw an ellipse with the same coordinates as the most recent line or vice-versa.
And one coding style issue: Using string literals for selected is confusing (although it does work.) I would define an enum instead.