I need to have a program that when I click on the card it will flip to the back side of the card and when I click on it again it will show the face again. Please Help, I have it to when I click the card it will show the back of it but how do I get it to show the front again?
import java.awt.Button;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JApplet;
public class DealCard extends JApplet implements ActionListener, MouseListener {
Random gen = new Random();
Button dealButton = new Button("Deal");
int card1 = 0;
Image[] card = new Image[53];
Image[] back= new Image[1];
int number = 0;
public void init() {
setSize(200, 200);
setLayout(null);
for (int i = 0; i < 53; i++) {
card[i] = getImage(getCodeBase(), "card" + (i + 1) + ".gif");
}
dealButton.setBounds(100, 200, 80, 30);
add(dealButton);
dealButton.addActionListener(this);
dealButton.setEnabled(true);
addMouseListener(this);
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(card[card1], 100, 100, 82, 82, this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == dealButton) {
card1 = gen.nextInt(52);
}
repaint();
}
public void mouseClicked(MouseEvent e){
int x = e.getX();
int y = e.getY();
if(x > 100 && x < (100+82) && y > 100 && y < (100+82)){
card1 = 52;
System.out.println(card1);
repaint();
e.consume();
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
You need a boolean value to state whether the card is facing up or not.
Then add a condition to your draw statement that checks if the card is facing up or not.
Hope that helps.
You should also add a back card image, which does not need to be an array as it is just one.
Image back= new Image();
Or alternatively make card[0] your back card Image.
Related
I am new to Java and I am trying to make a simple game for fun.
I first tried to put repaint into paintComponent(), it worked until I tried to add some background.
Does anyone know how to let my player move with or without 'repaint'?
Screen class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Frame extends JFrame implements KeyListener
{
Map map;
public static void main(String[] args)
{
Frame frame = new Frame();
frame.addKeyListener(new Frame());
frame.setVisible(true);
}
public Frame()
{
setInit();
}
private void setInit()
{
map = new Map();
add(map);
setSize(800, 800);//frame size 300 width and 300 height
setTitle("Eerste Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setLayout(new GridLayout(1,1,0,0));
setFocusable(true);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
map.movePlayer(keyCode);
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
Map class
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
class Map extends JPanel
{
Player player;
BufferedImage map;
public Map() {
player = new Player();
try{map = ImageIO.read(new File("img/map.png"));}catch (Exception e){};
}
public void movePlayer(int keyPressed)
{
player.move(keyPressed);
revalidate();
repaint();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(player.img,player.getX(),player.getY(), null);
}
}
Player class
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
class Player
{
BufferedImage img = null;
private int x = 100;
private int y = 100;
public Player()
{
try{img = ImageIO.read(new File("img/bob.png"));}catch (Exception e){}
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void move(int keyPressed)
{
if(keyPressed == KeyEvent.VK_W) {
// handle up
y = y - 5;
}
if (keyPressed == KeyEvent.VK_A) {
// handle links
x = x - 5;
}
if (keyPressed == KeyEvent.VK_S) {
// handle onder
y = y + 5;
}
if (keyPressed == KeyEvent.VK_D ) {
// handle right
x = x + 5;
}
}
}
You're unnecessarily creating a new Frame object as the KeyListener, and so the KeyListener events all go to a different Frame instance, not the one being shown. Change
frame.addKeyListener(new Frame());
to:
frame.addKeyListener(frame);
So that now the KeyListener drives the true displayed Frame instance of interest.
Other issues, this is not good:
catch (Exception e){}
Always catch specific exceptions and almost always, you should handle them. At least do something like this:
catch (IOException e) {
e.printStacktrace();
}
You do:
frame.addKeyListener(new Frame());
Which creates a new frame instead of adding the current frame as the Listener.
So you change it tO
frame.addKeyListener(frame);
So, I am using ImageIcon and Image to animate a character. So far my code makes it look like the character is running however for a reason that I can't figure out KeyListener is not working. I have been at this for a while and I am wondering what I am doing wrong. This is my code:
*Right now I took out moving up and down because I couldn't get side to side to work. velyY was going to be the change in y.
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.MediaTracker;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Image;
public class Main extends JPanel implements ActionListener,KeyListener{
ImageIcon images[];
int x = 100;
int y = 5;
int velX;
int velY;
int totalImages =3, currentImage = 0, animationDelay = 160;
Timer animationTimer;
public Main() {
images = new ImageIcon[totalImages];
images[0] = new ImageIcon("standing.png");
images[1] = new ImageIcon("ready.png");
images[2] = new ImageIcon("running.png");
startAnimation();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics g2 = (Graphics) g;
if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE){
Image img = images[currentImage].getImage();
g2.drawImage(img, x, 407, null);
currentImage = (currentImage + 1) % totalImages;
}
}
public void actionPerformed(ActionEvent e) {
repaint();
x+=velX;
}
public void right(){
velX = 8;
}
public void left(){
velX = -8;
}
public void keyPressed(KeyEvent arg0) {
int code = arg0.getKeyCode();
if (code == KeyEvent.VK_A){
left();
}
if(code == KeyEvent.VK_D){
right();
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
velX = 0;
velY = 0;
}
public void startAnimation() {
if (animationTimer == null) {
currentImage = 0;
animationTimer = new Timer(animationDelay, this);
animationTimer.start();
} else if (!animationTimer.isRunning())
animationTimer.restart();
}
public void stopAnimation() {
animationTimer.stop();
}
}//end class
You have to register your KeyListener to your panel, if you want it to manage key events.
The second thing is that a JPanel is not focusable by default, so you have to make it focusable to receive key events.
In your Main constructor, just add :
setFocusable(true); // make your panel focusable
addKeyListener(this); // register the key listener
I am trying to make simple program, exercise actually - its description is included in attached code. My trouble is that keyPressed() method is completely ignored. Please take a look if possible and provide me with some hints on what I am doing wrong.
class exercise_chapter10_5
/*
White a program that creates a window with a menu bar. The menu bar should have
a single menu that has 10 menu items with text: 0, 1, . . . , 9, respectively. When a user
selects a number from the menu bar, the corresponding number should be displayed
inside the panel of the window. Once finished, add a key listener. When a user types
a digit between 0 and 9, the digit should be displayed in the window. Create an array
to store the menu items.
*/
package exercise;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class exercise_chapter10_5 {
public static void main(String[] args) throws Exception {
MyFrame frame = new MyFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyFrame extends JFrame {
MyPanel p;
public MyFrame() {
setSize(300, 300);
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
//a window with a menu bar
JMenu numbers = new JMenu(" Numbers ");
bar.add(numbers);
// Create an array to store the menu items
ArrayList<JMenuItem> menuitems = new ArrayList<JMenuItem>();
for (int i = 0; i < 10; i++) {
menuitems.add(new JMenuItem(i + ""));
}
for (int i = 0; i < menuitems.size(); i++) {
numbers.add(menuitems.get(i));
}
// add action listener for every menu item
for (int i = 0; i < menuitems.size(); i++) {
menuitems.get(i).addActionListener(new NumberListener(i));
}
p = new MyPanel();
add(p);
}
class NumberListener implements ActionListener {
private int number;
public NumberListener(int num) {
this.number = num;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
p.changeNumber(number);
}
}
}
class MyPanel extends JPanel {
private int number;
public void changeNumber(int num) {
this.number = num;
repaint();
}
public MyPanel() {
this.setFocusable(true);
this.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
changeNumber((e.getKeyChar() - '0'));
//System.out.println(e.getKeyChar());
System.out.println("In Panel the number typed is: " + number);
repaint();
}
});
System.out.println("Panel was born");
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1) {
System.out.println("current number is: " + number);
repaint();
}
if (e.getButton() == 3) {// right button was pressed
System.out.println("Right mouse button was pressed");
repaint();
}
}
});
}
public void showMessage(String s, Graphics2D g2) {
Font myFont = new Font(" SansSerif ", Font.BOLD + Font.ITALIC, 40);
g2.setFont(myFont);
g2.setColor(Color.RED);
Rectangle2D textBox = myFont.getStringBounds(s, g2.getFontRenderContext());
g2.drawString(s, (int) (getWidth() / 2 - textBox.getWidth() / 2), (int) (getHeight() / 2 - textBox.getHeight()));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
showMessage(Integer.toString(number), g2);
}
}
Thanks for your hints. What worked for me here is that I had to call setFocusable(true) method within JPanel constructor first.
class MyPanel extends JPanel {
private int number;
public void changeNumber(int num) {
this.number = num;
repaint();
}
public MyPanel() {
this.setFocusable(true);
this.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
changeNumber((e.getKeyChar() - '0'));
//System.out.println(e.getKeyChar());
System.out.println("In Panel the number typed is: " + number);
repaint();
}
});
System.out.println("Panel was born");
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.getButton() == 1) {
System.out.println("current number is: " + number);
repaint();
}
if (e.getButton() == 3) {// right button was pressed
System.out.println("Right mouse button was pressed");
repaint();
}
}
});
}
I have a problem with JApplet. The code was working just fine, but when I converted it from JFrame to JApplet, the render part stopped working properly. Basicly what I'm trying to do is simplistic draw app. When launching applet, half of time repaint() is not working (There is no gray background; you have to put mouse over button for it to update its color etc), furtheremore the pixel rendering part is not shown up at all. Here's the code:
The Frame class (JApplet)
package painter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Frame extends JApplet {
public JPanel panel;
private JButton plus, minus, buttonColor;
private int scaleSize;
private JLabel labelScale;
private final Timer updateTimer;
private static boolean painting = false;
public static Color currentColor;
public static int mode = 0;
// 0 = draw; 1 = setcolor; 2 = erase
private ArrayList<Pixel> pixelArray;
public Frame() {
pixelArray = new ArrayList<>();
for (int i = 1; i <= 8; i++) {
for (int j = 1; j <= 8; j++) {
pixelArray.add(new Pixel(i, j));
}
}
setLayout(new BorderLayout());
panel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//g.fillRect(10, 10, 100, 100); <- test if fillRect works at all. Yus it does.
for (int i = 0; i < pixelArray.size(); i++) {
pixelArray.get(i).render(g);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
};
//panel.setBounds(0, 0, 800, 800);
//add(panel);
getContentPane().add(panel);
//panel.setLayout(null);
//panel.setOpaque(true);
//panel.setDoubleBuffered(true);
currentColor = Color.yellow;
buttonColor = new JButton("Choose color");
buttonColor.setBounds(10, 10, 128, 64);
buttonColor.setBackground(currentColor);
buttonColor.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
currentColor = JColorChooser.showDialog(null, "JColorChooser Sample", Color.gray);
}
});
updateTimer = new Timer(20, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonColor.setBackground(currentColor);
repaint();
}
});
updateTimer.start();
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
painting = true;
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
painting = false;
}
});
panel.add(buttonColor);
repaint();
}
public static boolean getPaint() {
return painting;
}
public static void main(String[] args) {
new Frame();
}
}
And here is the Pixel class:
package painter;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.MouseInfo;
import java.awt.Point;
public class Pixel {
private Color color;
private int size;
private int x, y, relativex, relativey;
public Pixel(int relx, int rely) {
color = new Color(0x999999, false);
size = 32;
x = relx * size + 64;
y = rely * size + 64;
}
public boolean mouseOver() {
Point pos, mousepos;
pos = new Point(x, y);
mousepos = MouseInfo.getPointerInfo().getLocation();
if ((mousepos.x > pos.x)
&& (mousepos.x < pos.x + size)
&& (mousepos.y > pos.y)
&& (mousepos.y < pos.y + size)) {
return true;
} else {
return false;
}
}
public void render(Graphics g) {
g.setColor(color);
if (mouseOver() && Frame.getPaint()) {
if (Frame.mode == 0) {
color = Frame.currentColor;
}
if (Frame.mode == 1) {
Frame.currentColor = color;
}
if (Frame.mode == 2) {
color = new Color(0xffffffff, true);
}
}
g.fillRect(x, y, size, size);
if (mouseOver()) {
g.setColor(Color.black);
g.drawRect(x, y, size - 1, size - 1);
g.setColor(Color.yellow);
g.drawRect(x + 1, y + 1, size - 3, size - 3);
}
//g.fillRect(10, 10, 250, 250);
}
}
As a stab in the dark, don't call Graphics#dipose on a Graphics context you did not create yourself explicitly
Apart from the fact the the Graphics context is a shared resource, used by all the components that might need to be painted within a given paint cycle, it can also prevent what ever was painted to it to be displayed on some platforms
In 15 years of professional development, I've never had reason to call Toolkit.getDefaultToolkit().sync();. I doubt it'll make that big a difference, I'm just saying
Java applets provide us with these methods
[here] http://docs.oracle.com/javase/tutorial/deployment/applet/appletMethods.html
the method
public void paint(Graphics g){}
is used as alternative of
public void paintComponent(Graphics g){}
of swing.
Check out http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html for the recommended way to perform custom painting of swing components
So I have am trying to make a keyListener for the arrow keys that responds to the arrow keys, and can handle multiple keys at once. I am trying to put the keys pressed into an ArrayList, and then handle them in my repaint() method. However, I have a problem. I am unsure where to add the keys, and where to remove them. I am not looking so much for a code solution as much as the logic that should go behind this.
//graham
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Arrows extends JPanel implements KeyListener {
private int c = 0;
private int x = 250;
private int y = 250;
private static ArrayList<Integer> keys = new ArrayList<Integer>();
public Arrows() {
this.setPreferredSize(new Dimension(500, 500));
addKeyListener(this);
}
public void addNotify() {
super.addNotify();
requestFocus();
}
public void paintComponent(Graphics g) {
//*********
//need to update to make so can press (and hold) multiple different keys at once
//*********
g.setColor(Color.WHITE);
g.fillRect(x, y , 20, 20);
for(int i = 0; i < keys.size(); i++){ //********> only want to handle one at a time
//handle each key
c = keys.get(i);
switch(c){
case 37:
//left arrow
x -= 10;
keys.remove(i);
break;
case 38:
// up arrow
y -= 10;
keys.remove(i);
break;
case 39:
//right arrow
x += 10;
keys.remove(i);
break;
case 40:
//down arrow
y += 10;
keys.remove(i);
break;
}
}
g.setColor(Color.BLUE);
g.fillRect(x, y, 20, 20);
}
public void keyPressed(KeyEvent e) {
//******
//need to create a list of keys pressed, then process them in the repaint. Later delete them after pressed
//******
keys.add(e.getKeyCode());
//repaint();
}
public void keyReleased(KeyEvent e) {
//****
//here need to repaint --- need to correct to do something proper later --- due to holding down a key teleports..
//****
repaint();
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] s) {
JFrame f = new JFrame();
f.getContentPane().add(new Arrows());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
//need to null out keys
keys.add(65);
}
}
Here see if you can use my code as an example. They're fairly similar.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MyGame extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx =0, vely =0, g = 0;
private Color color;
public MyGame() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 1000);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(x, y, 50, 30);
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
{
if (code == KeyEvent.VK_DOWN) {
vely = 1; // removing velx = 0 allows us to go vertically and horizontlly at the same time
}
if (code == KeyEvent.VK_UP) {
vely = -1; // same goes for here
}
if (code == KeyEvent.VK_LEFT) {
velx = -1;
}
{
if (code == KeyEvent.VK_RIGHT) {
velx = 1;
}
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}
public static void main (String arge[]){
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Incoming());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}