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.
Related
Copy and modify your canvas to implement the KeyListener interface, add itself as its own KeyListener , and call setFocusable(true) in order to receive keyboard focus. When a key is typed, your program should draw the corresponding character (see KeyEvent.getKeyChar() ) on the canvas at the location of the last mouse event. If another key is typed without the mouse being clicked, then draw the next character to
the right of the previous one as if you were typing in a text field. Again, think about what state you need to maintain to do this. It doesn’t have to be perfect (you can hard-code the width of the characters if you like).
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Canvas05 extends JComponent implements KeyListener {
public Canvas05() {
addKeyListener(this);
setFocusable(true);
}
#Override
public void keyTyped(KeyEvent e) {
System.out.print(e.getKeyChar());
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
public static void main (String[] args){
Canvas05 c = new Canvas05();
JFrame frame = new JFrame("Q05");
frame.add(c);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Here you go. The location from mouseEvent is very easily acessable from the MouseListener event where you can declare both an x and a y variable from
MouseListener.getX() and MouseListener.getY();
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JPanel{
public static int WIDTH = 500,HEIGHT = 500;
public static char myChar = ' ';
public static Game game = new Game();
public static JFrame frame = new JFrame();
public Game() {
this.addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent e) {
myChar = (char)e.getKeyCode();
repaint();
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
setFocusable(true);
}
public void paint(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g.clearRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.red);
g.setFont(new Font("Cambria",Font.BOLD,30));
g.drawString(String.valueOf(myChar),100, 100);
}
public static void main(String [] args){
frame.add(game);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I tried this code and all it was showing was the text. The Main script is:
import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Main extends JFrame{
public static void main(String[] args) {
DisplayMode dm = new DisplayMode(800, 600, 32, DisplayMode.REFRESH_RATE_UNKNOWN);
Main m = new Main();
m.run(dm);
}
public void run(DisplayMode dm){
setBackground(Color.PINK);
setForeground(Color.WHITE);
setFont(new Font("Arial",Font.PLAIN,24));
Screen s = new Screen();
try {
s.setFullScreen(dm, this);
try{
Thread.sleep(5000);
}catch(Exception ex){}
}finally{
s.RestoreScreen();
}
}
public void paint(Graphics g){
g.drawString("hello", 200, 200);
}
}
The other screen class is:
import java.awt.DisplayMode;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;
import javax.swing.JFrame;
public class Screen {
private GraphicsDevice gc;
public Screen(){
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
gc = env.getDefaultScreenDevice();
}
public void setFullScreen(DisplayMode dm, JFrame window){
window.setUndecorated(true);
window.setResizable(false);
gc.setFullScreenWindow(window);
if (dm != null && gc.isDisplayChangeSupported()){
try{
gc.setDisplayMode(dm);
}catch(Exception ex){}
}
}
public Window getFullScreenWindow(){
return gc.getFullScreenWindow();
}
public void RestoreScreen(){
Window w = gc.getFullScreenWindow();
if(w != null){
w.dispose();
}
gc.setFullScreenWindow(null);
}
}
My code is word for word to a tutorial I watched:
https://thenewboston.com/videos.php?cat=30&video=17934
and his worked. Also, when I switch it to 16 bit graphics, the paint method does not even work. Please Help!
In your class Main, in public void run type:
Screen s = new Screen();
try {
s.setFullScreen(dm, this);
try{
Thread.sleep(5000);
}catch(Exception ex){}
}finally{
s.RestoreScreen();
}
You forgot to set the JFrame visible
In your fullscreen method add this
window.setVisible(true);
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();
}
}
}
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();
}
}
});
}
}
I am trying to create a form. there is a button that when clicking the button, a photo which is specified would appear. my problem is, when I click the button, the picture pops up and if the cursor passes the form boundary, the image disappears. here is my code:
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SeamCarving extends JFrame
{
public static void main(String[] args) throws IOException {
final BufferedImage input = ImageIO.read(new File("path"));
final BufferedImage[] toPaint = new BufferedImage[]{input};
final Frame frame = new Frame("Seams") {
#Override
public void update(Graphics g) {
final BufferedImage im = toPaint[0];
if (im != null) {
g.clearRect(0, 0, getWidth(), getHeight());
g.drawImage(im, 0, 0, this);
}
}
};
frame.setSize(input.getWidth(), input.getHeight());
frame.setVisible(true);
frame.add(startButton);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BufferedImage out = input;
out = deleteVerticalSeam(out);
toPaint[0] = out;
frame.repaint();
System.out.println("Do Something Clicked");
}
});
}
}
Don't override update, this isn't how painting is achieved in Swing. Attempting to paint directly to a top level container like JFrame is problematic at best.
Instead, start with a JPanel and use it's paintComponent method instead. Make sure you call super.paintComponent as well.
In fact, you could probably just use a JLabel to display the image instead.
Take a look at;
Performing Custom Painting
How to use labels
For more details
Updated with example
I still think a JLabel would be simpler solution, but what do I know.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SeamCarving {
public static void main(String[] args) {
new SeamCarving();
}
public SeamCarving() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage input;
private BufferedImage[] toPaint;
public TestPane() {
try {
input = ImageIO.read(new File("C:\\hold\\thumbnails\\2005-09-29-3957.jpeg"));
toPaint = new BufferedImage[1];
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
BufferedImage out = input;
out = input; //deleteVerticalSeam(out);
toPaint[0] = out;
repaint();
System.out.println("Do Something Clicked");
}
});
add(startButton);
}
#Override
public Dimension getPreferredSize() {
return input == null ? new Dimension(400, 400) : new Dimension(input.getWidth(), input.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (toPaint[0] != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(input, 0, 0, this);
g2d.dispose();
}
}
}
}
The problem with overriding update is the paint subsystem can choose to avoid calling and end up calling paint directly, circumventing your painting.
Painting also involves painting child components (like your button) and borders, which you've conveniently discarded by not calling super.update.