I have a menu button that is supposed to transition into the game state once you click on it, but it won't work. Here is my MouseInput class. Ignore all of the methods except for the MousePressed method.
package com.game.src.main;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseInput implements MouseListener
{
#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
}
public void mousePressed(MouseEvent e)
{
int mx = e.getX();
int my = e.getY();
/**
public Rectangle playButton = new Rectangle(Game.WIDTH/2 + 120, 150, 100, 50);
public Rectangle helpButton = new Rectangle(Game.WIDTH/2 + 120, 250, 100, 50);
public Rectangle quitButton = new Rectangle(Game.WIDTH/2 + 120, 350, 100, 50);
*/
if (mx >= Game.WIDTH/2 + 120 && mx <= Game.WIDTH/2 + 220)
{
if (my >= 150 && mx <= 200)
Game.State = Game.STATE.GAME;
}
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
Here is the init method, which is part of the Game class. I bolded and italicized the line of code where I supposedly use the addMouseListener method to enable the mouse functionality (but clearly it doesn't work).
public static enum STATE
{
MENU,
GAME
};
public static STATE State = STATE.MENU;
public void init()
{
requestFocus();
BufferedImageLoader loader = new BufferedImageLoader();
try
{
spriteSheet = loader.loadImage("/spritesheettemplate.png");
background = loader.loadImage("/bkg.png");
}
catch(IOException e)
{
e.printStackTrace();
}
addKeyListener(new KeyInput(this));
***addMouseListener(new MouseInput());***
tex = new Textures(this);
p = new Player(WIDTH/2*SCALE - 16, HEIGHT/2*SCALE - 16, tex);
c = new Controller(this, tex);
menu = new Menu();
eA = c.getEntityA();
eB = c.getEntityB();
c.addEnemy(enemyCount);
}
Any help would be greatly appreciated. This is the final step in my game. I'm following a tutorial series on Youtube, but the uploader never responds to questions, so you guys are my only hope (I guess I'm being a little dramatic). If you need me to post more parts of my code, I can do that.
Just add an ActionListener to that menu button without dealing with MouseListener.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Game.State = Game.STATE.GAME;
}
});
Related
I am currently creating a solitaire game where a card will pop up on the bottom left corner of the middle JPanel if it was drawn by the user. Once shown in the bottom left corner, it should be able to be dragged freely. However, the image itself is not updating while it is being dragged. Additionally, the terminal outputs that I am dragging the card of several coordinates but the image itself never seems to move. The stack of cards above it is using the same move listener class and works perfectly as it can be dragged freely. Could someone help me in finding out what the problem is? Thank you!
This is the code for my move listener class:
public class MoveListener extends javax.swing.JFrame implements MouseListener, MouseMotionListener{
ImageIcon image = new ImageIcon("back of playing card.png");
int WIDTH = image.getIconWidth();
int HEIGHT = image.getIconHeight();
Point imgCorner;
Point startPt;
Component label;
MoveListener(JLayeredPane pane) {
imgCorner = new Point(0, 0);
this.label = pane;
}
MoveListener(JLabel label) {
imgCorner = new Point(0,0);
this.label = label;
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
Component pressedComponent = e.getComponent().getComponentAt(e.getPoint());
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
startPt = SwingUtilities.convertPoint(label, e.getPoint(), label.getParent());
System.out.println("Starting point: " + startPt);
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
startPt = null;
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
Component enteredComponent = e.getComponent().getComponentAt(e.getPoint());
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
Point currPt = SwingUtilities.convertPoint(label, e.getPoint(), label.getParent());
System.out.println("You are currently dragging over the point: " + currPt);
if(label.getParent().getBounds().contains(currPt)) {
Point newPt = label.getLocation();
newPt.translate((currPt.x - startPt.x), (currPt.y - startPt.y));
newPt.x = Math.max(newPt.x, 0);
newPt.y = Math.max(newPt.y, 0);
newPt.x = Math.min(newPt.x, label.getParent().getWidth() - label.getWidth());
newPt.y = Math.min(newPt.y, label.getParent().getHeight() - label.getHeight());
label.setLocation(newPt);
startPt = currPt;
}
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
I have no Idea why my JFrame keeps freezeing after I type Letters into the JTextField "Username" and "Password" :/ Could anyone look thru my code and tell my why and fix it please ?
public class Main
{
public static void main(String [ ] args)
{
LoginWindow loginframe = new LoginWindow();
loginframe.setVisible(true);
loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginframe.initialize();
while(true)
{
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
loginframe.Repaint();
}
}
}
FrameClass:
public class LoginWindow extends JFrame implements MouseListener, KeyListener, MouseMotionListener{
public LoginWindow(){
setSize(806, 629);
setResizable(false);
setLayout(new BorderLayout());
background = new JLabel(ResourceLoader.Iconload("/main_01.jpg"));
background.setBounds(0, 0, 800, 600);
add(background);
background.setLayout(null);
Username = new JTextField("", 20);
Username.setForeground(Color.WHITE);
Username.setBounds(312, 433, 170, 40);
Username.setFont(new Font("Impact", Font.BOLD, 25));
Username.setBackground(Color.BLACK);
Username.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.BLACK));
background.add(Username);
Password = new JPasswordField("", 20);
Password.setForeground(Color.WHITE);
Password.setBounds(312, 489, 170, 40);
Password.setBackground(Color.BLACK);
Password.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.BLACK));
Password.setFont(new Font("Serif", Font.BOLD, 25));
background.add(Password);
}
public void initialize()
{
makestrat();
addKeyListener(this);
requestFocus();
addMouseListener(this);
addMouseMotionListener(this);
}
public void makestrat()
{
createBufferStrategy(2);
strat = getBufferStrategy();
}
public void Repaint()
{
//System.out.println(mouseX + " " + mouseY);
Graphics g = strat.getDrawGraphics();
paintComponents(g);
Draw(g);
g.dispose();
strat.show();
}
public void Update()
{
}
public void Draw(Graphics g)
{
if(((mouseX >= 499) && (mouseX <= 669)) && ((mouseY >= 433)&&( mouseY <= 530))){
g.drawImage(ResourceLoader.ImageLoad("/login_02.jpg"), 502, 459, null);
}else{
g.drawImage(ResourceLoader.ImageLoad("/login_01.jpg"), 502, 459, null);
}
}
private class thehandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
}
}
public void mouseMoved(MouseEvent event)
{
mouseY = event.getY()-26;
mouseX = event.getX()-3;
}
#Override
public void mouseClicked(MouseEvent e) {
PointerInfo a = MouseInfo.getPointerInfo();
Point point = new Point(a.getLocation());
SwingUtilities.convertPointFromScreen(point, e.getComponent());
double mouseX = (int) point.getX();
double mouseY = (int) point.getY();
System.out.println("(ContainerPos) Mouse clicked! X: " + mouseX + " Y: " + mouseY);
}
#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) {
}
#Override
public void mouseReleased(MouseEvent 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
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
You don't need the while loop with the Thread.sleeap(). It's screwing with your program.
What you're trying to achieve here, a call to repaint continuously, can easily be accomplished with a javax.swing.Timer
Don't explicitly call paintComponent. An actual call to the real repaint() method will do that for you. No need to create an imitation Repaint()
Use a JPanel for painting instead of trying to paint on a JFrame
I would initialize, then set visible
Your code doesn't even compilable, so I can try and make fixes for you.
Use Java naming convention: methods and variable start with lower case letters.
Here's an example of a simple Login Window, using a modal JDialog
Learn how to use Layout Managers instead of relying on setBounds()
Point 2. Your main should look like this
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
LoginWindow loginframe = new LoginWindow();
loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginframe.initialize();
loginframe.setVisible(true);
}
});
}
And in your constructor, have a javax.swing.Timer instead of your while loop
private Timer timer = null;
private DrawPanel drawPanel = new DrawPanel(); // see below for DrawPanel
public LoginWindow() {
// add drawPanel somewhere
...
timer = new Timer (50, new ActionListener(){
public void actionPerformed(ActionEvent e) {
drawPanel.repaint();
}
});
timer.start();
}
Point 4. Have an inner JPanel class that you do all your painting in, and add that component to the frame. You'll need to override the paintComponent method.
private DrawPanel extends JPanel {
#Override
protected void paintComponent(Graophics g) {
super.paintComponent(g);
Draw(g);
}
}
The obvious thing is that you shouldn't use Swing (or AWT really) off of the AWT Event Dispatch Thread (EDT). Fix with java.awt.EventQueue.invokeLater and java.swing.Timer (not java.util!). Diagnose with jstack(and jps) or the relevant key sequence in the terminal window (um, ctrl-break in Windows, ctrl-3 in Linux).
When I press somewhere near Top-Left of the window, for some reason the output result for e.getY() is higher by about 40 than e.getX(). I don't see why... do you? Something is not clear to me regarding e.getY().
//BBDemo.java - The main program and window creation
import javax.swing.*;
public class BBDemo extends JApplet{ //this isn't Applet !
public int offset=400;
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame win = new JFrame("Bouncing Ball Demo");
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setContentPane(new BBPanel());
win.pack();
win.setVisible(true);
}
}//endclass BBDemo
//BBPanel.java - The JPanel which organizes the GUI
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/////////////////////////////////////////////////////////////////// BBPanel
public class BBPanel extends JPanel {
BallInBox m_bb; // The bouncing ball panel ///in order to take the Timer->setAnimation from m_bb
Ball BallN;
//========================================================== constructor
/** Creates a panel with the controls and bouncing ball display. */
BBPanel() {
//... Create components
m_bb = new BallInBox();
BallN=new Ball(400,400,400);
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
//... Add Listeners
startButton.addActionListener(new StartAction());
stopButton.addActionListener(new StopAction());
addMouseListener(new PressBall());
//... Layout inner panel with two buttons horizontally ///why inner and outer?
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout()); ///Flow???
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
//... Layout outer panel with button panel above bouncing ball ///???
this.setLayout(new BorderLayout()); ///this ??? ///Board???
this.add(buttonPanel, BorderLayout.NORTH); ///this, NORTH, ???
this.add(m_bb , BorderLayout.CENTER); ///this, CENTER, ???
}//end constructor
////////////////////////////////////// inner listener class StartAction
class StartAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
m_bb.setAnimation(true);
}
}
//////////////////////////////////////// inner listener class StopAction
class StopAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
m_bb.setAnimation(false);
}
}
public class PressBall implements MouseListener {
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
//System.out.print(BallN.m_x-BallN.getDiameter()/2+" ");
System.out.print(e.getX()+" ");
//System.out.print(BallN.m_x+BallN.getDiameter()/2+" ");
//System.out.print(BallN.m_y-BallN.getDiameter()/2+" ");
System.out.print(e.getY()+" ");
//System.out.println(BallN.m_y+BallN.getDiameter()/2+" ");
if ((e.getButton() == 1)
&& (e.getX() >= BallN.m_x-BallN.getDiameter()/2 && e.getX() <=
BallN.m_x+BallN.getDiameter()/2 && e.getY() >= BallN.m_y-BallN.getDiameter()/2 && e.getY() <=
BallN.m_y+BallN.getDiameter()/2 ))
{ m_bb.setAnimation(false);
}else{}
}
#Override
public void mouseClicked(MouseEvent e) {
// 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 mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
}//endclass BBPanel
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/////////////////////////////////////////////////////////////// BouncingBall
public class BallInBox extends JPanel {
//============================================== fields
public Ball m_ball = new Ball(400,400,400);
private int m_interval = 40; // Milliseconds between updates.
private Timer m_timer; // Timer fires to animate one step.
//=================================================== constructor
public BallInBox() {
setPreferredSize(new Dimension(800, 800));
setBorder(BorderFactory.createLineBorder(Color.BLACK));
m_timer = new Timer(m_interval, new TimerAction());
}
//========================================================= setAnimation
public void setAnimation(boolean turnOnOff) {
if (turnOnOff) {
m_timer.start(); // start animation by starting the timer.
} else {
m_timer.stop(); // stop timer
}
}
//======================================================= paintComponent
public void paintComponent(Graphics g) {
super.paintComponent(g); // Paint background, border
m_ball.draw(g); // Draw the ball.
// m_ball.changeColor(g);
}
class TimerAction implements ActionListener {
//================================================== actionPerformed
public void actionPerformed(ActionEvent e) {
m_ball.setBounds(getWidth(), getHeight()); ///???
m_ball.move(); // Move the ball.
repaint(); // Repaint indirectly calls paintComponent. ///why "indirectly"?
}
/* public void mousePressed(MouseEvent e) {
System.out.println("dfvsd");
if ((e.getButton() == 1)
&& (e.getX() >= 400- m_ball.m_x && e.getX() <= 400+ m_ball.m_x && e.getY() >=
400- m_ball.m_x && e.getY() <= 400+ m_ball.m_x)) {m_timer.stop();
// System.out.println("dfvsd");
}else{}
}*/
}
//////////////////////////////////////// inner listener class StopAction
}//endclass
import java.awt.*;
///////////////////////////////////////////////////////////////// BallModel
public class Ball {
//... Constants
final static int DIAMETER = 50;
//... Instance variables
static int m_x; // x and y coordinates upper left
static int m_y;
/*
private int m_velocityX; // Pixels to move each time move() is called.
private int m_velocityY;*/
private int m_rightBound; // Maximum permissible x, y values.
private int m_bottomBound;
public int i=0;
public int offset=400;
//======================================================== constructor
public Ball(int x, int y, int offset) {
m_x = x;
m_y = y;
//offset=400;
}
//======================================================== setBounds
public void setBounds(int width, int height) {
m_rightBound = width - DIAMETER;
m_bottomBound = height - DIAMETER;
}
//============================================================== move
public void move() {
double degrees=(double) i;
double radians=Math.toRadians(degrees);
double Sinu=Math.sin(radians);
double Sinu200=Math.sin(radians)*300;
int SinuInt=(int) Sinu200;
m_y=offset+SinuInt;
//z=offset-SinuInt;
double Cos=Math.cos(radians);
double Cos200=Math.cos(radians)*300;
int CosInt=(int) Cos200;
m_x=offset+CosInt;
i++; // j--;
if (i==360) i=0;
//w=offset-CosInt;
/*
//... Bounce the ball off the walls if necessary.
if (m_x < 0) { // If at or beyond left side
m_x = 0; // Place against edge and
m_velocityX = -m_velocityX; // reverse direction.
} else if (m_x > m_rightBound) { // If at or beyond right side
m_x = m_rightBound; // Place against right edge.
m_velocityX = -m_velocityX; // Reverse direction.
}
if (m_y < 0) { // if we're at top
m_y = 0;
m_velocityY = -m_velocityY;
} else if (m_y > m_bottomBound) { // if we're at bottom
m_y = m_bottomBound;
m_velocityY = -m_velocityY;
}*/
}
//============================================================== draw
public void draw(Graphics g) {
g.setColor(Color.green);
g.fillOval(m_x, m_y, DIAMETER, DIAMETER);
}
//======================================================== setPosition
public void setPosition(int x, int y) {
m_x = x;
m_y = y;
}
}
If the window is decorated, then you have to take into account the title bar height.
This is probably due to the blue strip (title bar, not sure if that's the right term) which most GUI programs have at their top.
I have a problem with my project, my project is draw lines (likes paint in windows). I want to draw more one line with mouseDragged,mousePressed and mouseReleased. But when I run to test, it showed a lot of errors, here my code
package image;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class paint extends JFrame{
private Point points[] = new Point[10000];
private Point pointends[] = new Point[10000];
private int pointCount = 0;
public paint()
{
panel paint2 = new panel();
add(paint2,BorderLayout.CENTER);
}
private class panel extends JPanel
{
public panel()
{
setBackground(Color.BLUE);
MouseHandler handler = new MouseHandler();
this.addMouseMotionListener(handler);
this.addMouseListener(handler);
}
#Override
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
for(int i = 0;i < pointCount;i++)
{
g.setColor(Color.RED);
g.drawLine(points[pointCount].x, points[pointCount].y, pointends[pointCount].x, pointends[pointCount].y);
}
}
}
private class MouseHandler extends MouseAdapter
{
#Override
public void mouseDragged(MouseEvent e)
{
// TODO Auto-generated method stub
pointends[ pointCount ] = e.getPoint();
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
super.mousePressed(e);
if(pointCount < points.length)
{
points[ pointCount ] = e.getPoint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseReleased(e);
pointends[pointCount]=e.getPoint();
repaint();
pointCount++;
}
}
}
and here's my void main
package image;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.BorderLayout;
public class test
{
public static void main(String[] args) {
paint paint1 = new paint();
/*paintP.add(paint1, BorderLayout.CENTER);
paintP.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
paintP.setSize(400,400);
paintP.setVisible(true);*/
paint1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
paint1.setSize(400,400);
paint1.setVisible(true);
}
}
In your paintComponentmethod, change the line
g.drawLine(points[pointCount].x, points[pointCount].y, pointends[pointCount].x, pointends[pointCount].y);
to this:
g.drawLine(points[i].x, points[i].y, pointends[i].x, pointends[i].y);
This will get rid of the NullPointerException and the lines will be drawn correctly once you release the mouse button. (Before, you were not only trying to paint the same line in each iteration of the loop, but also a line that did not exist yet, thus the NullPointerException.)
There's another problem: In your releaseMouse and mouseDragged methods, you are setting the end points for the line at index pointCount, but you are drawing only up to pointCount - 1. You have to increment the pointCount counter when you start drawing the lines, otherwise the new line will only be drawn when the mouse is released. One way to fix this would be to change your mouse listener to this:
private class MouseHandler extends MouseAdapter {
public void mouseDragged(MouseEvent e) {
pointends[ pointCount - 1 ] = e.getPoint(); // note the "- 1"
repaint();
}
public void mousePressed(MouseEvent e) {
if(pointCount < points.length) {
points[ pointCount ] = e.getPoint();
pointends[ pointCount ] = e.getPoint(); // add end point
pointCount++;
repaint();
}
}
public void mouseReleased(MouseEvent e) { // do nothing
}
}
You may try this:
public class myDrawLine extends JPanel {
private static final long serialVersionUID = 1L;
// These ArrayList will save all Points of Pressed and Released
ArrayList<Point> pointStart = new ArrayList<Point>();
ArrayList<Point> pointEnd = new ArrayList<Point>();
// These single Points will save the point of Dragged
Point startSinglePoint = new Point();
Point endSinglePoint = new Point();
public void paint(Graphics g) {
super.paint(g);
g.drawLine(startSinglePoint.x, startSinglePoint.y, endSinglePoint.x,
endSinglePoint.y);
for (int i = 0; i < pointStart.size() && i < pointEnd.size(); i++) {
g.drawLine(pointStart.get(i).x, pointStart.get(i).y,
pointEnd.get(i).x, pointEnd.get(i).y);
}// end for
}// end paint
{// start Block of Listeners
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
startSinglePoint = e.getPoint(); // used to the draw line when
// you drag
pointStart.add(e.getPoint()); // used to save all drew lines
}// end mousePressed
public void mouseReleased(MouseEvent e) {
pointEnd.add(e.getPoint()); // used to save all drew lines
repaint();
}// end mouseReleased
});// end addMouseListener
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
endSinglePoint = e.getPoint(); // used to draw the line when you
// drag
repaint();
}// end mouseDragged
});// end addMouseMotionListener
}// end Block of Listeners
}// end Class
and the main method:
public static void main(String[] args){
JFrame frame = new JFrame("Draw Line");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
myDrawLine draw = new myDrawLine();
frame.getContentPane().add(draw);
}//end main
So I'm creating a game in Java in which the user clicks on an image that's different from the rest. I've already got the images for the level created, but I just want to make it so that if the user clicks on a specific spot on the image, the game will react in moving on to the next image. (All of the images are placed in an array already.) The game is set up so that it opens with the first image already. Here's my code:
package Final;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.*;
import javax.swing.JFrame;
public class drawPictures extends JFrame implements MouseListener { //it implements this because I want the user to click stuff
//Now I need to declare the images that serve as my levels variables ahead of time.
protected static Image levelOne;
protected static Image levelTwo;
protected static Image levelThree;
protected static Image levelFour;
protected static Image levelFive;
protected Graphics g = this.getGraphics();
//Done declaring.
//Now to load the images
private static Image loadImage(String imgFileName) {
Image img = null;
try {
Toolkit tk = Toolkit.getDefaultToolkit();
img = tk.getImage(imgFileName);
} catch (Exception e) {
System.err.println("Image not found: "+ imgFileName);
}
return img;
} //done loading the images
static Image [] pictureArray = new Image[5]; { //This is the array that will store all of the images
//otherwise known as the "levels"
pictureArray[0] = levelOne; //each "slot" in the array is taken up by one
//of the images that serves as the level
pictureArray[1] = levelTwo;
pictureArray[2] = levelThree;
pictureArray[3] = levelFour;
pictureArray[4] = levelFive;
}
/*
* Now that the actual array that stores the levels has been created
* I need to create a method that "paints" the level,
* and moves on to the next one when the user clicks on something.
*
* I also need to create a box with dimensions 151x159
* overtop of the happy tomato in the first level.
* That will be the
*/
public drawPictures() {
super("One of These Things Doesn't Belong...");
setSize(1500, 750);
setDefaultCloseOperation(EXIT_ON_CLOSE); // Creates the "x" box.
setVisible(true); // Makes the window visible.
start();
}
public void paint(Graphics g) {
g.drawImage(pictureArray[0], 100, 100, this);
}
public static void start()
/*
* this entire method exists for the sole purpose of loading the images
* that I placed in the variables that I declared above.
* WHY IS PROGRAMMING SO DARN TEDIOUS???
*/
{
levelOne = loadImage("Level 1.jpg");
levelTwo = loadImage("Level 2.jpg");
levelThree = loadImage("Level 3.jpg");
levelFour = loadImage("Level 4.jpg");
levelFive = loadImage("Level 5.jpg");
}
#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
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
start();
new drawPictures();
}
}
You never add a mouse listener to the frame.
Having said that...
You should avoid extending from top level containers, such as JFrame
You should avoid painting onto top level containers (by overriding any of the paint methods)
You should ALWAYS call super.paintXxx (unless you have an incredibly good reason to do otherwise) as the paint methods a rather complex and perform a lot of very import work
Unless you're loading large images or downloading images from the Internet (even then), you should use the ImageIO. It has support for a larger number of images.
In your mouse clicked event, you need to determine the current image that is begin displayed. You need to determine is boundaries and determine if the mouse was clicked in it.
// Current index maintains the index of the current image...
// You should replace g.drawImage(pictureArray[0], 100, 100, this) with
// g.drawImage(pictureArray[currentIndex], 100, 100, this)
Image currentImage = pictureArray[currentIndex];
Rectangle bounds = new Rectangle(100, 100, currentImage.getWidth(this), currentImage.getHeight(this));
if (bounds.contains(arg0.getPoint()) {
// Image was clicked...
currentIndex++;
if (currentIndex >= pictureArray.length) {
currentIndex = 0;
}
repaint();
}
UPDATED with example
This is a crude example. Basically it uses a custom JPanel that paints the image. To this I add a MouseListener.
The main program uses a folder and scrolls through, displaying each (valid) image on the image panel as you click.
Mouse clicks will only occur within the context of the image panel itself.
public class ImageScoller {
public static void main(String[] args) {
new ImageScoller();
}
public ImageScoller() {
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 ImageViewPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImageViewPane extends JPanel {
private ImagePane imagePane;
private File[] fileList;
private int currentIndex = -1;
public ImageViewPane() {
fileList = new File("/path/to/some/folder/with/images").listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
imagePane = new ImagePane();
imagePane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
nextImage();
}
});
setLayout(new GridBagLayout());
add(imagePane);
nextImage();
}
public void nextImage() {
if (fileList != null && fileList.length > 0) {
currentIndex++;
if (currentIndex < 0 || currentIndex >= fileList.length) {
currentIndex = 0;
}
Image image = null;
/*
Because I don't know the contents of the folder, this is a little
more complicated then it really needs to be.
If you know the file is an image, you can simply use ImageIO.read(file)
*/
while (image == null && currentIndex < fileList.length) {
System.out.println("Loading next image: " + currentIndex);
try {
ImageInputStream iis = ImageIO.createImageInputStream(fileList[currentIndex]);
if (iis != null) {
Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
if (imageReaders != null && imageReaders.hasNext()) {
ImageReader imageReader = imageReaders.next();
imageReader.setInput(iis);
image = imageReader.read(0);
} else {
currentIndex++;
}
} else {
currentIndex++;
}
} catch (Exception e) {
e.printStackTrace();
currentIndex++;
}
}
imagePane.setImage(image);
invalidate();
repaint();
}
}
}
public class ImagePane extends JPanel {
private Image image;
private JLabel label;
public ImagePane() {
setLayout(new GridBagLayout());
label = new JLabel("No image available");
add(label);
}
public void setImage(Image value) {
if (image != value) {
image = value;
label.setVisible(image == null);
repaint();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this), image.getHeight(this));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int width = getWidth();
int height = getHeight();
int x = (width - image.getWidth(this)) / 2;
int y = (height - image.getHeight(this)) / 2;
g.drawImage(image, x, y, this);
}
}
}
}
Why do you want an invisible object above your image?
Anyway, to answer your question, create a JPanel located just as your image.
JPanel yourPanel = new JPanel() Set it's location same as your image.
Create a MouseListener on your JPanel.
yourpPanel.addMouseListener( new MouseAdapter() {
#Override
public void mousePressed( MouseEvent evnt ){
// Your code when clicked here
}
});</code>