I want to repaint() my JPanel using a Thread in Java .
I have two different classes which i am using .
The class with JFrame (Main class) and another class wich extends a JPanel.
Here are the classes :
This one is The Frame it selve
public class Frame {
static int width = 1280 ;
static int height = 720 ;
public Frame(){
InGamePanel inGame = new InGamePanel();
JFrame menu = new JFrame();
Menu.setSize(width, height);
Menu.setTitle("STICK FACTORY");
Menu.setResizable(false);
Menu.add(InGame);
Menu.setVisible(true);
}
public static void main(String[] args) {
new Frame();
}
}
And this one is the on with the Thread , which is not running :
import javax.swing.JPanel;
import BackGround.BackGround;
import Enums.Player;
import Enums.Stick;
public class InGamePanel extends JPanel implements KeyListener{
//Thread for FPS
FPS reloader = new FPS();
//Background
BackGround gameBG = new BackGround(Frame.width , Frame.height);
//Player
int xPosition_Player = 400;
int yPosition_Player = 180;
Player jeff = new Player();
//Stick
int xPosition_Stick = 600 ;
int yPosition_Stick = 180 ;
Stick fluffy = new Stick();
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
gameBG.drawBackGround(g);
jeff.drawPlayer(g, XPosition_Player, YPosition_Player);
fluffy.drawStick(g, XPosition_Stick, YPosition_Stick);
reloader.run();
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar() == 's'){
yPosition_Player+= 40 ;
jeff.direction = 's';
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
class FPS implements Runnable{
int fps = 60 ;
#Override
public void run() {
try {
Thread.sleep(1000 / fps);
repaint();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
So how can I get the Thread run and repaint my Program ?
Related
I am trying to load images to JPanel from a directory (which contains only images) one by one. I want to crop the image one by one using mouse events. I wrote program for loading one image by giving it's path to JPanael and then cropping it using mouse. But i don't know how to extend program for multiple images one by one and saving the cropped ones in a different directory. I tried swing timer also but i could not figure how to use it. Can any please help me?
Here is my code for single image.
public class MainActivity extends JFrame implements MouseListener,MouseMotionListener{
int drag_status=0,c1,c2,c3,c4;
static String[] pathArray = new String[1000];
public static void main(String args[]) {
new MainActivity().start();
String s = "G:\\my pic";
File f = new File(s);
String str;
System.out.println(true);
//just to put all the pictures in list
File[] fa = f.listFiles();
for (int i=0; i< fa.length; i++) {
String path = fa[i].toString();
str = path.replace("\\", "\\\\");
pathArray [i] = str;
System.out.println(pathArray[2]); //gives all the paths in ImagePanel path format
}
}
public void start() {
ImageJPanel imageJPanel=new ImageJPanel(pathArray[1]);
add(imageJPanel);
setSize(200,200);
setVisible(true);
addMouseListener(this);
addMouseMotionListener( this );
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
c1=arg0.getX();
c2=arg0.getY();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
if(drag_status==1) {
c3=arg0.getX();
c4=arg0.getY();
try {
draggedScreen();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public void draggedScreen()throws Exception {
int width = c1 - c3;
int height = c2 - c4;
width = width * -1;
height = height * -1;
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2,width,height));
File save_path=new File("C:\\Users\\apurvgandhwani\\Desktop\\cropped");
ImageIO.write(img, "JPG", save_path);
System.out.println("Saved to folder");
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
repaint();
drag_status=1;
c3=arg0.getX();
c4=arg0.getY();
}
public void paint(Graphics g) {
super.paint(g);
int width = c1 - c3;
int height = c2 - c4;
width = width * -1;
height = height * -1;
if(width<0) width = width * -1;
g.drawRect(c1, c2, width, height); }
}
And ImageJPanel class
public class ImageJPanel extends JPanel{
private static final long serialVersionUID = 1L;
private Image image;
int x = 0;
public ImageJPanel(String image){
this(new ImageIcon(image).getImage());
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
x += 110;
if (x >= 1000) {
x = 1000;
((Timer)e.getSource()).stop();
}
repaint();
}
});
timer.start();
}
public ImageJPanel(Image image){
this.image = image;
Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g){
g.drawImage(image, 0, 0, null);
}
}
So, I have this project, and you can draw images in it. I wanted people to be able to draw on it, but at first it was too slow when I was using repaint() So i used the repaint(Rectangle r) tool. It's better, but still not the speed i was looking for.
Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DrawingPad extends JPanel implements MouseListener,MouseMotionListener,ListSelectionListener{
public Color[][] picture = new Color[601][601];
public Color selected;
public String action;
public Maker m;
private static final long serialVersionUID = 1L;
public DrawingPad(Maker m){
this.m = m;
this.setPreferredSize(new Dimension(600,600));
this.setVisible(true);
for (int x = 1;x<=600;x++){
for (int y = 1; y<=600;y++){
picture[x][y]=Color.WHITE;
}
}
}
public void addColor(int x, int y){
try{
picture[x][y]=selected;
repaint(new Rectangle(x,y,x,y));
}catch (Exception e){
}
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.clearRect(0, 0, 600, 600);
for (int x = 1;x<=600;x++){
for (int y = 1; y<=600;y++){
g.setColor(picture[x][y]);
g.drawLine(x, y, x, y);
}
}
}
#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
}
#Override
public void mouseDragged(MouseEvent e) {
for (int x = -1;x<=1;x++){
for (int y = -1;y<=1;y++){
this.addColor(e.getX()+x, e.getY()+y);
}
}
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getSource()==m.seeit){
selected = m.colors[m.seeit.getSelectedIndex()];
}else{
action=(String) m.actions.getSelectedValue();
}
}
}
You might want to look into drawing that which will not be changed into a BufferedImage, and then displaying that BufferedImage in the paintComponent method as a background image.
For example, please have a look at this link and also this one.
Let me start off by saying I know I've violated some basic Java principles in this messy code, but I'm desperately trying to finish a program by Tuesday for a social science experiment, and I don't know Java, so I'm basically just fumbling through it for now.
With that disclaimer out of the way, I have a separate program working where a circle is moving around the screen and the user must click on it. It works fine when its in its own separate class file, but when I add the code to my main program, it's no longer working. I don't even really understand why repaint() calls my paint() function — as far as I'm concerned, it's magic, but I've noticed that repaint() calls paint() in my test program, but not in the more complicated actual program, and I assume that's why the circle is no longer painting on my program.
Entire code is below:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;
public class Reflexology1 extends JFrame{
private static final long serialVersionUID = -1295261024563143679L;
private Ellipse2D ball = new Ellipse2D.Double(0, 0, 25, 25);
private Timer moveBallTimer;
int _ballXpos, _ballYpos;
JButton button1, button2;
JButton movingButton;
JTextArea textArea1;
int buttonAClicked, buttonDClicked;
private long _openTime = 0;
private long _closeTime = 0;
JPanel thePanel = new JPanel();
JPanel thePlacebo = new JPanel();
final JFrame frame = new JFrame("Reflexology");
final JFrame frame2 = new JFrame("The Test");
JLabel label1 = new JLabel("Press X and then click the moving dot as fast as you can.");
public static void main(String[] args){
new Reflexology1();
}
public Reflexology1(){
frame.setSize(600, 475);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Reflexology 1.0");
frame.setResizable(false);
frame2.setSize(600, 475);
frame2.setLocationRelativeTo(null);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setTitle("Reflexology 1.0");
frame2.setResizable(false);
button1 = new JButton("Accept");
button2 = new JButton("Decline");
//movingButton = new JButton("Click Me");
ListenForAcceptButton lForAButton = new ListenForAcceptButton();
ListenForDeclineButton lForDButton = new ListenForDeclineButton();
button1.addActionListener(lForAButton);
button2.addActionListener(lForDButton);
//movingButton.addActionListener(lForMButton);
JTextArea textArea1 = new JTextArea(24, 50);
textArea1.setText("Tracking Events\n");
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
textArea1.setSize(15, 50);
textArea1.setEditable(false);
FileReader reader = null;
try {
reader = new FileReader("EULA.txt");
textArea1.read(reader, "EULA.txt");
} catch (IOException exception) {
System.err.println("Problem loading file");
exception.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
AdjustmentListener listener = new MyAdjustmentListener();
thePanel.add(scrollBar1);
thePanel.add(button1);
thePanel.add(button2);
frame.add(thePanel);
ListenForMouse lForMouse = new ListenForMouse();
thePlacebo.addMouseListener(lForMouse);
thePlacebo.add(label1);
frame2.add(thePlacebo);
ListenForWindow lForWindow = new ListenForWindow();
frame.addWindowListener(lForWindow);
frame2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
if(e.getKeyChar() == 'X' || e.getKeyChar() == 'x') {moveBallTimer.start();}
}
});
frame.setVisible(true);
moveBallTimer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveBall();
System.out.println("Timer started!");
repaint();
}
});
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(frame2.isVisible()){ moveBallTimer.start(); }
}
});
}
private class ListenForAcceptButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
Calendar ClCDateTime = Calendar.getInstance();
System.out.println(ClCDateTime.getTimeInMillis() - _openTime);
_closeTime = ClCDateTime.getTimeInMillis() - _openTime;
//frame.getContentPane().remove(thePanel);
//thePlacebo.addKeyListener(lForKeys);
//frame.getContentPane().add(thePlacebo);
//frame.repaint();
//moveBallTimer.start();
frame.setVisible(false);
frame2.setVisible(true);
frame2.revalidate();
frame2.repaint();
}
}
}
private class ListenForDeclineButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button2){
JOptionPane.showMessageDialog(Reflexology1.this, "You've declined the license agreement. DO NOT RESTART the program. Please go inform a researcher that you have declined the agreement.", "WARNING", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
}
private class ListenForWindow implements WindowListener{
public void windowActivated(WindowEvent e) {
//textArea1.append("Window is active");
}
// if this.dispose() is called, this is called:
public void windowClosed(WindowEvent arg0) {
}
// When a window is closed from a menu, this is called:
public void windowClosing(WindowEvent arg0) {
}
// Called when the window is no longer the active window:
public void windowDeactivated(WindowEvent arg0) {
//textArea1.append("Window is NOT active");
}
// Window gone from minimized to normal state
public void windowDeiconified(WindowEvent arg0) {
//textArea1.append("Window is in normal state");
}
// Window has been minimized
public void windowIconified(WindowEvent arg0) {
//textArea1.append("Window is minimized");
}
// Called when the Window is originally created
public void windowOpened(WindowEvent arg0) {
//textArea1.append("Let there be Window!");
Calendar OlCDateTime = Calendar.getInstance();
_openTime = OlCDateTime.getTimeInMillis();
//System.out.println(_openTime);
}
}
private class MyAdjustmentListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent arg0) {
AdjustmentEvent scrollBar1;
//System.out.println(scrollBar1.getValue()));
}
}
public void paint(Graphics g) {
//super.paint(g);
frame2.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
System.out.println("Calling fill()");
}
protected void moveBall() {
//System.out.println("I'm in the moveBall() function!");
int width = getWidth();
int height = getHeight();
int min, max, randomX, randomY;
min =200;
max = -200;
randomX = min + (int)(Math.random() * ((max - min)+1));
randomY = min + (int)(Math.random() * ((max - min)+1));
//System.out.println(randomX + ", " + randomY);
Rectangle ballBounds = ball.getBounds();
//System.out.println(ballBounds.x + ", " + ballBounds.y);
if (ballBounds.x + randomX < 0) {
randomX = 200;
} else if (ballBounds.x + ballBounds.width + randomX > width) {
randomX = -200;
}
if (ballBounds.y + randomY < 0) {
randomY = 200;
} else if (ballBounds.y + ballBounds.height + randomY > height) {
randomY = -200;
}
ballBounds.x += randomX;
ballBounds.y += randomY;
_ballXpos = ballBounds.x;
_ballYpos = ballBounds.y;
ball.setFrame(ballBounds);
}
public void start() {
moveBallTimer.start();
}
public void stop() {
moveBallTimer.stop();
}
private class ListenForMouse implements MouseListener{
// Called when the mouse is clicked
public void mouseClicked(MouseEvent e) {
//System.out.println("Mouse Panel pos: " + e.getX() + " " + e.getY() + "\n");
if (e.getX() >=_ballXpos && e.getX() <= _ballXpos + 25 && e.getY() <=_ballYpos && e.getY() >= _ballYpos - 25 ) {
System.out.println("TRUE");
}
System.out.println("{e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos + " | " + "{e.getY(): " + e.getY() + " / " + "_ballYpos: " + _ballYpos);
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
// System.out.println("e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos);
// Mouse over
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
// Mouse left the mouseover area:
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
Could anyone tell me what I need to do to get repaint() to call the paint() method in the above program? I'm assuming the multiple frames is causing the problem, but that's just a guess. Thanks.
You should not paint directly on JFrame. JPanel or extension of JComponent should be used. For painting override paintComponent() rather than paint(). Don't forget to call super.paintComponent(g);.
Also, keep in mind that repaint() only schedules component update, it does not trigger immediate paint().
For more details see Performing Custom Painting and Painting in AWT and Swing.
For example you can apply the following changes. TestPanel will paint the ball.
class TestPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
}
}
Then, update thePlacebo panel:
JPanel thePlacebo = new TestPanel();
Add repaint in moveBall():
thePlacebo.repaint();
Here is an example based on original code:
package so;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.Random;
import javax.swing.*;
public class TestBall {
private static void createAndShowUI() {
final TestPanel panel = new TestPanel();
panel.validate();
JFrame frame = new JFrame("TestBall");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 300));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ActionListener timerAction = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
panel.moveBall();
}
};
Timer timer = new Timer(1000, timerAction);
timer.setRepeats(true);
timer.start();
}
static class TestPanel extends JPanel {
public static int BALL_SIZE = 25;
private Ellipse2D ball = new Ellipse2D.Double(0, 0, BALL_SIZE,
BALL_SIZE);
Random rand = new Random();
public TestPanel() {
this.addMouseListener(new MouseAdapter() {
// Called when the mouse is clicked
public void mouseClicked(MouseEvent e) {
if (ball.contains(e.getPoint())) {
System.out.println("hit the ball");
}
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fill(ball);
}
public void moveBall() {
Rectangle ballBounds = ball.getBounds();
ball.setFrame(ballBounds);
ballBounds.x = rand.nextInt(getWidth() - BALL_SIZE + 1) + 1;
ballBounds.y = rand.nextInt(getHeight() - BALL_SIZE + 1) + 1;
ball.setFrame(ballBounds);
repaint();
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
I am trying to create a panel with pictures that are changed with the mouse.
I have 10 images (0.png to 9.png). My problem is, I want to move image and I am currently viewing the second picture. I used the JScrollPane to scroll back to the first image, but only the first image is moving. How can I refresh my panel and be able to move all images?
This is my code:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
class MapFrame extends JPanel {
/**
*
*/
private static final long serialVersionUID = (long) 1.0;
private static Image image;
private static JLabel label = new JLabel();
private static int ind =0;
private static JFrame frame;
private static String str;
//-----------------------------------------------------------------
public MapFrame(){ }
//-----------------------------------------------------------------
public MapFrame(String pathe) {
super(new BorderLayout());
image = new ImageIcon(getClass().getResource(pathe)).getImage();
label = new JLabel(new ImageIcon(image));
JScrollPane scroll = new JScrollPane(label,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
HandLcalss hand = new HandLcalss(label);
JViewport v = scroll.getViewport();
v.addMouseListener(hand);
v.addMouseMotionListener(hand);
v.addMouseWheelListener(hand);
}
//-----------------------------------------------------------------
public static void ShowGUI(String pathe) {
frame = new JFrame("Bladi_map");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MapFrame(pathe));
frame.setSize(500,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//-----------------------------------------------------------------
public static void ChangImage(String pathe){
frame.getContentPane().add(new MapFrame(pathe));
label.revalidate();
frame.setVisible(true);
}
//-----------------------------------------------------------------
class HandLcalss implements MouseListener,MouseMotionListener,MouseWheelListener{
private static final int DELAY = 10;
private Cursor hc = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
private Timer scroller;
private JComponent label;
private Point startPt = new Point();
private Point move = new Point();
//-----------------------------------------------------------------
public HandLcalss(JComponent comp) {
this.label = comp;
comp.getCursor();
this.scroller = new Timer(DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
}
//-----------------------------------------------------------------
#Override public void mouseDragged(MouseEvent e) {
JViewport vport = (JViewport)e.getSource();
Point pt = e.getPoint();
int dx = startPt.x - pt.x;
int dy = startPt.y - pt.y;
Point vp = vport.getViewPosition();
vp.translate(dx, dy);
label.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
startPt.setLocation(pt);
}
#Override
public void mousePressed(MouseEvent e) {
((JComponent)e.getSource()).setCursor(hc);
startPt.setLocation(e.getPoint());
move.setLocation(0, 0);
scroller.stop();
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation();
if (notches < 0) {
ind++;
if(ind <0){ind=0;}
if(ind<=9){
str="/resources/"+ind+".png";
ChangImage(str);
System.out.println("indink"+str);
}
} else {
ind--;
if(ind >9){ind=8;}
if(ind>=0){
str="/resources/"+ind+".png";
ChangImage(str);
System.out.println("ind"+ind);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(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 mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
//-----------------------------------------------------------------
}
This is the main class:
public class main {
public static void main(String[] args) {
MapFrame.ShowGUI("/resources/0.png");
}
}
You have 2 problems in your code:
The first:
public static void ChangImage(String pathe){
frame.getContentPane().add(new MapFrame(pathe));
label.revalidate();
frame.setVisible(true);
}
When you change image (invoked on mouse wheel event) you simply add new panel (MapFrame) with image to existing container: (Container pane = frame.getContentPane()). The old ones are still there and are overlapping with the new panel. The above method should be:
public static void ChangImage(String pathe) {
frame.getContentPane().removeAll();
frame.getContentPane().add(new MapFrame(pathe));
label.revalidate();
frame.setVisible(true);
}
The second thing:
Why complicate? (also there is an error on 0 value of ind):
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
int notches = e.getWheelRotation() * -1;
ind += notches;
if(ind < 0) {
ind = 0;
}
else if(ind > 9) {
ind = 9;
}
str = "/resources/" + ind + ".png";
ChangImage(str);
}
And the last thing:
If you are implementing all mouse interfaces - you can extend MouseAdapter. Now you needn't override methods you don't want.
How do I use KeyListener on this code to move up and down? Ii know how to use KeyListener but I don't know where it put it on this code.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class ControlPanel extends JPanel implements Runnable,ActionListener,KeyListener,MouseListener{
private MainPanel main;
private final static int maxWidth = 800, maxHeight = 600; //width & height of JPanel
private boolean running; //keeps track of state of the program
private Thread thread;
private Graphics2D graphics;
private Image image; //used for double buffering
private BufferedImage bgImage;
private String s = "";
Font f = new Font("Times New Roman",Font.PLAIN,50);
Timer t = new Timer(2000,this);
private int typed = 0;
private int x = 50,y = 500;
public ControlPanel(MainPanel main) {
this.setDoubleBuffered(false); //we'll use our own double buffering method
this.setBackground(Color.black);
this.setPreferredSize(new Dimension(maxWidth, maxHeight));
this.setFocusable(true);
this.requestFocus();
this.main = main;
addKeyListener(this);
addMouseListener(this);
t.start();
}
public static void main(String[] args) {
new MainPanel();
}
public void addNotify() {
super.addNotify();
startGame();
}
public void stopGame() {
running = false;
}
//Creates a thread and starts it
public void startGame() {
if (thread == null || !running) {
thread = new Thread(this);
}
thread.start(); //calls run()
}
public void run() {
running = true;
init();
while (running) {
createImage(); //creates image for double buffering
///////////////USE THESE 2 METHODS////////////////////
update(); //use this to change coordinates, update values, etc
draw(); //use this to draw to the screen
//////////////////////////////////////////////////////
drawImage(); //draws on the JPanel
}
System.exit(0);
}
//Use this to create or initialize any variables or objects you have
public void init() {
}
public void initGame(){
}
//Use this to update anything you need to update
public void update() {
}
//Use this to draw anything you need to draw
public void draw() {
graphics.setColor(Color.WHITE);
graphics.fillRect(250, 450, 300,100);
graphics.setColor(Color.WHITE);
graphics.fillRect(250, 320, 300,100);
graphics.setColor(Color.GREEN);
graphics.setFont(f);
graphics.drawString(s, x, y);
typed = 0;
graphics.setFont(f);
graphics.setColor(Color.blue);
graphics.drawString("HANGMAN", 270,75);
graphics.setFont(f);
graphics.setColor(Color.blue);
graphics.drawString("PLAY", 330, 390);
graphics.setFont(f);
graphics.setColor(Color.blue);
graphics.drawString("QUIT", 330, 520);
graphics.setColor(Color.red);
graphics.drawRect(248, 318, 304,104);
}
//creates an image for double buffering
public void createImage() {
if (image == null) {
image = createImage(maxWidth, maxHeight);
if (image == null) {
System.out.println("Cannot create buffer");
return;
}
else
graphics = (Graphics2D)image.getGraphics(); //get graphics object from Image
}
if (bgImage == null) {
graphics.setColor(Color.black);
graphics.fillRect(0, 0, maxWidth, maxHeight);
//System.out.println("No background image");
}
else {
//draws a background image on the Image
graphics.drawImage(bgImage, 0, 0, null);
}
}
//outputs everything to the JPanel
public void drawImage() {
Graphics g;
try {
g = this.getGraphics(); //a new image is created for each frame, this gets the graphics for that image so we can draw on it
if (g != null && image != null) {
g.drawImage(image, 0, 0, null);
g.dispose(); //not associated with swing, so we have to free memory ourselves (not done by the JVM)
}
image = null;
}catch(Exception e) {System.out.println("Graphics objects error");}
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
typed = 1;
s+=Character.toString(e.getKeyChar());
s+=" ";
System.out.println(s);
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getPoint());
}
#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
}
}
KeyListener isn‘t designated for listening of keyboard events for Swing JComponents, use KeyBindings instead, output to the Swing GUI should be from Swing Action
You have added key listener by calling this
addKeyListener(this);