I'm having some issues with my code.
I want to fix the background image to stay there fixed, meanwhile other components can move.
It's a simple a game where a circle avoid the squares but the istruction about the game will be added further.
Here's my code
import java.applet.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Line2D;
import java.net.URL;
import javax.swing.*;
public class Main extends Applet implements Runnable,KeyListener{
Thread r;
Image bg = null;
int a,b;
int x = 600;
int y = 400;
public void init(){
setSize(600,600);
try
{
MediaTracker tr = new MediaTracker (this);
bg = getImage
(new URL("file:D:/workspace/Game/bin/image.jpg")); //set image
tr.addImage(bg, 0);
} catch (Exception e) { System.out.println(e.toString());
}
}
public void start(){
if(r == null){
r = new Thread(this);
r.start();
}
}
public void paint(Graphics g){
g.drawImage(bg,0,0,this);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(20));
g2.draw(new Line2D.Float(0, 500, 600, 500));
g.fillRect(x, y, 20, 20);
}
public void pp(Graphics g){
}
public void run() {
Thread Th = Thread.currentThread();
while(r == Th) {
if(a < 600) {
a = a+10;
x = x-10;
repaint();
}else{
repaint();
a = 30;
x = 600;
}
try {
Thread.sleep(100);
} catch(InterruptedException 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
}
}
if you run the code, you'll see that the line and the background will be loaded a lot of time...
Related
So i have been trying to learn swing and trying to make a painting program.
The problem ive been having is that if you move your mouse to fast it doesnt fill the gaps (Run code if you dont undetstand)
Im thinking it might be where its filling up the arraylist.
So i was woundering how i can fix this, Thanks!
My code:
import javax.swing.*;
import java.util.ArrayList;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseAdapter;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Window extends JPanel implements MouseListener{
//new array list
private ArrayList<Point> dots;
static JFrame frame;
Font f;
static int Dx1=0, Dx2=0, Dy1=0, Dy2=0; //fill void dots
static int v=0;
static int posX = 250;
static int posY = 250;
static double winX=0;
static double winY=0;
public Window() {
dots = new ArrayList<Point>();
frame = new JFrame();
f = new Font("Calibri", Font.BOLD, 30);
this.setBackground(Color.white);
frame.add(this);
frame.setResizable(true);
frame.setVisible(true);
frame.setSize(500, 500);
frame.setTitle("Minigameshuehu");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
// MOVE BALL DEPENDING ON "Dragging"
this.addMouseListener(this);
this.addMouseListener(new MouseAdapter() {
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
dots.add(new Point(e.getX(), e.getY())); // adding pos to to array to make dots
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
posX = e.getX() - 3;
posY = e.getY() - 3;
repaint();
}
}
);
//End of moving ball
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(new Color(0,0,0));
g2.fillOval(posX, posY, 6, 6);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.black);
for (Point point : dots) {
g2.fillOval(point.x-3, point.y-3, 6, 6);
}
}
public static void main(String[] args) throws InterruptedException {
Window applikation = new Window();
}
#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 arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// posX=(e.getX()-25);
// posY=(e.getY()-25);
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
v=0;
// TODO Auto-generated method stub
}
}
if you move your mouse to fast it doesnt fill the gaps
That is correct, a MouseEvent is not generated for every pixel, so you can't just draw an oval for every point generated.
Instead, you need to draw a line between two points in your ArrayList.
for (int i = 0; i < dots.size() - 1; i++)
{
Point p1 = dots.get(i);
Point p2 = dots.get(i + 1);
g2.drawLine(...);
}
You will also want to change the size of the line drawn by using something like:
g2.setStroke(new BasicStroke(15, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
This will draw a line with a rounded edge so it looks like the end of an oval.
hello i really need your help if you would be kind to help me out i'll appreciate it a lot .i have recently started learning java
i am making a java program that allows my player to jump and move to the place of the mouse i think that i have succeeded to make that but it not really SPECIFIC ;
also i want to display my sprite sheet so that he would look like he is really walking but i am having a problem in this part
here is my codes :
package animation;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferStrategy;
import java.awt.*;
import javax.swing.*;
import animation.Boulle.move;
import gfx.Sprite;
import gfx.SpriteSheet;
public class deux_bulle extends JFrame implements MouseListener, MouseMotionListener {
Monp p;
int X, Y, x = 150, y = 150;
Thread t, t2, t3,t4;
int f = 0;
boolean b = false;
public Graphics g;
private int framedelay;
public static SpriteSheet sheet;
public static gfx.Sprite Sprite[] = new gfx.Sprite[3]; // my sprite sheet
// has 3 pictures
public deux_bulle() {
setSize(400, 400);
p = new Monp();
sheet = new SpriteSheet("/Untitled.png");
add(p);
p.addMouseListener(this);
p.addMouseMotionListener(this);
for (int i = 0; i < Sprite.length; i++) {
Sprite[i] = new Sprite(sheet, i + 1, 1);
}
}
class Monp extends JPanel {
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(deux_bulle.Sprite[f].getBufferedIamge(), x, y, 200, 200, null);
}
}
class moveX implements Runnable {
#Override
public void run() {
while (x < X) {
try {
x++;
if (f < 3)
//g.drawImage(deux_bulle.Sprite[f].getBufferedIamge(), x, y, 200, 200, null);
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while (x > X) {
try {
x--;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class image implements Runnable{
public void run() {
framedelay++;
if (framedelay>=3)
{f++;
if(f>=3)
{f=0;}
framedelay=0;}
}}
class moveY implements Runnable {
#Override
public void run() {
while (y < Y) {
try {
y++;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while (y > Y) {
try {
y--;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class jump implements Runnable {
#Override
public void run() {
int p = y;
while (y != Y) {
try {
y--;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while (y != p) {
try {
y++;
repaint();
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
deux_bulle db = new deux_bulle();
db.setVisible(true);
}
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
Y = 70;
t3 = new Thread(new jump());
t3.start();
}
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
X = e.getX();
Y = e.getY();
t4 = new Thread(new image());
t = new Thread(new moveX());
t2 = new Thread(new moveY());
t.start();
t2.start();
t4.start();
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
my sprite sheet class
package gfx;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpriteSheet {
private BufferedImage sheet;
public SpriteSheet(String path) {
try {
sheet= ImageIO.read(getClass().getResource(path));
} catch (IOException e) {
e.printStackTrace();
}
}
public BufferedImage getSprite(int x,int y)
{
return sheet.getSubimage(x*66-66,y*66-66,66,66);}
}
my sprite class
package gfx;
import java.awt.image.BufferedImage;
public class Sprite {
public SpriteSheet sheet;
public BufferedImage image;
public Sprite(SpriteSheet sheet,int x,int y) {
image= sheet.getSprite(x, y);
}
public BufferedImage getBufferedIamge(){
return image;
}
}
I'd like to do JButton with nice transition effect. I write a class which extend by JButton and add to it custom MouseAdapter. It almost works, but if opacity should have 0 my one BufferedImage don't vanish.
Here my all source code:
public class ImageHoverButton extends JButton {
public class MouseListener extends MouseAdapter
{
public void mouseExited(MouseEvent me)
{
new Thread(new Runnable()
{
public void run()
{
for (float i = 1f; i >= 0f; i -= .03f)
{
setOpacity(i);
try
{
Thread.sleep(10);
}
catch (Exception e)
{
}
}
}
}).start();
}
public void mouseEntered(MouseEvent me)
{
new Thread(new Runnable()
{
public void run()
{
for (float i = 0f; i <= 1f; i += .03f)
{
setOpacity(i);
try
{
Thread.sleep(10);
}
catch (Exception e)
{
}
}
}
}).start();
}
public void mousePressed(MouseEvent me)
{
new Thread(new Runnable()
{
public void run()
{
for (float i = 1f; i >= 0.6f; i -= .1f)
{
setOpacity(i);
try
{
Thread.sleep(1);
}
catch (Exception e)
{
}
}
}
}).start();
}
}
private static final long serialVersionUID = 1L;
private BufferedImage imgBottom;
private BufferedImage imgHover;
private BufferedImage imgHoverRGB;
// filter to imgInActive
float[] scales = { 1f, 1f, 1f, 0f};
float[] offsets = new float[4];
RescaleOp rop = new RescaleOp(scales, offsets, null);
/**
* Constructor for image path
* #param img
* #param x
* #param y
*/
public ImageHoverButton(String imgBottomPath, String imgHoverPath, int x, int y) {
try {
this.imgBottom = ImageIO.read(new File(imgBottomPath));
this.imgHover = ImageIO.read(new File(imgHoverPath));
imgHoverRGB = new BufferedImage(imgHover.getWidth(null),
imgHover.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics g = imgHoverRGB.getGraphics();
g.drawImage(imgHover, 0, 0, null);
} catch (IOException e) {
}
this.setBounds(x, y, imgBottom.getWidth() + 40 , imgBottom.getHeight() + 50);
addMouseListener(new MouseListener());
setOpacity(0f);
setOpaque(false);
setBorderPainted(false);
setRolloverEnabled(false);
setCursor(new Cursor(Cursor.HAND_CURSOR));
setLayout(null);
}
public void setOpacity(float opacity) {
scales[3] = opacity;
rop = new RescaleOp(scales, offsets, null);
repaint();
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(imgBottom, 50, 50, null);
g2d.drawImage(imgHoverRGB, rop, 0, 0);
}
}
Have any idea how to improve this?
I'm not so familiar with RescaleOp, and can't remember having used this before. But it seems like the results of applying it in this case are somewhat unexpected.
As an alternative, you might consider an AlphaComposite. The minimum modification that is necessary to achieve the desired effect would then be to change the line
g2d.drawImage(imgHoverRGB, rop, 0, 0);
to
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, scales[3]));
g2d.drawImage(imgHoverRGB, 0, 0, null);
However, there are several other issues with the code:
don't override paint. Instead, override paintComponent
don't call setBounds on a component (particlularly not in a constructor). The placement should be done by a layout manager
don't swallow Exceptions silently
don't load the images in the constructor of the button
implement getPreferredSize properly
don't spawn hundreds of threads due to mouse movement. (When you quickly move the mouse in and out, you'll have several threads running - some of them increasing the opacity, and some of them decreasing the opacity)
I created an example showing one possible approach: It contains an OpacityAnimator that allows a transition between two opacities, with a predefined delay in milliseconds. This animator is used to increase the opacity of the foreground image when the button is hovered with the mouse, and to decrease it when the mouse leaves the button.
(Note that this could be generalized further, and there are many possible "configuration settings" (like the transition delay) that could be exposed, but this is just intended as an example)
import java.awt.AlphaComposite;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class HoverButtonTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
createAndShowGUI();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
private static void createAndShowGUI() throws IOException
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage backgroundImage = loadImage("background.png");
BufferedImage foregroundImage = loadImage("foreground.png");
f.getContentPane().setLayout(new FlowLayout());
f.getContentPane().add(
new ImageHoverButton(backgroundImage, foregroundImage));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static BufferedImage loadImage(String path) throws IOException
{
return convertToARGB(ImageIO.read(new File(path)));
}
public static BufferedImage convertToARGB(BufferedImage image)
{
BufferedImage newImage = new BufferedImage(image.getWidth(),
image.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return newImage;
}
}
class ImageHoverButton extends JButton
{
private class MouseHoverListener extends MouseAdapter
{
#Override
public void mouseExited(MouseEvent me)
{
opacityAnimator.changeOpacity(0.0f, 250);
}
#Override
public void mouseEntered(MouseEvent me)
{
opacityAnimator.changeOpacity(1.0f, 1000);
}
#Override
public void mousePressed(MouseEvent me)
{
opacityAnimator.changeOpacity(0.5f, 50);
}
}
private class OpacityAnimator
{
private final int DELAY_MS = 10;
private final Timer timer;
private float targetOpacity;
private float currentOpacity;
private float opacityStep;
OpacityAnimator()
{
timer = new Timer(DELAY_MS, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if (currentOpacity > targetOpacity)
{
currentOpacity += opacityStep;
currentOpacity = Math.max(
currentOpacity, targetOpacity);
}
else if (currentOpacity < targetOpacity)
{
currentOpacity += opacityStep;
currentOpacity = Math.min(
currentOpacity, targetOpacity);
}
if (currentOpacity == targetOpacity)
{
timer.stop();
}
setOpacity(currentOpacity);
}
});
}
void changeOpacity(float targetOpacity, int durationMs)
{
timer.stop();
this.targetOpacity = targetOpacity;
float delta = targetOpacity - currentOpacity;
if (durationMs > 0)
{
opacityStep = (delta / durationMs) * DELAY_MS;
}
else
{
opacityStep = delta;
}
timer.start();
}
}
private final OpacityAnimator opacityAnimator;
private final BufferedImage backgroundImage;
private final BufferedImage foregroundImage;
private float opacity = 0.0f;
public ImageHoverButton(BufferedImage backgroundImage,
BufferedImage foregroundImage)
{
this.backgroundImage = backgroundImage;
this.foregroundImage = foregroundImage;
this.opacityAnimator = new OpacityAnimator();
addMouseListener(new MouseHoverListener());
setOpaque(false);
setBorderPainted(false);
setRolloverEnabled(false);
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
#Override
public Dimension getPreferredSize()
{
if (super.isPreferredSizeSet())
{
return super.getPreferredSize();
}
int w = Math
.max(backgroundImage.getWidth(), foregroundImage.getWidth());
int h = Math.max(backgroundImage.getHeight(),
foregroundImage.getHeight());
return new Dimension(w, h);
}
public void setOpacity(float opacity)
{
this.opacity = opacity;
repaint();
}
#Override
protected void paintComponent(Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D) gr;
g.drawImage(backgroundImage, 0, 0, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
opacity));
g.drawImage(foregroundImage, 0, 0, null);
}
}
Don't access Swing components from other threads. Use a swing Timer instead.
See How to use swing timers
I am new to applet and I have a problem access denied java.lang.runtimepermission exitvm.0 it shows me this error on Safari, Firefox doesn't show me anything at all, I have no idea why is so, it runs perfectly on my Eclipse but it doesn't work on web browser Any help? Thanks.
package test;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.lang.reflect.Method;
public class app extends JApplet{
URL url;
String methodName;
String f1="http://localhost/webpage/upload/suit.jpeg";
String f2="http://localhost/webpage/customers/download.jpeg";
boolean setR=false;
Image image=null;
int x=0;
int y=0;
int endX;
int endY;
int center1;
int center2;
int imageWidth;
int imageHeight;
boolean clicked=false;
int initialX=0;
int initialY=0;
public void init(){
load();
}
public void start(){
load();
}
public void load(){
//String methodName = method.getName();
// try{
Image img= getImage(getDocumentBase(), f1);
makeColorTransparent(img,Color.white);
initialX=img.getWidth(null);
initialY=img.getHeight(null);
// }//catch (InvocationTargetException ex) {
//ex.getTargetException();
// }
}
public Image makeColorTransparent
(Image im, final Color color) {
ImageFilter filter = new RGBImageFilter() {
// the color we are looking for... Alpha bits are set to opaque
public int markerRGB = color.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb) {
if ( ( rgb | 0xFF000000 ) == markerRGB ) {
// Mark the alpha bits as zero - transparent
return 0x00FFFFFF & rgb;
}
else {
// nothing to do
return rgb;
}
}
};
ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
image=Toolkit.getDefaultToolkit().createImage(ip);
drawing();
return Toolkit.getDefaultToolkit().createImage(ip);
}
public void drawing(){
Image img=null;
//File f=new File("./src/trans1/download.jpeg");
draw2();
//buff=ImageIO.read(img);
//try {
// img = ImageIO.read(new File("download.jpeg"));
// } catch (IOException e) {
// }
BufferedImage buff=new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
//buff=img;
ImageIcon pic1=null;
//try {
// pic1 = new ImageIcon(ImageIO.read(new File("./src/trans1/download.jpeg")));
System.out.println("I am working");
// } catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
//}
JFrame frame=new JFrame();
Graphics2D bGr = buff.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
buff.getGraphics().drawImage(img, 100, 100, null);
//JLabel label1=new JLabel(pic1);
frame.setSize(300,300);
// frame.add(label1);
// this.add(label1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
this.addMouseListener(new MouseL());
this.addMouseMotionListener(new MouseList());
frame.setVisible(true);
}
public void draw2(){
BufferedImage buff;
int type;
int width;
int height;
try {
// buff=new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
url = new URL (getCodeBase(), f2 );
buff=ImageIO.read(url);
Image img=ImageIO.read(url);
type=buff.getType();
width=buff.getWidth();
height=buff.getHeight();
Graphics g=buff.getGraphics();
g.drawImage(img, width, height, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void draw3(Graphics g, Image img){
g.drawImage(img, 0, 0, null);
// g.drawImage(img, img.getWidth(null), img.getWidth(null), null);
}
public void paint(Graphics g){
Image img=getImage(getDocumentBase(), f2);
draw3(g,img);
draw2();
if(image == null) return;
if(clicked==false){
imageWidth = image.getWidth(this);
imageHeight = image.getHeight(this);}
endX=x+imageWidth;
endY=y+imageHeight;
g.drawImage(image, x, y, imageWidth, imageHeight, this );
if(setR){
g.drawRect(x, y, imageWidth, imageHeight);
center1=(x+endX)/2;
center2=(y+endY)/2;
g.drawRect(center1, y, 3, 3);
g.drawRect(center1,endY, 3,3);
g.drawRect(x, center2, 3, 3);
g.drawRect(endX, center2, 3, 3);
}
}
int inX;
int inY;
int subX;
int subY;
int diffX;
int diffY;
long ratio;
boolean isSet=false;
class MouseList implements MouseMotionListener{
#Override
public void mouseDragged(MouseEvent arg0) {
setR=true;
if(isSet==true){
subX=arg0.getX();
subY=arg0.getY();
diffX=subX-inX;
diffY=subY-inY;
x=x+diffX;
y=y+diffY;
repaint();
inX=arg0.getX();
inY=arg0.getY();
//setR=false;
repaint();
}else{
if(clicked==true){
subY=arg0.getY();
diffY=subY-inY;
if(ratio==0){
ratio=1;
}
diffX=(int) (diffY/ratio);
y=y-diffY;
x=x-diffX;
imageHeight=imageHeight+diffY;
imageWidth=imageWidth+diffX;
//size of the screen
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//height of the task bar
Insets scnMax = Toolkit.getDefaultToolkit().getScreenInsets(getGraphicsConfiguration());
int taskBarSize = scnMax.bottom;
//available size of the screen
//setLocation(screenSize.width - getWidth(), screenSize.height - taskBarSize - getHeight());
if(imageHeight<0 || imageWidth<0 || imageWidth>=screenSize.width ||imageHeight>=screenSize.height){
imageHeight=initialY;
x=0;
y=0;
imageWidth=initialX;
}
setR=false;
repaint();
}
}
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class MouseL implements MouseListener{
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
if((arg0.getX()<x &&arg0.getY()<y)||(arg0.getX()<x && arg0.getY()>endY)||(arg0.getX()>endX && arg0.getY()<y)||(arg0.getX()>endX && arg0.getY()>endY)){
System.out.println(" 1 I am working");
setR=false;
repaint();
}
}
#Override
public void mouseEntered(MouseEvent arg0) {
/* if(arg0.getX()>x && arg0.getX()<endX && arg0.getY()>y && arg0.getY()<endY){
if(isSet==false){
inX=arg0.getX();
inY=arg0.getY();
isSet=true;
}
}*/
if(arg0.getX()>x && arg0.getX()<endX && arg0.getY()>y && arg0.getY()<endY){
System.out.println("Yes i am here");
Cursor c=new Cursor(Cursor.HAND_CURSOR);
setCursor(c);
}else if((arg0.getX()>=center1 && arg0.getX()<=center1+3)&&((arg0.getY()>=y && arg0.getY()<=y+3)||(arg0.getY()>=endY&& arg0.getY()<=endY+3))||(arg0.getY()>=center2 && arg0.getY()<=center2+3)&&((arg0.getX()>=x && arg0.getX()<=x+3)||(arg0.getX()>=endX && arg0.getX()<=endX+3))){
System.out.println("No i am here");
Cursor c=new Cursor(Cursor.N_RESIZE_CURSOR);
setCursor(c);
}/*else if(arg0.getX()<x || arg0.getX()>endX && arg0.getY()<y || arg0.getY()>endY){
System.out.println(" 1 I am working");
setR=false;
repaint();
}*/
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
System.out.println(x+" "+y+" "+endX+" "+endY+" "+arg0.getX()+" "+arg0.getY());
if(arg0.getX()>x && arg0.getX()<endX && arg0.getY()>y && arg0.getY()<endY){
if(isSet==false){
inX=arg0.getX();
inY=arg0.getY();
isSet=true;
}
//repaint();
System.out.println("2");
}
else if((arg0.getX()>=center1 && arg0.getX()<=center1+3)&&((arg0.getY()>=y && arg0.getY()<=y+3)||(arg0.getY()>=endY&& arg0.getY()<=endY+3))||(arg0.getY()>=center2 && arg0.getY()<=center2+3)&&((arg0.getX()>=x && arg0.getX()<=x+3)||(arg0.getX()>=endX && arg0.getX()<=endX+3))){
if((arg0.getX()>=center1 && arg0.getX()<=center1+3)&&((arg0.getY()>=y && arg0.getY()<=y+3)||(arg0.getY()>=endY&& arg0.getY()<=endY+3))){
ratio=imageHeight/imageWidth;
inY=arg0.getY();
clicked=true;
}
//repaint();
System.out.println("3");
}else if((arg0.getX()<x || arg0.getY()<y)||(arg0.getX()<x || arg0.getY()>endY)||(arg0.getX()>endX || arg0.getY()<y)||(arg0.getX()>endX || arg0.getY()>endY)){
System.out.println(" 1 I am working");
setR=false;
repaint();
System.out.println("4");
}
//repaint();
/*else if((arg0.getX()<x || arg0.getX()>endX)|| (arg0.getY()<y || arg0.getY()>endY)){
System.out.println(" 1 I am working");
setR=false;
repaint();
}*/
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
isSet=false;
// clicked=false;
// setR=false;
// repaint();
}
}
}
The problem is this line:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
When setting EXIT_ON_CLOSE we are effectively trying to get the JVM to shut down itself as soon as the frame is closed. An applet security manager (even when the applet is trusted) will prevent that.
It should be:
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
That will fix the immediate problem, but a better solution is to scrap the applet and put all the necessary controls in a frame. After that is accomplished, launch the frame using Java Web Start.
I'm trying to create a program that draws up playing cards. The chart is drawn each time an object of class is created. As it stands now, I have five objects of the class, but only one card is being painted. I wonder of course why?
I also wonder how I could improve my movement of the cards.
Cards.java
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Cards extends JPanel implements MouseMotionListener, MouseListener{
Random rnd = new Random();
int X, posX;
int Y, posY;
int line;
int col;
String card;
boolean faceUp;
boolean pressOut;
static int numOfCards;
String [][] icons = {
{"img/c1.gif", "img/d1.gif", "img/h1.gif" , "img/s1.gif"},
{"img/c2.gif", "img/d2.gif", "img/h2.gif" , "img/s2.gif"},
{"img/c3.gif", "img/d3.gif", "img/h3.gif" , "img/s3.gif"},
{"img/c4.gif", "img/d4.gif", "img/h4.gif" , "img/s4.gif"},
{"img/c5.gif", "img/d5.gif", "img/h5.gif" , "img/s5.gif"},
{"img/c6.gif", "img/d6.gif", "img/h6.gif" , "img/s6.gif"},
{"img/c7.gif", "img/d7.gif", "img/h7.gif" , "img/s7.gif"},
{"img/c8.gif", "img/d8.gif", "img/h8.gif" , "img/s8.gif"},
{"img/c9.gif", "img/d9.gif", "img/h9.gif" , "img/s9.gif"},
{"img/c10.gif", "img/d10.gif", "img/h10.gif" , "img/s10.gif"},
{"img/cj.gif", "img/dj.gif", "img/hj.gif" , "img/sj.gif"},
{"img/cq.gif", "img/dq.gif", "img/hq.gif" , "img/sq.gif"},
{"img/ck.gif", "img/dk.gif", "img/hk.gif" , "img/sk.gif"}
};
public Cards() {
numOfCards++;
addMouseListener(this);
addMouseMotionListener(this);
this.X = rnd.nextInt(300);
this.Y = rnd.nextInt(300);
this.line = rnd.nextInt(13);
this.col = rnd.nextInt(4);
this.card = icons[line][col];
this.faceUp = rnd.nextBoolean();
this.pressOut = false;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(faceUp == true){
ImageIcon icon = new ImageIcon(this.getClass().getResource(card));
g.drawImage(icon.getImage(), this.X, this.Y, this);
} else {
ImageIcon icon = new ImageIcon(this.getClass().getResource("/img/b1fv.gif"));
g.drawImage(icon.getImage(), this.X, this.Y, this);
}
}
#Override
public void mouseClicked(MouseEvent e) {
if(this.faceUp == false){
this.faceUp = true;
this.repaint();
} else {
this.faceUp = false;
this.repaint();
}
}
#Override
public void mousePressed(MouseEvent e) {
this.posX = this.getX() - e.getX();
this.posY = this.getY() - e.getY();
if (this.card != null) {
updateLocation(e);
}else{
pressOut = true;
}
}
#Override
public void mouseReleased(MouseEvent e) {
updateLocation(e);
}
#Override
public void mouseDragged(MouseEvent e) {
if (!pressOut) {
updateLocation(e);
}
}
public void updateLocation(MouseEvent e){
this.setLocation(this.posX + e.getX(), this.posY + e.getY());
repaint();
}
#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 mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
Table.java
import java.awt.Color;
import java.awt.Frame;
import javax.swing.JFrame;
public class Table{
public static void main(String[] args) {
JFrame frame = new JFrame("Cards");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseListener(null);
frame.addMouseMotionListener(null);
frame.setBackground(Color.GREEN);
frame.setSize(400,600);
Cards c1 = new Cards();
Cards c2 = new Cards();
Cards c3 = new Cards();
Cards c4 = new Cards();
Cards c5 = new Cards();
System.out.println(c1.card);
System.out.println(c2.card);
System.out.println(c3.card);
System.out.println(c4.card);
System.out.println(c5.card);
System.out.println(c5.numOfCards);
frame.add(c1);
frame.add(c2);
frame.add(c3);
frame.add(c4);
frame.add(c5);
frame.setVisible(true);
}
}
The default layout for a JFrame is BorderLayout.
Try using GridLayout, for example
frame.setLayout(new GridLayout(0, 3));
Don't load the image in the paintComponent method, this method should exit as fast as possible, instead, pre-load the images...
public class Cards extends JPanel implements MouseMotionListener, MouseListener{
//...
private Image face;
private Image back;
//...
public Cards() {
//...
face = new ImageIcon(this.getClass().getResource(card)).getImage();
back = ImageIcon icon = new ImageIcon(this.getClass().getResource("/img/b1fv.gif")).getImage();
//...
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(faceUp){
g.drawImage(face, this.X, this.Y, this);
} else {
g.drawImage(back , this.X, this.Y, this);
}
}
You should also be overriding the getPreferredSize method of the JPanel, this works with the layout manager API to allow it to make decisions about how best to layout component...
public Dimension getPreferredSize() {
return face == null ? super.getPreferredSize() : new Dimension(face.getWidth(this), face.getHeight(this));
}
This will now allow you to use JFrame#pack instead of JFrame#setSize