how to call the method repaint() after a certain time - java

I want to renew the toolTip so i thought in using the repaint method , to repaint the frame every 30 seconds but it doesn't work . can someone helpme..
GrphicsTut Method
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class GrphicsTut extends JFrame{
Timer timer;
Image image;
Image image2;
int x1,y1,x2,y2;
Font fonte = new Font("TimesRoman ",Font.BOLD,100);
public GrphicsTut(){
MouseListenerJ bkg = new MouseListenerJ();
this.setTitle("Remember g for Graphics");
this.setSize(600,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.addMouseMotionListener(bkg);
this.addMouseListener(bkg);
this.add(bkg);
}
public void paint(Graphics gr){
gr.setFont(fonte);
gr.setColor(Color.black);
gr.drawLine(35,35, 410, 110);
gr.drawLine(410,110, 310, 410);
ImageIcon i=new ImageIcon("image/1005511030.jpg");
image=i.getImage();
gr.drawImage(image, 35, 35,null);
gr.drawImage(image, 400, 100,null);
gr.drawImage(image, 300, 400,null);
repaint();
}
public static void main(String[] args) {
new GrphicsTut();
}
}
and here the method for MouseListner
package Carte;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MouseListenerJ extends JPanel implements MouseListener, MouseMotionListener {
public MouseListenerJ(){}
public void paint(Graphics g){}
#Override
public void mouseClicked(MouseEvent me) {
// TODO Auto-generated method stub
if(me.getX()>=35 && me.getX()<=70 && me.getY()>=35 &&me.getY()<=70){
//JOptionPane.showMessageDialog(null,"Que voulez vous faire");
new Carte1();
}
}
#Override
public void mouseEntered(MouseEvent me) {
// TODO Auto-generated method stub
//System.out.println("Entered at x "+me.getX());
}
#Override
public void mouseExited(MouseEvent me) {
// TODO Auto-generated method stub
//System.out.println("Exited");
}
#Override
public void mousePressed(MouseEvent me) {
// TODO Auto-generated method stub
System.out.println("Pressed at : "+me.getX()+" "+me.getY());
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
System.out.println("released");
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent me) {
// TODO Auto-generated method stub
if(me.getX()>=35 && me.getX()<=70 && me.getY()>=35 && me.getY()<=70){
//JOptionPane.showMessageDialog(null,"Que voulez vous faire");
this.setToolTipText("text");
System.out.println(me.getX()+" "+me.getY());
}
else if(me.getX()>=400 && me.getX()<=470 && me.getY()>=100 && me.getY(<=170){
this.setToolTipText("Text 2");
System.out.println(me.getX()+" "+me.getY());
}
}
}

Consider using the native Swing components for your objectives. They provide all the features you want:
Handle mouse clicks
Display tooltips
Display images
Here is a small snippet showing you how to use JButton:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestButtons {
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(2, 2, 20, 20));
panel.add(createButton("https://pbs.twimg.com/profile_images/378800000534649369/489a1e058bea59b62fd73c56f4bcb6c7.jpeg"));
panel.add(createButton("https://pbs.twimg.com/profile_images/378800000714838591/ebbde1563faae6da2be79df945a7a02b.jpeg"));
panel.add(createButton("https://pbs.twimg.com/profile_images/3477392906/f1907df0bd76668deac4a5e31a22fbe7.jpeg"));
panel.add(createButton("https://pbs.twimg.com/profile_images/2718799802/9567ed3c3299f6f6ab1ffcbcbfd93da5.jpeg"));
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private JButton createButton(final String url) throws MalformedURLException {
final JButton button = new JButton(new ImageIcon(new URL(url)));
button.setToolTipText("You are looking at image located at " + url);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(button,
"You clicked on image located at " + url);
}
});
return button;
}
/**
* #param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestButtons().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}

Related

How do I use a mouse listener to call another class?

I have bits and and pieces of the mouse listener, but I am not sure how to tie it all together. I am trying to have a tic tac toe game activate when the user clicks on the play games button. Assistance would be greatly appreciated.
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.EventQueue;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.GridBagLayout;
import java.awt.event.*;
import java.awt.event.ActionListener.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import java.awt.Color;
public class Use_PF_Interface extends JFrame implements Pet_Fish_Interface, MouseListener
{
// instance variables - replace the example below with your own
private JFrame window;
private JPanel backgroundPanel;
private JLabel lblBackgroundImage = new JLabel();
private JButton feedButton = new JButton("Feed Fish");
private JButton playGamesButton = new JButton("Play Game");
volatile private boolean mouseDown = false;
//creates frame window
public Use_PF_Interface()
{
setTitle("Virtual Pet Fish");
setSize(400, 400);
//initializes panels and panel layout
backgroundPanel = new JPanel();
backgroundPanel.setOpaque(false);
backgroundPanel.setLayout(new FlowLayout());
lblBackgroundImage.setLayout(new FlowLayout());
//sets background image of panel
lblBackgroundImage.setIcon(new ImageIcon("OCEAN2.jpg"));
lblBackgroundImage.setLayout(new BorderLayout());
lblBackgroundImage.setBounds(0, 0, 400, 400);
//adds button to panels
backgroundPanel.add(feedButton);
backgroundPanel.add(playGamesButton);
lblBackgroundImage.add(backgroundPanel);
add(lblBackgroundImage);
feedButton.addMouseListener(this);
playGamesButton.addMouseListener(listener);
addMouseListener(this);
}//creates frame window
/**
* This method will create an action for the button.
* #pre none
* #return tic tac toe game
* #param none
* #post none
*/
public void mousePressed(MouseEvent e)
{
if (e.getButton() == MouseEvent.playGamesButton)
{
mouseDown = true;
Tic_Tac_Toe();
}
}
public void mouseReleased(MouseEvent e)
{
if(e.getButton() == MouseEvent.feedButton)
{
mouseDown = false;
}
}
public void mouseExited(MouseEvent e)
{
}
I am currently recieving this error: Use_PF_interface is not abstract and does not override abstract method mouseEntered(java.awt.event.MouseEvent) in java.awt.event.MouseListener
The solution is very simple. MouseListener is an Interface. An Interface is a class with methods, which the class that implements this interface, must contain. Even if these methods contain nothing, you have to include them in your code. So if you want to implement the MouseListener you have to override these 5 methods:
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Example implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#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
}
}
And by the way, can't you just use an ActionListener for that, what you're trying to do?
Not too sure if this is the issue, but should there be a mouseEntered method inside that class to override as mentioned?

Is it possible to start drag on mousePressed using java Swing DnD api?

In the example below there is a standard way to trigger drag and drop, which is mousePress+mouseMove.
import javax.swing.*;
import java.awt.datatransfer.StringSelection;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
public class DndExample extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DndExample());
}
public DndExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel dragLabel = createDndLabel();
getContentPane().add(dragLabel);
pack();
setVisible(true);
}
private JLabel createDndLabel() {
JLabel label = new JLabel("Drag me, please");
DragGestureListener dragGestureListener = (dragTrigger) -> {
dragTrigger.startDrag(null, new StringSelection(label.getText()));
};
DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(label, DnDConstants.ACTION_COPY, dragGestureListener);
return label;
}
}
Is it possible to trigger startDrag on mousePressed without mouseMove? The desired behaviour is something like that: I press the mouse button then cursor changes indicating that drag has started, if mouse is moved than drag is continued. I obviously know that I may add MouseListener and change cursor manually but there is much more code needed to restore previous cursor.
Because you're asking for non-standard behaviour, you're going to need to do the "extra" lifting yourself, this requires you to have a MouseListener with mousePressed setting the cursor and mouseReleased resting it (so if the user just clicks and doesn't drag the component, you don't end up with a stupid cursor state) and the DragGestureListener#dragDropEnd also resetting the cursor.
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
public class DragAndDropTest {
public static void main(String[] args) {
new DragAndDropTest();
}
public DragAndDropTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(1, 2));
add(new DropPane());
add(new DragPane());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class DragPane extends JPanel {
private DragSource ds;
private Transferable transferable;
public DragPane() {
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
#Override
public void mouseReleased(MouseEvent e) {
setCursor(Cursor.getDefaultCursor());
}
});
ds = new DragSource();
transferable = new Transferable() {
#Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DataFlavor.stringFlavor};
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.stringFlavor.equals(flavor);
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return "This is a test";
}
};
ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, new DragGestureListener() {
#Override
public void dragGestureRecognized(DragGestureEvent dge) {
// This is where you would export the data you want
// to transfer
ds.startDrag(dge, Cursor.getPredefinedCursor(Cursor.HAND_CURSOR), transferable, new DragSourceListener() {
#Override
public void dragEnter(DragSourceDragEvent dsde) {
}
#Override
public void dragOver(DragSourceDragEvent dsde) {
}
#Override
public void dropActionChanged(DragSourceDragEvent dsde) {
}
#Override
public void dragExit(DragSourceEvent dse) {
}
#Override
public void dragDropEnd(DragSourceDropEvent dsde) {
setCursor(Cursor.getDefaultCursor());
}
});
}
});
setLayout(new GridBagLayout());
add(new JLabel("Drag from here"));
setBorder(new LineBorder(Color.RED));
}
}
public class DropPane extends JPanel {
private List<Point> dropPoints;
public DropPane() {
dropPoints = new ArrayList<>(25);
setDropTarget(new DropTarget(this, new DropTargetListener() {
#Override
public void dragEnter(DropTargetDragEvent dtde) {
}
#Override
public void dragOver(DropTargetDragEvent dtde) {
}
#Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
#Override
public void dragExit(DropTargetEvent dte) {
}
#Override
public void drop(DropTargetDropEvent dtde) {
// Normally here, I'd inspect the Transferable and make sure
// what is been dropped and can be imported, I'd then go through
// the process of unwrapping the data from the Transferable and
// processing it appropriatly, but in this example, I really don't
// care, I just care about WHERE the event occured
dropPoints.add(dtde.getLocation());
dtde.dropComplete(true);
repaint();
}
}));
setLayout(new GridBagLayout());
add(new JLabel("Drop to here"));
setBorder(new MatteBorder(1, 1, 1, 0, Color.RED));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
for (Point p : dropPoints) {
g.fillOval(p.x - 2, p.y - 2, 5, 5);
}
}
}
}
Now, remember, you're doing something the system doesn't want you to do, so it might turn around and byte you any way
I might consider writing a factory method which took a reference to Component, Transferable (and probably a Cursor) and build and registered the MouseListener and DragSource

Add image on mouse click? Java applet

How would I go and add an image on the mouse coordinates when the mouse clicks? I have looked at this :Adding Images on Mouse Click to JPanel
But I don't understand it and am trying to add it on mouse click in an applet
And please don't say, "Learn some basic java first! and provide me with a link to some oracle docs", I just can't get any info from those things.
Code:
> `import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
`import java.net.URL;
import javax.imageio.ImageIO;
public class SHR extends Applet implements MouseListener{
int a;
int b;
#Override
public void mouseClicked(MouseEvent e) {
a = e.getX();
b = e.getY();
paint(null, a, b);/this is the part i am having trouble with
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
public void paint(Graphics g, int x, int y){
BufferedImage photo = null;
try
{
URL u = new URL(getCodeBase(),"SilverHandRecruit.png");
photo = ImageIO.read(u);
}
catch (IOException e)
{
g.drawString("Problem reading the file", 100, 100);
}
g.drawImage(photo,x, y, 10, 30, null);
}
}
`
The problem is, I don't know what I am supposed to replace "null" with to get it to work
Thanks
Start by taking a look at Painting in AWT and Swing and Performing Custom Painting to understand how painting works in AWT/Swing.
Then, take a look at 2D Graphics for more details about how you can use the Graphics class to paint things with.
This is a really basic example which loads a single image and every time you click on the panel, moves it to that point.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawImage {
public static void main(String[] args) {
new DrawImage();
}
public DrawImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage image;
private Point drawPoint;
public TestPane() {
try {
image = ImageIO.read(getClass().getResource("/SmallPony.png"));
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
drawPoint = new Point(e.getPoint());
repaint();
}
});
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (drawPoint != null) {
g2d.drawImage(image, drawPoint.x, drawPoint.y, this);
}
g2d.dispose();
}
}
}

Drag JComponent within JPanel

I have a subclass of JPanel which contains an array of JComponent objects. I then use the paint(Graphics g) method to position the JComponent objects next to each other in the panel. All these JComponent Objects implement MouseMostionListener and I initialise the listener using addMouseMotionListener(this);, I also have the methods mouseMoved(MouseEvent m) and mouseDragged(MouseEvent m). All the components are being drawn correctly but the mouseMoved(MouseEvent m) and mouseDragged(MouseEvent m)are never called. Any ideas why?
Here is my code:
JPanel Subclass
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Image;
import javax.swing.ImageIcon;
import java.awt.Graphics;
import java.util.ArrayList;
public class ExamplePanel extends JPanel
{
ArrayList<ExampleComponent> components;
public ExamplePanel()
{
components = new ArrayList<ExampleComponent>();
}
public void paint(Graphics g)
{
for(ExampleComponent c : components)
g.drawImage(c.getImage(), 0, 30, 50, 75, null);
}
public void addComponent(ExampleComponent j)
{
components.add(j);
repaint();
}
public static void main(String[] args)
{
JFrame app = new JFrame("Staff Prototype");
app.setSize(700,200);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setResizable(false);
ExamplePanel s = new ExamplePanel();
app.getContentPane().add(s);
s.addComponent(new ExampleComponent());
app.setVisible(true);
}
}
JComponent Subclass:
import java.awt.Image;
import javax.swing.JComponent;
import javax.swing.ImageIcon;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class ExampleComponent extends JComponent implements MouseMotionListener
{
Image image;
public ExampleComponent()
{
ImageIcon icon = new ImageIcon("image.png");
image = icon.getImage();
addMouseMotionListener(this);
}
public Image getImage()
{
return image;
}
public void mouseMoved(MouseEvent m)
{
System.out.println("Mouse Moved");
}
public void mouseDragged(MouseEvent m)
{
System.out.println("Mouse Dragged");
}
}
1)Add components like you do isn't proper way.
2)Instead of drawing Image use JLabel with icon, you get a lot of advantages with it from 'box'.
I have fixed your code, examine that:
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Example extends JPanel {
ArrayList<ExampleComponent> components;
public Example() {
components = new ArrayList<ExampleComponent>();
}
public void addComponent(ExampleComponent j) {
components.add(j);
add(j);
}
public static void main(String[] args) {
JFrame app = new JFrame("Staff Prototype");
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Example s = new Example();
s.setLayout(null);
app.getContentPane().add(s);
s.addComponent(s.new ExampleComponent(new Rectangle(0,0,25,25)));
s.addComponent(s.new ExampleComponent(new Rectangle(45,45,25,25)));
app.pack();
app.setVisible(true);
}
class ExampleComponent extends JPanel implements MouseMotionListener {
public ExampleComponent(Rectangle bounds) {
URL resource = getClass().getResource("3_disc.png");
ImageIcon icon = new ImageIcon(resource);
add(new JLabel(icon));
addMouseMotionListener(this);
setBounds(bounds);
}
public void mouseMoved(MouseEvent m) {
System.out.println("Mouse Moved");
}
public void mouseDragged(MouseEvent m) {
System.out.println("Mouse Dragged");
}
}
}

KeyListener Java

I am trying to use KeyListener in my code.... But it's not working, the KeyListener not responding I think...
If you guys see anything wrong please tell me. I don't know why it's not working.
Thanks in advance.
Here is the code.
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class Main extends JFrame {
static void drawFrame(JFrame frame) {
frame.setSize(610, 805);
frame.setLocation(145, 15);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
JFrame frame = new JFrame("PacMan");
drawFrame(frame);
MyPanel panel = new MyPanel();
panel.setBounds(00, 00, 610, 800);
frame.setLayout(null);
frame.getContentPane().setLayout(null);
frame.getContentPane().add(panel);
}
}
MyPanel Class
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyPanel extends JPanel implements KeyListener {
private int xpac = 285, ypac = 570;
public MyPanel() {
this.requestFocus();
this.requestFocusInWindow();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawMap1(g);
drawPacman(g);
addKeyListener(this);
}
void drawMap1(Graphics g) {
BufferedImage image = null;
try {
image = ImageIO.read(new File("pacmap1.png"));
} catch (IOException e) {
System.out.println("Can't find the Image.");
}
setBackground(Color.BLACK);
g.drawImage(image, 0, 0, null);
}
void drawPacman(Graphics g) {
int x = xpac, y = ypac;
BufferedImage image = null;
try {
image = ImageIO.read(new File("pacright.png"));
} catch (IOException e) {
System.out.println("Can't find the Image.");
}
g.drawImage(image, x, y, null);
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Hi there Buddy");
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Hi there Buddy");
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Hi there Buddy");
}
}
You should just comment out the addKeyListener in the MyPanel class and do this in the Main class after you instantiate the MyPanel:
frame.addKeyListener(panel);
You should put the this.addKeyListener(this); in your MyPanel class constructor, not the paintComponent method.
Please always use a KeyBindings for such Tasks. See: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
As a little tip, I would recommend you to implement KeyListener as an AnonymousClass.

Categories

Resources