Multiple images one by one JPanel - java

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);
}
}

Related

Why BufferedImage is not cut according to the drawn in paintComponent method rectangle(its height is calculated wrong)?

I write an application with the ability for the user to cut images.
Currently, the code below cut the image a little bit above the drawn rectangle(whose purpose is to show with which coordinates the user wants to cut the image, actually.)
public class ScreenCaptureRectangle extends JFrame implements MouseListener, MouseMotionListener {
int drag_status = 0, c1, c2, c3, c4;
public void cut() {
ImagePanel im = new ImagePanel(PicChanges.getNewImage());
JScrollPane scrollPane = new JScrollPane(im);
add(scrollPane);
setSize(500, 400);
setVisible(true);
im.addMouseListener(this);
im.addMouseMotionListener(this);
}
public void draggedScreen() throws Exception {
int w = c1 - c3;
int h = c2 - c4;
w = w * -1;
h = h * -1;
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2, w, h));
File save_path = new File("screen1.jpg");
ImageIO.write(img, "JPG", save_path);
System.out.println("Cropped image saved successfully.");
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
repaint();
c1 = arg0.getX();
c2 = arg0.getY();
}
#Override
public void mouseReleased(MouseEvent arg0) {
repaint();
if (drag_status == 1) {
c3 = arg0.getX();
c4 = arg0.getY();
try {
repaint();
draggedScreen();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Issue is under construction");
}
}
#Override
public void mouseDragged(MouseEvent arg0) {
repaint();
drag_status = 1;
c3 = arg0.getX();
c4 = arg0.getY();
}
#Override
public void mouseMoved(MouseEvent arg0) {
}
public void paint(Graphics g) {
super.paint(g);
int w = c1 - c3;
int h = c2 - c4;
w = w * -1;
h = h * -1;
if (w < 0)
w = w * -1;
g.setColor(Color.RED);
g.drawRect(c1, c2, w, h);
}
public class ImagePanel extends JPanel {
private BufferedImage imageToCut;
public ImagePanel(BufferedImage img) {
this.imageToCut = img;
Dimension size = new Dimension(imageToCut.getWidth(null), imageToCut.getHeight(null));
setPreferredSize(size);
setMaximumSize(size);
setMinimumSize(size);
setSize(size);
}
#Override
protected void paintComponent(Graphics g) {
g.drawImage(imageToCut, 0, 0, null);
}
}
As of for now when the user crops image like this:
He gets this:
My target is to get the following result:
I use mouse listeners so to get the coordinates of the drawn rectangle and then using these coordinates cut the image. Now the image is cut with incorrect height(as I see it).
I would appreciate it if anyone could tell me what can be wrong in the code?
Thanks!
Thanks to the recommendations I received, now I don't open a separate frame for a photo to cut after a user clicks on the Cut button, I just add MouseListeners to JFrame, which is more convenient and user-friendly. The photo is cut correctly, according to the coordinates from the MouseListeners:
public class ImageScreenShot extends JFrame implements MouseListener, MouseMotionListener {
int drag_status = 0, c1, c2, c3, c4;
public int getC1() {
return c1;
}
public int getC2() {
return c2;
}
public int getC3() {
return c3;
}
public int getC4() {
return c4;
}
public void cut() {
GraphicalUserInterface.getFrame().addMouseMotionListener(this);
GraphicalUserInterface.getFrame().addMouseListener(this);
}
public void draggedScreen() throws Exception {
int w = c1 - c3;
int h = c2 - c4;
w = w * -1;
h = h * -1;
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2, w, h));
File save_path = new File("screen1.jpg");
ImageIO.write(img, "JPG", save_path);
GraphicalUserInterface.getLabelIcon().setIcon(new ImageIcon(new ImageIcon(img).getImage().getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_SMOOTH)));
JOptionPane.showConfirmDialog(null, "Would you like to save your cropped Pic?");
if (JOptionPane.YES_OPTION == 0) {
/**Need to implement some code*/
} else {
/**Need to implement some code*/
}
System.out.println("Cropped image saved successfully.");
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
c1 = arg0.getXOnScreen();
c2 = arg0.getYOnScreen();
}
#Override
public void mouseReleased(MouseEvent arg0) {
if (drag_status == 1) {
c3 = arg0.getXOnScreen();
c4 = arg0.getYOnScreen();
try {
draggedScreen();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Issue is under construction");
}
}
#Override
public void mouseDragged(MouseEvent arg0) {
drag_status = 1;
c3 = arg0.getXOnScreen();
c4 = arg0.getYOnScreen();
}
#Override
public void mouseMoved(MouseEvent arg0) {
}

How to clip a BufferedImage with a shape created with Graphics2D?(Java)

Currently, I'm working on my first Java application with which a user can look through photos, cut them and rotate. I have an issue with clipping an image. What I want to achieve is the following:
User clicks on the "Cut" option
Rectangle shape called by repaint method appears on the image
By stretching the rectangle user chooses the area for cutting
When the user releases the mouse(which stops stretching the rectangle) the area that is surrounded with the rectangle is left and all the rest of the image is cut.
As of for now I have several issues:
My image is centralized on JLabel which in its turn is added to JPanel and the last is added to JFrame, so now, when I want to add a rectangle above JLable (so it is to be located on the picture) it's invisible and is added only on JPanel directly.
I drew an image with paintComponent but can't figure out how to move and stretch it and repaint the rectangle again.
Below is the part of my code which (I hope) will describe my problems more precisely:
public class GraphicalUserInterface {
static JPanel background;
static JLabel labelIcon;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GraphicalUserInterface().go();
}
});
}
public void go() {
buildGui();
}
public void buildGui() {
frame = new JFrame("PicMove");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout layout = new BorderLayout();
background = new JPanel(layout);
/**To center picture on the background**/
labelIcon = new JLabel();
labelIcon.setHorizontalAlignment(JLabel.CENTER);
labelIcon.setVerticalAlignment(JLabel.CENTER);
background.add(BorderLayout.SOUTH, bottom);
background.add(BorderLayout.PAGE_START, bar);
background.add(BorderLayout.CENTER, labelIcon);
background.add(BorderLayout.EAST, chatPanel);
frame.getContentPane().add(BorderLayout.CENTER, background);
frame.setJMenuBar(menuBar);
frame.setVisible(true);
frame.setSize(1300, 1200);}
static class CutImage extends JPanel implements Runnable {
boolean clip;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if (clip) {
BasicStroke bs = new BasicStroke(50, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10, null, 0);
g2d.setStroke(bs);
QuadCurve2D.Float qc = new QuadCurve2D.Float(20, 50, 100, 140, 460, 170);
g2d.setClip(qc);
}
BasicStroke bs = new BasicStroke(5, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10, new float[]{10}, 0);
g2d.setStroke(bs);
g2d.drawRect(260, 50, 80, 120);
}
#Override
public void run() {
CutImage cutPanel = new CutImage();
GraphicalUserInterface.background.add(cutPanel).repaint();
}
}
public class PicChanges implements Runnable{
static BufferedImage newImage;
static File [] selectedFile;
static int currentImage;
FileNameExtensionFilter filter;
JFileChooser fileChooser;
public void openPic() {
currentImage = 0;
try {
fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new java.io.File((System.getProperty("user.home"))));
filter = new FileNameExtensionFilter("*.images", "jpg", "gif", "png");
fileChooser.addChoosableFileFilter(filter);
fileChooser.setMultiSelectionEnabled(true);
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.OPEN_DIALOG) {
selectedFile = fileChooser.getSelectedFiles();
for (File image : selectedFile) {
if ((image.isFile()) && (selectedFile.length > 0)){
newImage = ImageIO.read(selectedFile[0]);
GraphicalUserInterface.labelIcon.setIcon(new ImageIcon(
new ImageIcon(newImage).getImage().getScaledInstance(
450, 620, Image.SCALE_DEFAULT)));
} else if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("No Pics Selected");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Thread.currentThread().interrupt();
openPic();
}
public static void nextPic() {
currentImage++;
try {
newImage = ImageIO.read(selectedFile[currentImage]);
} catch (IOException e) {
e.printStackTrace();
System.out.println("No pictures left");
System.out.println("next"+currentImage);
}
GraphicalUserInterface.labelIcon.setIcon(new ImageIcon(
new ImageIcon(newImage).getImage().getScaledInstance(
450, 620, Image.SCALE_DEFAULT)));
}
static class NextPicture implements Runnable{
#Override
public void run() {
Thread.currentThread().interrupt();
nextPic();
}
}
public static void previousPic () {
currentImage--;
try {
newImage = ImageIO.read(selectedFile[currentImage]);
} catch (IOException e) {
e.printStackTrace();
System.out.println("previous "+currentImage);
}
GraphicalUserInterface.labelIcon.setIcon(new ImageIcon(
new ImageIcon(newImage).getImage().getScaledInstance(
450, 620, Image.SCALE_DEFAULT)));
}
static class PreviousPic implements Runnable{
#Override
public void run() {
Thread.currentThread().interrupt();
previousPic();
}
}
}
My idea was to add MouseListeners but can I add it to the shape created with Graphics2D?
I would be greatful for the help :)
Thank you
Being in search of finding a solution to this question I've asked two more questions(maybe it will be helpful for someone) :
1) Why BufferedImage is not cut according to the drawn in paintComponent method rectangle(its height is calculated wrong)?
2) Repaint() method doesn't invoke paint() & paintComponent() methods one by one, only paintComponent () method is working
that further helped me to find out the way.
My solution is to create a separate frame for displaying copied BufferedImage in it and on this frame to draw a rectangle with the help of MouseListeners. This is the piece of code:
public class ImageScreenShot extends JFrame implements MouseListener, MouseMotionListener {
#Override
public Dimension getPreferredSize() {
return super.getPreferredSize();
}
private static Thread screenShotThread;
public static Thread getScreenShotThread() {
return screenShotThread;
}
public static void setScreenShotThread(Thread screenShot) {
ImageScreenShot.screenShotThread = screenShot;
}
private int drag_status = 0, c1, c2, c3, c4;
public int getC1() {
return c1;
}
public int getC2() {
return c2;
}
public int getC3() {
return c3;
}
public int getC4() {
return c4;
}
class AdditionalPanel extends JLabel {
private BufferedImage img;
public BufferedImage getImg() {
return img;
}
public AdditionalPanel(BufferedImage img) {
this.img = img;
setPreferredSize(new Dimension(2560, 1600));
getPreferredSize();
setLayout(null);
}
#Override
public Dimension getPreferredSize() {
return super.getPreferredSize();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
System.out.println("Additional panel class paint method was invoked");
}
}
public void cut() {
AdditionalPanel apanel = new AdditionalPanel(PicChanges.getNewImage());
JScrollPane scrollPane = new JScrollPane(apanel);
scrollPane.addMouseMotionListener(this);
scrollPane.addMouseListener(this);
getContentPane().add(scrollPane, BorderLayout.CENTER);
setPreferredSize(new Dimension(2560, 1600));
getPreferredSize();
pack();
setVisible(true);
}
private void draggedScreen() throws Exception {
int w = c1 - c3;
int h = c2 - c4;
w = w * -1;
h = h * -1;
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2, w, h));
File save_path = new File("screen1.jpg");
ImageIO.write(img, "JPG", save_path);
GraphicalUserInterface.getLabelIcon().setIcon(new ImageIcon(new ImageIcon(img).getImage().getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_SMOOTH)));
JOptionPane.showConfirmDialog(this, "Would you like to save your cropped Pic?");
System.out.println("Cropped image saved successfully.");
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
repaint();
c1 = arg0.getXOnScreen();
c2 = arg0.getYOnScreen();
System.out.println("pressed");
}
#Override
public void mouseReleased(MouseEvent arg0) {
repaint();
if (drag_status == 1) {
c3 = arg0.getXOnScreen();
c4 = arg0.getYOnScreen();
try {
repaint();
draggedScreen();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void mouseDragged(MouseEvent arg0) {
repaint();
drag_status = 1;
c3 = arg0.getXOnScreen();
c4 = arg0.getYOnScreen();
}
#Override
public void mouseMoved(MouseEvent arg0) {
}
#Override
public void paint(Graphics g) {
super.paint(g);
int w = c1 - c3;
int h = c2 - c4;
w = w * -1;
h = h * -1;
if (w < 0)
w = w * -1;
g.setColor(Color.RED);
g.drawRect(c1, c2, w, h);
System.out.println("Paint component was invoked in imagescreenshot class");
}
P.S. I know that adding JFrame is not the best solution but I'm still in search for the best way to implement it so do not hesitate to comment on my code and tell what is wrong or what is good)

Painting on a JPanel using Threads in Java

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 ?

Drawing Graphics is too slow

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.

How do i use KeyListener in java?

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);

Categories

Resources