GetGraphics() problem
hello guys,
I have some problem in Swing pl help,
What i have to do is draw a image on the JFrame so this is what i did
1. created a class
2. created the JFrame
3. got the image using getImage()
4. tried drawing it using drawImage()
but the image is not drawn
Here is the code
import java.awt.*;
import javax.swing.*;
class canvas12
JFrame jf;
Image img;
Toolkit tk;
Container cp;
canvas12()
jf= new JFrame("hello");
tk = Toolkit.getDefaultToolkit();
img = tk.getImage(getClass().getResource("puyo_blue.png"));
jf.setVisible(true);
jf.repaint();
public void repaint()
Graphics g;
g = jf.getGraphics();
System.out.println(g);
g.drawImage(img,12,34,null);
public static void main(String args[])
canvas12 c=new canvas12();
}now the above class is not totaly correct i know i should have used the paintComponent() method must have subclassed JComponent, the class name is also unappropriate
but i want to do it using repaint() i know there is some error in my code because of which i 'm having problem drawing the image(one should not be using paint() when wortking with Swing)
what i lack is the concept behind the drawing of image i read books but i'm still not clear with the concepts pl help me understand the concept
Pl if you could correct my code and help me understand the point where i'm lacking i would be very gratefull
this is the below code of some other person i downloaded
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
// Referenced classes of package Puyo:
// PuyoLogic, Ball
public class PuyoWindow
implements KeyListener
JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;
PuyoLogic puyoLogic;
public Image puyoImages[];
private Image doubleBuffer;
public static final int boardWidth = 6;
public static final int boardHeight = 12;
public static final int ballWidth = 32;
public static final int ballHeight = 32;
public static final int canvasWidth = 192;
public static final int canvasHeight = 384;
public PuyoWindow()
puyoLogic = null;
Toolkit toolkit = Toolkit.getDefaultToolkit();
puyoImages = new Image[4];
puyoImages[0] = toolkit.getImage(getClass().getResource("images/puyo_red.png"));
puyoImages[1] = toolkit.getImage(getClass().getResource("images/puyo_green.png"));
puyoImages[2] = toolkit.getImage(getClass().getResource("images/puyo_blue.png"));
puyoImages[3] = toolkit.getImage(getClass().getResource("images/puyo_yellow.png"));
mainFrame = new JFrame("PuyoWindow");
Container cp = mainFrame.getContentPane();
labelScore = new JLabel("Score:");
cp.add(labelScore, "North");
paintCanvas = new Canvas();
paintCanvas.addKeyListener(this);
paintCanvas.setSize(192, 384);
cp.add(paintCanvas, "Center");
JPanel panelButtom = new JPanel();
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp = new JLabel("Start: S; Pause: P/SPACE", 0);
panelButtom.add(labelHelp, "North");
labelHelp = new JLabel("Speed: PgUp, PgDn", 0);
panelButtom.add(labelHelp, "Center");
labelHelp = new JLabel("Move/Rotate: Arrow keys", 0);
panelButtom.add(labelHelp, "South");
cp.add(panelButtom, "South");
mainFrame.addKeyListener(this);
//mainFrame.pack();
mainFrame.setResizable(false);
//mainFrame.setTitle("Puyo");
mainFrame.setDefaultCloseOperation(3);
mainFrame.setVisible(true);
beginPuyo();
public void keyPressed(KeyEvent e)
int keyCode = e.getKeyCode();
if(puyoLogic.running)
switch(keyCode)
case 38: // '&'
puyoLogic.rotateCW();
break;
case 40: // '('
puyoLogic.rotateCCW();
break;
case 37: // '%'
puyoLogic.moveLeft();
break;
case 39: // '\''
puyoLogic.moveRight();
break;
case 33: // '!'
puyoLogic.speedUp();
break;
case 34: // '"'
puyoLogic.speedDown();
break;
case 32: // ' '
case 80: // 'P'
puyoLogic.changePauseState();
break;
if(keyCode == 83 || keyCode == 10)
puyoLogic.running = true;
beginPuyo();
public void keyReleased(KeyEvent keyevent)
public void keyTyped(KeyEvent keyevent)
public void repaint()
Graphics g = paintCanvas.getGraphics();
if(doubleBuffer != null)
Graphics g2 = doubleBuffer.getGraphics();
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, 192, 384);
drawBalls(g2);
g2.dispose();
g.drawImage(doubleBuffer, 0, 0, null);
} else
doubleBuffer = paintCanvas.createImage(192, 384);
updateScore();
private int color2ImageIndex(int color)
return color - 1;
private void drawBalls(Graphics g)
label0:
label1:
if(puyoLogic == null)
break label0;
int i = 0;
do
PuyoLogic _tmp = puyoLogic;
if(i >= 2)
break label1;
g.drawImage(puyoImages[color2ImageIndex(puyoLogic.droppingBalls.color)], (puyoLogic.droppingBalls[i].x - 1) * 32, (12 - puyoLogic.droppingBalls[i].y) * 32, null);
i++;
} while(true);
for(int i = 1; i < 7; i++)
for(int j = 1; j < 13; j++)
PuyoLogic _tmp1 = puyoLogic;
if(puyoLogic.accumBalls[i][j] != 0)
g.drawImage(puyoImages[color2ImageIndex(puyoLogic.accumBalls[i][j])], (i - 1) * 32, (12 - j) * 32, null);
private void updateScore()
if(puyoLogic != null)
String s = (new StringBuilder()).append("Score: ").append(puyoLogic.score).toString();
labelScore.setText(s);
private void beginPuyo()
if(puyoLogic == null || !puyoLogic.running)
puyoLogic = new PuyoLogic(this);
(new Thread(puyoLogic)).start();
public static void main(String args[])
PuyoWindow puyoWin = new PuyoWindow();
i know he has mixed Swing with AWT now what i want to know is that what wrong do i do that i do not get my images drawn & the above code gets the images drawn
Similar Messages
-
Hmm..repaint, refresh jpanel?
Hi,
I had a problem and i dun have codes to show. All I can say are just descriptions.
Well, here it goes. I had use jPanel to display Unicode characters. It is able to display but when another frame, say msn, overlaps the jPanel, partial of the character drawn on it will disappear.
This is dependent on the amount of overlapping of that particular frame. If the whole jpanel is covered, then the whole character would be gone when the overlapping is removed.
What can I do to enable the character to be displayed even when i remove the overlapping?
Hope my descriptions are vivid to you all.
ShokerHi,
Thanks for your replies!
Well after searching through the forum, I realised that my problem lies with 'getGraphics()'. This function only stores the data temporary. Therefore, when a frame overlaps it, the that overlapped portion is erased. Shown below are my codes:
Graphics g2 = null;
g2 = jPanel8.getGraphics(); //problem
jPanel8.paint(g2);
g2.setFont(new Font("Arial",Font.PLAIN,12));
g2.drawString(rClassify[count_rClass],10,10);
g2.dispose();
I tried using 'super.paintComponents(g2)' but during runtime, there is an error regarding some null pointers. Hence, the problem still exist.
Would appreciate greatly if you guys can enlighten me!
Thanks.
Shoker -
Problem with BufferedImage & "getGraphics()" / "createGraphics()"
I try to create with a servlet a Graphics2D Object with the method "createGraphics()" from a BufferedImage Object. Therefore I use the following code:
BufferedImage bufferimage=new BufferedImage(100,100,BufferedImage. TYPE_INT_RGB);
Graphics2D g2;
g2=bufferimage.createGraphics();
With the Graphics2D Object I wanna draw into the BufferedImage Object:
g2brut.drawLine(5,5,30,30);
The servlet runs fine on a Windows-PC with Apache and Jserv. On a Linux-PC the same code doesn't work: The method createGraphics() creates a bug and the servlet doesn't run any longer.
Hope someone could help!If there are no graphical components in your Linux system, like X-Windows or something, you don't have the capabilities to use the drawing package. AWT is system-dependent and without drawing routines on your system, you can't access drawing functions in Java. Assuming this is the problem, there's a package out there that gets around that by providing system-independent access to AWT. I've only heard of the problem, never faced it myself so I don't know exactly how to implement it, but my friend ran into the same problem and solved it this way.
Here's the link: http://www.eteks.com/pja/en/
Michael Bishop -
A problem with Threads and MMapi
I am tring to execute a class based on Game canvas.
The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
The MIDI tone "Stammers".
How to over come the problem?
Thanks in advance
Kobi
See Code example below:
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
public class MainScreenCanvas extends GameCanvas implements Runnable {
private MainMIDlet parent;
private boolean mTrucking = false;
Image imgBackgound = null;
int imgBackgoundX = 0, imgBackgoundY = 0;
Player player;
public MainScreenCanvas(MainMIDlet parent)
super(true);
this.parent = parent;
try
imgBackgound = Image.createImage("/images/area03_bkg0.png");
imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
catch(Exception e)
System.out.println(e.getMessage());
* starts thread
public void start()
mTrucking = true;
Thread t = new Thread(this);
t.start();
* stops thread
public void stop()
mTrucking = false;
public void play()
try
InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
player = Manager.createPlayer(is, "audio/midi");
player.setLoopCount(-1);
player.prefetch();
player.start();
catch(Exception e)
System.out.println(e.getMessage());
public void run()
Graphics g = getGraphics();
play();
while (true)
tick();
input();
render(g);
* responsible for object movements
private void tick()
* response to key input
private void input()
int keyStates = getKeyStates();
if ((keyStates & LEFT_PRESSED) != 0)
imgBackgoundX++;
if (imgBackgoundX > 0)
imgBackgoundX = 0;
if ((keyStates & RIGHT_PRESSED) != 0)
imgBackgoundX--;
if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
* Responsible for the drawing
* @param g
private void render(Graphics g)
g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
this.flushGraphics();
}You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
Regds,
SD
N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM -
We are experiencing a landry list of problems with java 1.2.2 and 1.3 when trying to print reasonably simple reports. I am just curious if anyone has encounterd problems like these, or if anyone has had any luck working around them. We would really like to release our software to production but I need to make sure that printing works well on all of the environments our client might run on. Here are the problems:
* Reporting was originaly done with a proprietary tool that limits us to using java.awt.PrintJob (new code is using PrinterJob... which is working okay...)
* When I try to use jre1.3 on my NT4.0 machine with a very simple program that gets a PrintJob it doesn't open the Print dialog and simply returns null (although it does work on my WinME laptop, and I cant find any bug reports about PrintJob dialogs on this site)
* When I try to use jre1.2 (which was our original target) there are problems with some printers running with some drivers (in house they are all various network HP printers). The printers will take 3 minutes a page while the same printer with an different driver (non-PS or PCL) will print very quickly.
Well I need some advice, are other people releasing software that doesn't work with all the possible ways that people could have their printers configured? Is there any hope of me finding a workaround... Is someone perhaps maintaining a list of drivers that work well with java? Or is there some empirical way of deciding (perhaps drivers that are not PS or PCL?)... Any responce would be very helpful...
--Erik HaddenWell, I decided to post my problem in more than one forum and got a response that may be what you are looking for. I haven't tried it yet and I'm not sure I understand it correctly, but I thought it may help you since it deals with printJob and supposedly works:
Other person wrote the following:
I have worked on printing but through Print Job.
i Print Multiple pages in landscsape.
in the printer Job you can print the static information
like if you implemented BOOk for mutiple pages it will only print the last information of your print function.
i found many problems when i was trying to implemnet printer Job
here is the complete code how can you print through print Job u can extends this to implement for multiple pages just use array of graphics.
Graphics Arrpage[];
Arrpage=new Graphics[count_pages];
PageAttributes pa=new PageAttributes();
pa.setOrientationRequested(PageAttributes.OrientationRequestedType.LANDSCAPE);
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Toolkit toolkit = this.getToolkit();
PrintJob job = toolkit.getPrintJob(new Frame(), user,null,pa);
if (job == null) return;
for(int j=0;j<count_pages;j++)
Arrpage[j] = job.getGraphics();
// Check the size of the scribble component and of the page.
Dimension size = this.getSize();
Dimension pagesize = job.getPageDimension();
// Center the output on the page. Otherwise it would be
// be scrunched up in the upper-left corner of the page.
Arrpage[j].translate((pagesize.width - size.width)/2, (pagesize.height - size.height)/2);
Arrpage[j].setColor(Color.white);
Arrpage[j].fillRect(0,0,pagesize.width,pagesize.height);
Arrpage[j].setClip(0, 0, size.width, size.height);
Arrpage[j].dispose(); // End the page--send it to the printer.
//System.out.println("Disposing "+j+" page");
}// end of for loop
//System.out.println("before ending the job");
job.end(); // End the print job.
Hope this will help u. -
Problems changing colour using Graphics class in java.awt
Hi,
The problem only happens when more than two images are on a panel. In this case, I have to strings that are drawn. The first drawn string is called "A" the second drawn string is called "B". However, when i change the colour of "B" to let's say Red, the panel erases the letter "B" and insteads changes "A" to red. How can I fix this so that when the user chooses the colour red it changes the colour of the latest drawn string and not the first one. please help!!!!
import java.awt.*;
public class StringPanel extends GBPanel
private String shape = "clear", str;
private int x, y;
private Color color = Color.black;
public void paintComponent(Graphics g)
super.paintComponent(g);
g.setColor (color);
if(shape.equalsIgnoreCase("draw string"))
g.setColor(color);
g.drawString(str, x, y);
else if (shape.equalsIgnoreCase("exit"))
System.exit(0);
public void drawCurve(Color color)
this.color = color;
repaint();
public void drawString(String shape, String str, int x, int y)
this.shape = shape;
this.str = str;
this.x = x;
this.y = y;
repaint();
public void drawString1(String shape, String str, int x, int y)
Graphics g = getGraphics();
g.setColor(color);
if (shape.equalsIgnoreCase("draw string"))
g.setColor(color);
g.drawString(str, x, y);
else
repaint();
}well, as I said, I can't remember what the update method thing was for... I think it was related to not clearing the screen first.
Anyway, if you maintain a list of objects that should be drawn and then in the paintComponent method, loop thru the list of objects and redraw them, it will work. Then you change the state of an object and call repaint. When you are going to change color, you need to, in effect, redraw the entire affected area. Now this can be done partially with clipping, but it's complicated to deal with that. So the simplest way is just redraw everything on repaint. -
The Rules of Game of Life
For a space that is 'populated':
Each cell with one or no neighbors dies, as if by loneliness.
Each cell with four or more neighbors dies, as if by overpopulation.
Each cell with two or three neighbors survives.
For a space that is 'empty' or 'unpopulated'
Each cell with three neighbors becomes populated.
I have three classes: Cell, BoardComponent, and GameViewer
I got few problems in my code: 1. the button shows wrongly, 2. without the button, there is always a dot on the upper-left corner, which is not on purpose, 3, after click the mouse to initialize few dots, nothing happened
How could I fix those problems?
My Code:
1. Cell:
import java.awt.Rectangle;
public class Cell extends Rectangle{
public Cell(int x, int y, int side)
super(x, y, side, side);
}2. BoardComponent:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import com.sun.jdi.event.Event;
public class BoardComponent extends JComponent{
public BoardComponent()
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
board[i][j] = new Cell(i*SIDE, j*SIDE, SIDE);
public void paint(Graphics g)
Graphics2D g2 = (Graphics2D)g;
for(int i = 0; i < ROW; i++)
for(int j = 0; j < COL; j++)
g2.draw(board[i][j]);
public void initialize(int x, int y)
Graphics g = getGraphics();
Graphics2D g2 = (Graphics2D) g;
if(g2.getColor().equals(Color.BLUE))
g2.getBackground();
else
g2.setColor(Color.BLUE);
g.fillOval(mouseX, mouseY, 10, 10);
public void generate()
int count = 0;
for(int i = 0; i < ROW-2; i++)
for(int j = 0; j < COL-2; j++)
for(int m = 0; m < 2; m++)
for(int n = 0; n < 2; n++)
if(m!=0 || n !=0)
if(!(board[i+m][j+n].isEmpty()))
count++;
if(count == 3 || count < 2 || count > 4)
initialize(i*SIDE, j*SIDE);
private int mouseX, mouseY;
private boolean mouseclicked = false;
public static final int ROW = 40;
public static final int COL = 40;
private Cell[][] board = new Cell[ROW][COL];
public static final int SIDE = 14;
}3. GameViewer:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class GameViewer extends JFrame{
public static void main(String[] args)
final BoardComponent game = new BoardComponent();
class MouseClickListener extends MouseAdapter
public void mouseClicked(MouseEvent event)
int x = event.getX();
int y = event.getY();
game.initialize(x, y);
MouseAdapter listener = new MouseClickListener();
game.addMouseListener(listener);
JButton button = new JButton("Start");
class TimerListener implements ActionListener
public void actionPerformed(ActionEvent event)
game.generate();
ActionListener timer = new TimerListener();
button.setSize(40, 10);
button.setLocation(250, 500);
button.addActionListener(timer);
final int DELAY = 500;
Timer t = new Timer(DELAY, timer);
t.start();
JFrame window = new JFrame();
window.setSize(600, 600);
window.setTitle("Life of Game");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.add(game);
window.add(button);
window.setVisible(true);
}Thanks a million.As already said, you should override paintComponent(), not paint(), and don't forget to call the superclass's paintComponent() method.
public void paintComponent(Graphics g)
super.paintComponent(g);
}As for this method:
public void initialize(int x, int y)
Graphics g = getGraphics();
Graphics2D g2 = (Graphics2D) g;
if(g2.getColor().equals(Color.BLUE))
g2.getBackground();
else
g2.setColor(Color.BLUE);
g.fillOval(mouseX, mouseY, 10, 10);
}You really shouldn't be doing any painting outside the paintComponent() method.
Finally, your GameViewer class extends JFrame, but yet you are creating another JFrame in the main method. This doesn't make sense. -
JInternalFrame drawing problem.
Hi gurus
Please could you help with a java problem that I cant find an answer to over the net:
I have a JDesktop which contains multiple JInternalFrames. On one JInternalFrame i have attached a JPanel on which to draw on. I have multiple threads (simple ball shapes) that need to be drawn onto the JPanel and have left it up to the indivual threads to draw themselves (as opposed to using paintComponent in the JPanel class). The drawing on the JInternalFrame works perfectly fine.
The problem arises when the other JInternalFrames are placed on top of each other - the balls are drawn over the top most JInternalFrame. What am i doing wrong? I have attached snippets of the code:
public class Desktop extends JFrame implements ActionListener
public Desktop()
setTitle("Agent's world");
setSize(w,h);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JDesktopPane desktop = new JDesktopPane();
setContentPane(desktop);
/************* Agent *************/
JInternalFrame agents = new JInternalFrame("Agents War", true, false, true, false);
agents.reshape(0,0,(int)((w/3)*2),h);
Container contentPane = agents.getContentPane();
canvas = new AgentPanel(agents);
contentPane.add(canvas);
/************* Button *************/
JPanel buttonPanel = new JPanel();
ButtonGroup buttonGroup = new ButtonGroup();
JButton start = new JButton("START");
start.addActionListener(this);
buttonPanel.add(start);
contentPane.add(buttonPanel, "North");
agents.setVisible(true);
desktop.add(agents);
//sets focus to other frames within the desktop
try
agents.setSelected(true);
catch(PropertyVetoException e)
//attempt to refocus was vetoed by a frame
/** Method to listen for event actions, i.e. button clicks **/
public void actionPerformed(ActionEvent event)
//passes through 'this' to allow access to the getList method
Agents agent = new Agents(canvas, this);
agent.start();
public class Agents extends Thread
public Agents(AgentPanel panel, Desktop desktop)
panel =_panel;
desktop = _desktop;
setDaemon(true);
/** Moves the agent from a spefic position to a new position **/
public void move()
Graphics g = panel.getGraphics();
Graphics2D g2 = (Graphics2D)g;
try
//set XOR mode
g.setXORMode(panel.getBackground());
//draw over old
Ellipse2D.Double ballOld = new Ellipse2D.Double(i , j, length, length);
g2.fill(ballOld);
i++;
j++;
if(flag == true)
//draw new
Ellipse2D.Double ballNew = new Ellipse2D.Double(i , j, length, length);
g2.fill(ballNew);
g2.setPaintMode();
finally
g.dispose();
/** Activates the Thread **/
public void run()
int i = 0;
while(!interrupted() && i<100)
try
for(i = 0 ; i <100 ; i++)
//draw ball in old position move();
sleep(100);
catch(InterruptedException e)
public class AgentPanel extends JPanel
/** local copy of internal frame */
private JInternalFrame frame;
public AgentPanel(JInternalFrame _frame)
frame = _frame;
setSize(frame.getWidth(), frame.getHeight());
setBackground(Color.white);
public void paintComponent(Graphics g)
super.paintComponent(g);
Thank you in advance.
RavsI have the same problem. Seems to be a bug. See:
http://forum.java.sun.com/thread.jsp?forum=57&thread=231037
Bummer. -
Problem converting a (working) Java program into an applet
When I'm trying to access an Image through a call to :
mediaTracker = new MediaTracker(this);
backGroundImage = getImage(getDocumentBase(), "background.gif");
mediaTracker.addImage(backGroundImage, 0);
I'm getting a nullPointerException as a result of the call to getDocumentBase() :
C:\Chantier\Java\BallsApplet
AppletViewer testBallsApplet.htmljava.lang.NullPointerException
at java.applet.Applet.getDocumentBase(Applet.java:125)
at Balls.<init>(Balls.java:84)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
orAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
onstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
at java.lang.Class.newInstance0(Class.java:296)
at java.lang.Class.newInstance(Class.java:249)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:548)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:477)
at sun.applet.AppletPanel.run(AppletPanel.java:290)
at java.lang.Thread.run(Thread.java:536)
It seems very weird to me... :-/
(all the .gif files are in the same directory than the .class files)
The problem appears with AppletViewer trying to open an HTML file
containing :
<HTML>
<APPLET CODE="Balls.class" WIDTH=300 HEIGHT=211>
</APPLET>
</HTML>
(I tried unsuccessfully the CODEBASE and ARCHIVE attributes, with and without putting the .gif and .class into a .jar file)
I can't find the solution by myself, so, I'd be very glad if someone could help
me with this... Thank you very much in advance ! :-)
You'll find below the source of a small game that I wrote and debugged (without
problem) and that I'm now (unsuccessfully) trying to convert into an Applet :
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.net.URL;
public class Balls extends java.applet.Applet implements Runnable, KeyListener
private Image offScreenImage;
private Image backGroundImage;
private Image[] gifImages = new Image[6];
private Image PressStart ;
private Sprite pressStartSprite = null ;
private Image YouLose ;
private Sprite YouLoseSprite = null ;
private Image NextStage ;
private Sprite NextStageSprite = null ;
private Image GamePaused ;
private Sprite GamePausedSprite = null ;
//offscreen graphics context
private Graphics offScreenGraphicsCtx;
private Thread animationThread;
private MediaTracker mediaTracker;
private SpriteManager spriteManager;
//Animation display rate, 12fps
private int animationDelay = 83;
private Random rand = new Random(System.currentTimeMillis());
private int message = 0 ; // 0 = no message (normal playing phase)
// 1 = press space to start
// 2 = press space for next level
// 3 = game PAUSED, press space to unpause
// 4 = You LOSE
public static void main(String[] args)
try
new Balls() ;
catch (java.net.MalformedURLException e)
System.out.println(e);
}//end main
public void start()
//Create and start animation thread
animationThread = new Thread(this);
animationThread.start();
public void init()
try
new Balls() ;
catch (java.net.MalformedURLException e)
System.out.println(e);
public Balls() throws java.net.MalformedURLException
{//constructor
// Load and track the images
mediaTracker = new MediaTracker(this);
backGroundImage = getImage(getDocumentBase(), "background.gif");
mediaTracker.addImage(backGroundImage, 0);
PressStart = getImage(getDocumentBase(), "press_start.gif");
mediaTracker.addImage(PressStart, 0);
NextStage = getImage(getDocumentBase(), "stage_complete.gif");
mediaTracker.addImage(NextStage, 0);
GamePaused = getImage(getDocumentBase(), "game_paused.gif");
mediaTracker.addImage(GamePaused, 0);
YouLose = getImage(getDocumentBase(), "you_lose.gif");
mediaTracker.addImage(YouLose, 0);
//Get and track 6 images to use
// for sprites
gifImages[0] = getImage(getDocumentBase(), "blueball.gif");
mediaTracker.addImage(gifImages[0], 0);
gifImages[1] = getImage(getDocumentBase(), "redball.gif");
mediaTracker.addImage(gifImages[1], 0);
gifImages[2] = getImage(getDocumentBase(), "greenball.gif");
mediaTracker.addImage(gifImages[2], 0);
gifImages[3] = getImage(getDocumentBase(), "yellowball.gif");
mediaTracker.addImage(gifImages[3], 0);
gifImages[4] = getImage(getDocumentBase(), "purpleball.gif");
mediaTracker.addImage(gifImages[4], 0);
gifImages[5] = getImage(getDocumentBase(), "orangeball.gif");
mediaTracker.addImage(gifImages[5], 0);
//Block and wait for all images to
// be loaded
try {
mediaTracker.waitForID(0);
}catch (InterruptedException e) {
System.out.println(e);
}//end catch
//Base the Frame size on the size
// of the background image.
//These getter methods return -1 if
// the size is not yet known.
//Insets will be used later to
// limit the graphics area to the
// client area of the Frame.
int width = backGroundImage.getWidth(this);
int height = backGroundImage.getHeight(this);
//While not likely, it may be
// possible that the size isn't
// known yet. Do the following
// just in case.
//Wait until size is known
while(width == -1 || height == -1)
System.out.println("Waiting for image");
width = backGroundImage.getWidth(this);
height = backGroundImage.getHeight(this);
}//end while loop
//Display the frame
setSize(width,height);
setVisible(true);
//setTitle("Balls");
//Anonymous inner class window
// listener to terminate the
// program.
this.addWindowListener
(new WindowAdapter()
{public void windowClosing(WindowEvent e){System.exit(0);}});
// Add a key listener for keyboard management
this.addKeyListener(this);
}//end constructor
public void run()
Point center_place = new Point(
backGroundImage.getWidth(this)/2-PressStart.getWidth(this)/2,
backGroundImage.getHeight(this)/2-PressStart.getHeight(this)/2) ;
pressStartSprite = new Sprite(this, PressStart, center_place, new Point(0, 0),true);
center_place = new Point(
backGroundImage.getWidth(this)/2-NextStage.getWidth(this)/2,
backGroundImage.getHeight(this)/2-NextStage.getHeight(this)/2) ;
NextStageSprite = new Sprite(this, NextStage, center_place, new Point(0, 0),true);
center_place = new Point(
backGroundImage.getWidth(this)/2-GamePaused.getWidth(this)/2,
backGroundImage.getHeight(this)/2-GamePaused.getHeight(this)/2) ;
GamePausedSprite = new Sprite(this, GamePaused, center_place, new Point(0, 0),true);
center_place = new Point(
backGroundImage.getWidth(this)/2-YouLose.getWidth(this)/2,
backGroundImage.getHeight(this)/2-YouLose.getHeight(this)/2) ;
YouLoseSprite = new Sprite(this, YouLose, center_place, new Point(0, 0),true);
BackgroundImage bgimage = new BackgroundImage(this, backGroundImage) ;
for (;;) // infinite loop
long time = System.currentTimeMillis();
message = 1 ; // "press start to begin"
while (message != 0)
repaint() ;
try
time += animationDelay;
Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
catch (InterruptedException e)
System.out.println(e);
}//end catch
boolean you_lose = false ;
for (int max_speed = 7 ; !you_lose && max_speed < 15 ; max_speed++)
for (int difficulty = 2 ; !you_lose && difficulty < 14 ; difficulty++)
boolean unfinished_stage = true ;
spriteManager = new SpriteManager(bgimage);
spriteManager.setParameters(difficulty, max_speed) ;
//Create 15 sprites from 6 gif
// files.
for (int cnt = 0; cnt < 15; cnt++)
if (cnt == 0)
Point position = new Point(
backGroundImage.getWidth(this)/2-gifImages[0].getWidth(this)/2,
backGroundImage.getHeight(this)/2-gifImages[0].getHeight(this)/2) ;
spriteManager.addSprite(makeSprite(position, 0, false));
else
Point position = spriteManager.
getEmptyPosition(new Dimension(gifImages[0].getWidth(this),
gifImages[0].getHeight(this)));
if (cnt < difficulty)
spriteManager.addSprite(makeSprite(position, 1, true));
else
spriteManager.addSprite(makeSprite(position, 2, true));
}//end for loop
time = System.currentTimeMillis();
while (!spriteManager.getFinishedStage() && !spriteManager.getGameOver())
// Loop, sleep, and update sprite
// positions once each 83
// milliseconds
spriteManager.update();
repaint();
try
time += animationDelay;
Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
catch (InterruptedException e)
System.out.println(e);
}//end catch
}//end while loop
if (spriteManager.getGameOver())
message = 4 ;
while (message != 0)
spriteManager.update();
repaint();
try
time += animationDelay;
Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
catch (InterruptedException e)
System.out.println(e);
}//end catch
you_lose = true ;
if (spriteManager.getFinishedStage())
message = 2 ;
while (message != 0)
spriteManager.update();
repaint();
try
time += animationDelay;
Thread.sleep(Math.max(0,time - System.currentTimeMillis()));
catch (InterruptedException e)
System.out.println(e);
}//end catch
} // end for difficulty loop
} // end for max_speed
} // end infinite loop
}//end run method
private Sprite makeSprite(Point position, int imageIndex, boolean wind)
return new Sprite(
this,
gifImages[imageIndex],
position,
new Point(rand.nextInt() % 5,
rand.nextInt() % 5),
wind);
}//end makeSprite()
//Overridden graphics update method
// on the Frame
public void update(Graphics g)
//Create the offscreen graphics
// context
if (offScreenGraphicsCtx == null)
offScreenImage = createImage(getSize().width,
getSize().height);
offScreenGraphicsCtx = offScreenImage.getGraphics();
}//end if
if (message == 0)
// Draw the sprites offscreen
spriteManager.drawScene(offScreenGraphicsCtx);
else if (message == 1)
pressStartSprite.drawSpriteImage(offScreenGraphicsCtx);
else if (message == 2)
NextStageSprite.drawSpriteImage(offScreenGraphicsCtx);
else if (message == 3)
GamePausedSprite.drawSpriteImage(offScreenGraphicsCtx);
else if (message == 4)
YouLoseSprite.drawSpriteImage(offScreenGraphicsCtx);
// Draw the scene onto the screen
if(offScreenImage != null)
g.drawImage(offScreenImage, 0, 0, this);
}//end if
}//end overridden update method
//Overridden paint method on the
// Frame
public void paint(Graphics g)
//Nothing required here. All
// drawing is done in the update
// method above.
}//end overridden paint method
// Methods to handle Keyboard event
public void keyPressed(KeyEvent evt)
int key = evt.getKeyCode(); // Keyboard code for the pressed key.
if (key == KeyEvent.VK_SPACE)
if (message != 0)
message = 0 ;
else
message = 3 ;
if (key == KeyEvent.VK_LEFT)
if (spriteManager != null)
spriteManager.goLeft() ;
else if (key == KeyEvent.VK_RIGHT)
if (spriteManager != null)
spriteManager.goRight() ;
else if (key == KeyEvent.VK_UP)
if (spriteManager != null)
spriteManager.goUp() ;
else if (key == KeyEvent.VK_DOWN)
if (spriteManager != null)
spriteManager.goDown() ;
if (spriteManager != null)
spriteManager.setMessage(message) ;
public void keyReleased(KeyEvent evt)
public void keyTyped(KeyEvent e)
char key = e.getKeyChar() ;
//~ if (key == 's')
//~ stop = true ;
//~ else if (key == 'c')
//~ stop = false ;
//~ spriteManager.setStop(stop) ;
}//end class Balls
//===================================//
class BackgroundImage
private Image image;
private Component component;
private Dimension size;
public BackgroundImage(
Component component,
Image image)
this.component = component;
size = component.getSize();
this.image = image;
}//end construtor
public Dimension getSize(){
return size;
}//end getSize()
public Image getImage(){
return image;
}//end getImage()
public void setImage(Image image){
this.image = image;
}//end setImage()
public void drawBackgroundImage(Graphics g)
g.drawImage(image, 0, 0, component);
}//end drawBackgroundImage()
}//end class BackgroundImage
//===========================
class SpriteManager extends Vector
private BackgroundImage backgroundImage;
private boolean finished_stage = false ;
private boolean game_over = false ;
private int difficulty ;
private int max_speed ;
public boolean getFinishedStage()
finished_stage = true ;
for (int cnt = difficulty ; cnt < size(); cnt++)
Sprite sprite = (Sprite)elementAt(cnt);
if (!sprite.getEaten())
finished_stage = false ;
return finished_stage ;
public boolean getGameOver() {return game_over ;}
public void setParameters(int diff, int speed)
difficulty = diff ;
max_speed = speed ;
finished_stage = false ;
game_over = false ;
Sprite sprite;
for (int cnt = 0;cnt < size(); cnt++)
sprite = (Sprite)elementAt(cnt);
sprite.setSpeed(max_speed) ;
public SpriteManager(BackgroundImage backgroundImage)
this.backgroundImage = backgroundImage ;
}//end constructor
public Point getEmptyPosition(Dimension spriteSize)
Rectangle trialSpaceOccupied = new Rectangle(0, 0,
spriteSize.width,
spriteSize.height);
Random rand = new Random(System.currentTimeMillis());
boolean empty = false;
int numTries = 0;
// Search for an empty position
while (!empty && numTries++ < 100)
// Get a trial position
trialSpaceOccupied.x =
Math.abs(rand.nextInt() %
backgroundImage.
getSize().width);
trialSpaceOccupied.y =
Math.abs(rand.nextInt() %
backgroundImage.
getSize().height);
// Iterate through existing
// sprites, checking if position
// is empty
boolean collision = false;
for(int cnt = 0;cnt < size(); cnt++)
Rectangle testSpaceOccupied = ((Sprite)elementAt(cnt)).getSpaceOccupied();
if (trialSpaceOccupied.intersects(testSpaceOccupied))
collision = true;
}//end if
}//end for loop
empty = !collision;
}//end while loop
return new Point(trialSpaceOccupied.x, trialSpaceOccupied.y);
}//end getEmptyPosition()
public void update()
Sprite sprite;
// treat special case of sprite #0 (the player)
sprite = (Sprite)elementAt(0);
sprite.updatePosition() ;
int hitIndex = testForCollision(sprite);
if (hitIndex != -1)
if (hitIndex < difficulty)
{ // if player collides with an hunter (red ball), he loose
sprite.setEaten() ;
game_over = true ;
else
// if player collides with an hunted (green ball), he eats the green
((Sprite)elementAt(hitIndex)).setEaten() ;
//Iterate through sprite list
for (int cnt = 1;cnt < size(); cnt++)
sprite = (Sprite)elementAt(cnt);
//Update a sprite's position
sprite.updatePosition();
//Test for collision. Positive
// result indicates a collision
hitIndex = testForCollision(sprite);
if (hitIndex >= 0)
//a collision has occurred
bounceOffSprite(cnt,hitIndex);
}//end if
}//end for loop
}//end update
public void setMessage(int message)
Sprite sprite;
//Iterate through sprite list
for (int cnt = 0;cnt < size(); cnt++)
sprite = (Sprite)elementAt(cnt);
//Update a sprite's stop status
sprite.setMessage(message);
}//end for loop
}//end update
public void goLeft()
Sprite sprite = (Sprite)elementAt(0);
sprite.goLeft() ;
public void goRight()
Sprite sprite = (Sprite)elementAt(0);
sprite.goRight() ;
public void goUp()
Sprite sprite = (Sprite)elementAt(0);
sprite.goUp() ;
public void goDown()
Sprite sprite = (Sprite)elementAt(0);
sprite.goDown() ;
private int testForCollision(Sprite testSprite)
//Check for collision with other
// sprites
Sprite sprite;
for (int cnt = 0;cnt < size(); cnt++)
sprite = (Sprite)elementAt(cnt);
if (sprite == testSprite)
//don't check self
continue;
//Invoke testCollision method
// of Sprite class to perform
// the actual test.
if (testSprite.testCollision(sprite))
//Return index of colliding
// sprite
return cnt;
}//end for loop
return -1;//No collision detected
}//end testForCollision()
private void bounceOffSprite(int oneHitIndex, int otherHitIndex)
//Swap motion vectors for
// bounce algorithm
Sprite oneSprite = (Sprite)elementAt(oneHitIndex);
Sprite otherSprite = (Sprite)elementAt(otherHitIndex);
Point swap = oneSprite.getMotionVector();
oneSprite.setMotionVector(otherSprite.getMotionVector());
otherSprite.setMotionVector(swap);
}//end bounceOffSprite()
public void drawScene(Graphics g)
//Draw the background and erase
// sprites from graphics area
//Disable the following statement
// for an interesting effect.
backgroundImage.drawBackgroundImage(g);
//Iterate through sprites, drawing
// each sprite
for (int cnt = 0;cnt < size(); cnt++)
((Sprite)elementAt(cnt)).drawSpriteImage(g);
}//end drawScene()
public void addSprite(Sprite sprite)
addElement(sprite);
}//end addSprite()
}//end class SpriteManager
//===================================//
class Sprite
private Component component;
private Image image;
private Rectangle spaceOccupied;
private Point motionVector;
private Rectangle bounds;
private Random rand;
private int message = 0 ; // number of message currently displayed (0 means "no message" = normal game)
private int max_speed = 7 ;
private boolean eaten = false ; // when a green sprite is eaten, it is no longer displayed on screen
private boolean wind = true ;
private boolean go_left = false ;
private boolean go_right = false ;
private boolean go_up = false ;
private boolean go_down = false ;
public Sprite(Component component,
Image image,
Point position,
Point motionVector,
boolean Wind
//Seed a random number generator
// for this sprite with the sprite
// position.
rand = new Random(position.x);
this.component = component;
this.image = image;
setSpaceOccupied(new Rectangle(
position.x,
position.y,
image.getWidth(component),
image.getHeight(component)));
this.motionVector = motionVector;
this.wind = Wind ;
//Compute edges of usable graphics
// area in the Frame.
int topBanner = ((Container)component).getInsets().top;
int bottomBorder = ((Container)component).getInsets().bottom;
int leftBorder = ((Container)component).getInsets().left;
int rightBorder = ((Container)component).getInsets().right;
bounds = new Rectangle( 0 + leftBorder, 0 + topBanner
, component.getSize().width - (leftBorder + rightBorder)
, component.getSize().height - (topBanner + bottomBorder));
}//end constructor
public void setMessage(int message_number)
message = message_number ;
public void setSpeed(int speed)
max_speed = speed ;
public void goLeft()
go_left = true ;
public void goRight()
go_right = true ;
public void goUp()
go_up = true ;
public void goDown()
go_down = true ;
public void setEaten()
eaten = true ;
setSpaceOccupied(new Rectangle(4000,4000,0,0)) ;
public boolean getEaten()
return eaten ;
public Rectangle getSpaceOccupied()
return spaceOccupied;
}//end getSpaceOccupied()
void setSpaceOccupied(Rectangle spaceOccupied)
this.spaceOccupied = spaceOccupied;
}//setSpaceOccupied()
public void setSpaceOccupied(
Point position){
spaceOccupied.setLocation(
position.x, position.y);
}//setSpaceOccupied()
public Point getMotionVector(){
return motionVector;
}//end getMotionVector()
public void setMotionVector(
Point motionVector){
this.motionVector = motionVector;
}//end setMotionVector()
public void setBounds(Rectangle bounds)
this.bounds = bounds;
}//end setBounds()
public void updatePosition()
Point position = new Point(spaceOccupied.x, spaceOccupied.y);
if (message != 0)
return ;
//Insert random behavior. During
// each update, a sprite has about
// one chance in 10 of making a
// random change to its
// motionVector. When a change
// occurs, the motionVector
// coordinate values are forced to
// fall between -7 and 7. This
// puts a cap on the maximum speed
// for a sprite.
if (!wind)
if (go_left)
motionVector.x -= 2 ;
if (motionVector.x < -15)
motionVector.x = -14 ;
go_left = false ;
if (go_right)
motionVector.x += 2 ;
if (motionVector.x > 15)
motionVector.x = 14 ;
go_right = false ;
if (go_up)
motionVector.y -= 2 ;
if (motionVector.y < -15)
motionVector.y = -14 ;
go_up = false ;
if (go_down)
motionVector.y += 2 ;
if (motionVector.y > 15)
motionVector.y = 14 ;
go_down = false ;
else if(rand.nextInt() % 7 == 0)
Point randomOffset =
new Point(rand.nextInt() % 3,
rand.nextInt() % 3);
motionVector.x += randomOffset.x;
if(motionVector.x >= max_speed)
motionVector.x -= max_speed;
if(motionVector.x <= -max_speed)
motionVector.x += max_speed ;
motionVector.y += randomOffset.y;
if(motionVector.y >= max_speed)
motionVector.y -= max_speed;
if(motionVector.y <= -max_speed)
motionVector.y += max_speed;
}//end if
//Move the sprite on the screen
position.translate(motionVector.x, motionVector.y);
//Bounce off the walls
boolean bounceRequired = false;
Point tempMotionVector = new Point(
motionVector.x,
motionVector.y);
//Handle walls in x-dimension
if (position.x < bounds.x)
bounceRequired = true;
position.x = bounds.x;
//reverse direction in x
tempMotionVector.x = -tempMotionVector.x;
else if ((position.x + spaceOccupied.width) > (bounds.x + bounds.width))
bounceRequired = true;
position.x = bounds.x +
bounds.width -
spaceOccupied.width;
//reverse direction in x
tempMotionVector.x =
-tempMotionVector.x;
}//end else if
//Handle walls in y-dimension
if (position.y < bounds.y)
bounceRequired = true;
position.y = bounds.y;
tempMotionVector.y = -tempMotionVector.y;
else if ((position.y + spaceOccupied.height)
> (bounds.y + bounds.height))
bounceRequired = true;
position.y = bounds.y +
bounds.height -
spaceOccupied.height;
tempMotionVector.y =
-tempMotionVector.y;
}//end else if
if(bounceRequired)
//save new motionVector
setMotionVector(
tempMotionVector);
//update spaceOccupied
setSpaceOccupied(position);
}//end updatePosition()
public void drawSpriteImage(Graphics g)
if (!eaten)
g.drawImage(image,
spaceOccupied.x,
spaceOccupied.y,
component);
}//end drawSpriteImage()
public boolean testCollision(Sprite testSprite)
//Check for collision with
// another sprite
if (testSprite != this)
return spaceOccupied.intersects(
testSprite.getSpaceOccupied());
}//end if
return false;
}//end testCollision
}//end Sprite class
//===================================//
Thanks for your help...Sorry,
Can you tell me how do you solve it because I have got the same problem.
Can you indicate me the topic where did you find solution.
Thank in advance. -
Hello,
The problem is pretty much exactly as specified.
Take this class for example:
* To change this template, choose Tools | Templates
* and open the template in the editor.
package vicsanimation;
* @author
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
public class VButton extends JLabel {
BufferedImage activeImage;
BufferedImage pressedImage;
BufferedImage deactiveImage;
BufferedImage highlightedImage;
ImageIcon currentImage;
public VButton (String b1, String b2, String b3, String b4, int x, int y){
activeImage = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);
try {
activeImage = ImageIO.read(new File(b1));
pressedImage = ImageIO.read(new File(b2));
deactiveImage = ImageIO.read(new File(b3));
highlightedImage = ImageIO.read(new File(b4));
catch (IOException e) {
System.out.println(e.getMessage());
this.setSize(activeImage.getWidth(), activeImage.getHeight());
this.setLocation(x,y);
this.setVisible(true);
this.render(); // <----------------- ERROR FROM HERE!!!
// This is the method used to render the button. It does not use the paint method
// because the application can use FullScreen mode.
public void render(){
Graphics2D buttonGraphics = (Graphics2D)this.getGraphics();
buttonGraphics.drawImage(activeImage, null, 0, 0);
System.out.println("Image drawn successfully");
}If I run this code, I get a Null-Pointer exception thrown from the last method. This is because the "buttonGraphics" object is null.
I do know a work-around, although I'd really like to know exactly why this is happening.
The work-around is simply to remove the this.render() call at the end of the constructor, create the button in an outside container object, and then call the render() method from the object that contains the button. For example:
private void initScreen(){
..... snip ....
VButton closeButton = getCloseButton();
this.add(closeButton);
closeButton.render();
..... snip .....
}If anyone could explain to me why this happens (in non-Java expert language) I'd be very thankful.Thanks again for your help.
I'm sure the solution to every problem is in the API if one were to look hard enough!
But obviously the API is massive and I suppose you learn these things from experience more than committing that kind of stuff to memory. If I were to scour the API looking for solutions to things which I only barely understand to start with I'd go mad. Let alone be there for several days.
So thanks for helping out, I really appreciate it!
Edited by: wombatvvv on Jul 23, 2008 3:23 PM -
Problem with JPanel, JMenuBar
Hi, I'm new here so I'm not even sure if I'm posting in the correct forum ^^
I usually don't have problems when building a JFrame and adding items into it but now I'm confused.
When the JFrame is "built", I get a NullPointerException from the Panel's paintComponent method when it's trying to draw an image (g.drawImage())
This is the whole JPanel class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanneauDe extends JPanel
private static final String [] TAB_IMAGE = { "De1.GIF", "De2.GIF", "De3.GIF",
"De4.GIF", "De5.GIF", "De6.GIF" };
private static final int [] TAB_FREQUENCE = {0,0,0,0,0,0};
private static final int SIDE = 100;
private De unDe;
private ImageIcon imageDe;
private boolean aFirstTime;
private int aX, aY;
public PanneauDe()
unDe = new De();
aX = aY = 0;
aFirstTime = true;
addMouseListener(new EcouteurSouris());
public String getStats()
String statsMsg = "";
for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
statsMsg += "Face " + (iPos + 1) + " : " + TAB_FREQUENCE[iPos] + " fois\n\n";
return statsMsg;
public String getTotal()
int total = 0;
for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
total += TAB_FREQUENCE[iPos];
return "Le d� a �t� lanc� " + total + " fois";
public void throwDice()
unDe.throwAgain();
TAB_FREQUENCE[unDe.getFace() - 1] ++;
public void paintComponent (Graphics g)
super.paintComponent(g);
g.drawImage (imageDe.getImage(), aX, aY, null); // <---- THIS GENERATES THE NULLPOINTEREXCEPTION
class EcouteurSouris extends MouseAdapter
public void mouseClicked (MouseEvent pMouseEvent)
aX = pMouseEvent.getX();
aY = pMouseEvent.getY();
throwDice();
imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
repaint();
}When I click in the windows, a picture of a dice (different side, randomly generated by the method throwDice() ), when I click again the first image dissapear and another one appears... and I make statistics about the results.
I tried ...
public void paintComponent (Graphics g)
super.paintComponent(g);
//g.drawImage (imageDe.getImage(), aX, aY, null);
class EcouteurSouris extends MouseAdapter
public void mouseClicked (MouseEvent pMouseEvent)
aX = pMouseEvent.getX();
aY = pMouseEvent.getY();
throwDice();
imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
Graphics g = getGraphics();
g.drawImage (imageDe.getImage(), aX, aY, null);
g.dispose();
}Everything works correctly, no more NullPointerException, but the images don't dissapear when I click again. They just stay there.
I'm not completly familiar with the repaint/dispose/paintComponent but I really don't understand why i get this NullPointerException error :\
If you see some weird words in the code, it's because i'm canadian-frenchy! :)
Full program is hereThe real question is why are you trying to override the paintComponent() method. Just add the image to a JLabel and add the label to a panel.
However, the problem is that the paintComponent() method is invoked when the frame is shown and since you don't create the image until you do a mouseClick, the image in null. -
Problem with Graphics and JPanel...
I would like to draw a rectangle on a JPanel. Here is my code:
JPanel panel = new JPanel();
Graphics g = panel.getGraphics();
g.drawRect(20,20,20,20);
When I run my program, I have a NullPointerException...
Do you any suggestions to fix the problem??
thanks
Peteimport java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class pete extends JFrame {
public pete() {
JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int midx = getSize().width / 2;
int midy = getSize().height / 2;
g2.draw(new Rectangle2D.Double(midx/2, midy/2, midx, midy));
getContentPane().add(panel, "Center");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
setLocation(300,100);
setVisible(true);
public static void main(String[] args) {
new pete();
} -
Problem with Double Buffering and Swing
Hi
I made a game and basically it works pretty well, my only problem is it flickers really badly right now. I read up on a whole lot of forums about double buffering and none of those methods seemed to work. Then I noticed that Swing has double buffering built in so I tried that but then I get compilation errors and I'm really not sure why. My original code was a console application and worked perfectly, then I ported it into a JApplet and it still works but it flickers and thats what I'm tryign to fix now.
The code below is in my main class under the constructor.
Heres the double buffering code I'm trying to use, I'm sure you all seen it before lol
public void update(Graphics g)
// initialize buffer
if (dbImage == null)
dbImage = createImage(this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics();
// clear screen in background
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
// draw elements in background
dbg.setColor(getForeground());
paint(dbg);
// draw image on the screen
g.drawImage(dbImage, 0, 0, this);
}My paint is right under neath and heres how it looks
This snipet of code works but when I change the method to
public paintComponent(Graphics g){
super.paintComponent(g)...
everythign stops working and get a compilation error and says that it can't find paintComponent in javax.swing.JFrame.
public void paint(Graphics g)
super.paint(g);
//if game starting display menue
if (show_menue)
//to restart lives if player dies
lives = 3;
menue.draw_menue(g);
menue_ufo1.draw_shape(g);
menue_ufo2.shape_color = Color.DARK_GRAY;
menue_ufo2.draw_shape(g);
menue_ufo3.shape_color = Color.BLUE;
menue_ufo3.draw_shape(g);
menue_ufo4.shape_color = new Color(82, 157, 22);
menue_ufo4.draw_shape(g);
menue_ufo5.draw_shape(g);
menue_ufo6.shape_color = new Color(130, 3, 3); ;
menue_ufo6.draw_shape(g);
menue_turret.draw_ship(g);
menue_ammo.draw_ammo(g);
else
//otherwise redraw game objects
gunner.draw_ship(g);
y_ammo.draw_ammo(g);
grass.draw_bar(g);
o_ufo.draw_shape(g);
b_ufo.draw_shape(g);
m_ufo.draw_shape(g);
s_ufo.draw_shape(g);
z_ufo.draw_shape(g);
xx_ufo.draw_shape(g);
info.draw_bar(g);
live_painter.draw_lives(g, lives);
score_painter.draw_score(g, score);
level_display.draw_level(g, level);
explosion.draw_boom(g);
}I just want to get rid of the flickering for now so any help will be greatly appreciated. Depending which will be simpler I can either try to double buffer this program or port it all to swing but I'm not sure which elements are effected by AWT and which by Swing. Also I read some of the Java documentation but couldn't really understand how to implement it to fix my program.
Thanks in advance
SebastianThis is a simple animation example quickly thrown together. I have two classes, an animation panel which is a JPanel subclass that overrides paintComponent and draws the animation, and a JApplet subclass that simply holds the animation panel in the applet's contentpane:
SimpleAnimationPanel.java
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.Timer;
class SimpleAnimationPanel extends JPanel
private static final int DELAY = 20;
public static final int X_TRANSLATION = 2;
public static final int Y_TRANSLATION = 2;
private Point point = new Point(5, 32);
private BufferedImage duke = null;
private Timer timer = new Timer(DELAY, new TimerAction());
public SimpleAnimationPanel()
try
// borrow an image from sun.com
duke = ImageIO.read(new URL(
"http://java.sun.com/products/plugin/images/duke.wave.med.gif"));
catch (MalformedURLException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
setPreferredSize(new Dimension(600, 400));
timer.start();
// do our drawing here in the paintComponent override
@Override
protected void paintComponent(Graphics g)
super.paintComponent(g);
if (duke != null)
g.drawImage(duke, point.x, point.y, this);
private class TimerAction implements ActionListener
@Override
public void actionPerformed(ActionEvent e)
int x = point.x;
int y = point.y;
Dimension size = SimpleAnimationPanel.this.getSize();
if (x > size.width)
x = 0;
else
x += X_TRANSLATION;
if (y > size.height)
y = 0;
else
y += Y_TRANSLATION;
point.setLocation(new Point(x, y)); // update the point
SimpleAnimationPanel.this.repaint();
}AnimationApplet.java
import java.lang.reflect.InvocationTargetException;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class AnimationApplet extends JApplet
public void init()
try
SwingUtilities.invokeAndWait(new Runnable()
public void run()
// construct the panel
JPanel simpleAnimation = new SimpleAnimationPanel();
// put it in the contentPane of the JApplet
getContentPane().add(simpleAnimation);
setSize(simpleAnimation.getPreferredSize());
catch (InterruptedException e)
e.printStackTrace();
catch (InvocationTargetException e)
e.printStackTrace();
}Here's a 3rd bonus class that shows how to put the JPanel into a stand-alone program, a JFrame. It's very similar to doing it in the JApplet:
AnimationFrame.java
import javax.swing.JFrame;
public class AnimationFrame
private static void createAndShowUI()
JFrame frame = new JFrame("SimpleAnimationPanel");
frame.getContentPane().add(new SimpleAnimationPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public static void main(String[] args)
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
createAndShowUI();
}Edited by: Encephalopathic on Mar 15, 2008 11:01 PM -
Problem in JSF with Swing in a web application
hi
i am using jsf for my online projects.my problem is that when i use Swing concept ,the server is closed automatically when i click the swing dialog option 'OK', how can i protect server being closed automatically when user click the the options of Swing dialog box.it is so tedious because my application is going to integrate
with online server?
my swing java file is
* FileExistsDialog.java
package com.obs.ftw.util.alert;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
* FileExistsDialog: A JOptionPane-like dialog that displays the message
* that a file exists.
public class FileExistsDialog extends JDialog {
* The component that gets the focus when the window is first opened
private Component initialFocusOwner = null;
* Command string for replace action (e.g., a button).
* This string is never presented to the user and should
* not be internationalized.
private String CMD_REPLACE = "OK"/*NOI18N*/;
* Command string for a cancel action (e.g., a button).
* This string is never presented to the user and should
* not be internationalized.
private String CMD_CANCEL = "CANCEL"/*NOI18N*/;
// Components we need to access after initialization
private JButton replaceButton = null;
private JButton cancelButton = null;
public FileExistsDialog(){
System.out.println("INSIDE THE FILE EXIST DIALOG");
JFrame frame = new JFrame() {
public Dimension getPreferredSize() {
return new Dimension(200,100);
frame.setTitle("Debugging frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(false);
FileExistsDialog dialog = new FileExistsDialog(frame, true);
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent event) {
System.exit(0);
public void windowClosed(WindowEvent event) {
System.exit(0);
dialog.pack();
dialog.setVisible(true);
* Creates a new FileExistsDialog
* @param parent parent frame
* @param modal modal flag
public FileExistsDialog(Frame parent,boolean modal) {
super(parent, modal);
//initResources();
System.out.println("INSIDE THE FILE EXIST DIALOG CONSTRUCTOR");
initComponents();
pack();
* Determines the locale, loads resources
/* public void initResources() {
Locale locale = Locale.getDefault();
resources = ResourceBundle.getBundle(
"samples.resources.bundles.FileExistsDialogResources", locale);
imagePath = resources.getString("images.path");
}*/ // initResources()
* Sets all of the buttons to be the same size. This is done
* dynamically after the buttons are created, so that the layout
* automatically adjusts to the locale-specific strings.
private void equalizeButtonSizes() {
System.out.println("INSIDE THE equalizeButtonSizes()");
String[] labels = new String[] {
replaceButton.getText(),
cancelButton.getText()
// Get the largest width and height
Dimension maxSize= new Dimension(0,0);
Rectangle2D textBounds = null;
Dimension textSize = null;
FontMetrics metrics =
replaceButton.getFontMetrics(replaceButton.getFont());
Graphics g = getGraphics();
for (int i = 0; i < labels.length; ++i) {
textBounds = metrics.getStringBounds(labels, g);
maxSize.width =
Math.max(maxSize.width, (int)textBounds.getWidth());
maxSize.height =
Math.max(maxSize.height, (int)textBounds.getHeight());
Insets insets =
replaceButton.getBorder().getBorderInsets(replaceButton);
maxSize.width += insets.left + insets.right;
maxSize.height += insets.top + insets.bottom;
// reset preferred and maximum size since BoxLayout takes both
// into account
replaceButton.setPreferredSize((Dimension)maxSize.clone());
cancelButton.setPreferredSize((Dimension)maxSize.clone());
replaceButton.setMaximumSize((Dimension)maxSize.clone());
cancelButton.setMaximumSize((Dimension)maxSize.clone());
} // equalizeButtonSizes()
* This method is called from within the constructor to
* initialize the dialog.
private void initComponents() {
System.out.println("INSIDE THE initComponents()");
// Configure the window, itself
Container contents = getContentPane();
contents.setLayout(new GridBagLayout ());
GridBagConstraints constraints = null;
setTitle("Waring");
// accessibility - all applets, frames, and dialogs should
// have descriptions
this.getAccessibleContext().setAccessibleDescription("Descriptions");
addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent event) {
// For some reason the window opens with no focus owner,
// so we need to force the issue
if (initialFocusOwner != null) {
initialFocusOwner.requestFocus();
// Only do this the 1st time the window is opened
initialFocusOwner = null;
public void windowClosing(WindowEvent event) {
System.out.println("INSIDE THE windowClosing");
// Treat it like a cancel
windowAction(CMD_CANCEL);
// image
JLabel imageLabel = new JLabel();
imageLabel.setIcon(
new ImageIcon("/images/degraded_large.gif"));
// accessibility - set name so that low vision users get a description
imageLabel.getAccessibleContext().setAccessibleName("OK");
constraints = new GridBagConstraints ();
constraints.gridheight = 2;
constraints.insets = new Insets(12, 33, 0, 0);
constraints.anchor = GridBagConstraints.NORTHEAST;
contents.add(imageLabel, constraints);
// header
JLabel headerLabel = new JLabel ();
headerLabel.setText("SAMPLE");
headerLabel.setForeground(
new Color(MetalLookAndFeel.getBlack().getRGB()));
constraints = new GridBagConstraints ();
constraints.insets = new Insets(12, 12, 0, 11);
constraints.anchor = GridBagConstraints.WEST;
contents.add(headerLabel, constraints);
// Actual text of the message
JTextArea contentTextArea = new JTextArea();
contentTextArea.setEditable(false);
contentTextArea.setText("SAMPLE");
contentTextArea.setBackground(
new Color(MetalLookAndFeel.getControl().getRGB()));
// accessibility -- every component that can have the
// keyboard focus must have a name. This text area has no
// label, so the name must be set explicitly (if it had a
// label, the name would be pulled from the label).
contentTextArea.getAccessibleContext().setAccessibleName(
"CONTENTNAME");
constraints = new GridBagConstraints ();
constraints.gridx = 1;
constraints.gridy = 1;
constraints.insets = new Insets(0, 12, 0, 11);
constraints.anchor = GridBagConstraints.WEST;
contents.add(contentTextArea, constraints);
// Buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout (new BoxLayout(buttonPanel, 0));
replaceButton = new JButton();
replaceButton.setActionCommand(CMD_REPLACE);
replaceButton.setText("OK");
replaceButton.setToolTipText("TO OK");
replaceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
windowAction(event);
buttonPanel.add(replaceButton);
// spacing
buttonPanel.add(Box.createRigidArea(new Dimension(5,0)));
cancelButton = new JButton();
cancelButton.setActionCommand(CMD_CANCEL);
cancelButton.setText("CANCEL");
cancelButton.setNextFocusableComponent(replaceButton);
cancelButton.setToolTipText("TO CANCEL");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
windowAction(event);
buttonPanel.add(cancelButton);
constraints = new GridBagConstraints ();
constraints.gridx = 1;
constraints.gridy = 2;
constraints.insets = new Insets(12, 12, 11, 11);
constraints.anchor = GridBagConstraints.WEST;
contents.add(buttonPanel, constraints);
// Equalize the sizes of all the buttons
equalizeButtonSizes();
// For some reason, the dialog appears with no input focus.
// We added a window listener above to force the issue
initialFocusOwner = replaceButton;
} // initComponents()
* The user has selected an option. Here we close and dispose the dialog.
* If actionCommand is an ActionEvent, getCommandString() is called,
* otherwise toString() is used to get the action command.
* @param actionCommand may be null
private void windowAction(Object actionCommand) {
System.out.println("INSIDE THE WINDOW ACTION");
String cmd = null;
if (actionCommand != null) {
if (actionCommand instanceof ActionEvent) {
cmd = ((ActionEvent)actionCommand).getActionCommand();
} else {
cmd = actionCommand.toString();
if (cmd == null) {
// do nothing
} else if (cmd.equals(CMD_REPLACE)) {
System.out.println("your replace code here...");
} else if (cmd.equals(CMD_CANCEL)) {
System.out.println("your cancel code here...");
setVisible(false);
dispose();
} // windowAction()
* This main() is provided for debugging purposes, to display a
* sample dialog.
// main()
} // class FileExistsDialog
and calling java function is
public String fileDialog(){
return "Success";
public void processFile(ActionEvent event){
System.out.println("INSIDE THE FILE DIALOG");
FileExistsDialog file = new FileExistsDialog();
System.out.println("SUCCESS");
called from
<h:commandButton action="#{userLogin.fileDialog}" actionListener="#{userLogin.processFile}"></h:commandButton>
pls help me as soon
advance thanks
rgds
oasisdesertsSwing is GUI library for use in desktop applications.
JSF is a web application framework which runs on an application server and is accessed by clients via web browsers.
To fully understand what you have done, try accessing your application from a different machine than the server.
To answer your question, don't invoke System.exit() if you would like the process to continue. But that is the least of your problems. -
Problem in creating 1 image using differnt images
Dear Fellows I want to create an image by using different images in byte array format. Images may be transparent or normal images. I want final result in byte array. I am using the following technique which is working fine but the problem with this technique is that it takes too much time to create an image. This is because I am using MediaTraker. If I delete the code of MediaTracker then program have undeterministic behavior i.e, sometimes it create the final image properly and sometimes nothing is displayed in final image.
I need some help from you. If anyone of you know the technique to draw image using different images without using mediaTracker kindly let me know.
Early replies will be appreciated
// here is the sample code which i m using for creating image
byte[] backgroundImage= // read 800 X 600 image from disk and convert it in to byte array
byte[] image1 = // read 200 X 200 image from disk and convert it in to byte array
byte[] transparentImage // read 300 X 300 transparent image from disk and convert it in to byte array
Image img=null;
Frame frame =new Frame();
frame.addNotify();
//creating BufferedImage object to store Final image
BufferedImage requiredImage= new BufferedImage(800,600,BufferedImage.SCALE_SMOOTH);
//get Graphics of BufferedImage created above
Graphics2D g=(Graphics2D) requiredImage.getGraphics();
///// begin draw back ground image
img=Toolkit.getDefaultToolkit().createImage(backgroundImage);
try
MediaTracker mt = new MediaTracker(frame);
mt.addImage(img, 0); // adds image with ID 0
mt.waitForID(0);
}catch(Exception myex)
myex.printStackTrace();
//draw background starting from x=0, y=0 with 800 X 600 dimentions
g.drawImage(img,0,0,800,600,null);
////////// end draw background image
////////// begin draw image1
img=Toolkit.getDefaultToolkit().createImage(image1);
try
MediaTracker mt = new MediaTracker(frame);
mt.addImage(img, 0); // adds image with ID 0
mt.waitForID(0);
}catch(Exception myex)
myex.printStackTrace();
//draw image1 starting from x=10, y=10 with 200 X 200 dimentions
g.drawImage(img,10,10,200,200,null);
//////////// end draw image1
//////begin transparentImage
img=Toolkit.getDefaultToolkit().createImage(backData);
try
MediaTracker mt = new MediaTracker(frame);
mt.addImage(img, 0); // adds image with ID 0
mt.waitForID(0);
}catch(Exception myex)
myex.printStackTrace();
//draw transparentImage starting from x=400, y=0 with 300 X 300 dimentions
g.drawImage(img,400,0,300,300,null);
///end draw transparent image
byte []finalResult = //convert requiredImage into byte array;
you can mail me the solution on my email address [email protected]
thanks with best regards
and waiting for someone to reply
kamran zameeris there anyone on this forum to help me??????
regards,
kamran zameer
Maybe you are looking for
-
Memory issues - kernel panics / system freezes with 1Gb Memory Card
I've recently updated my PowerBook OS to 10.4.7 and now more recently 10.4.8. Prior to this, i had been running a pair of pc2700 memory cards (1x1Gb + 1x 512Mb) bought from crucial technology on 10.3.9 with no problems. During the upgrade, i experien
-
ABAP QUERY REPORT on Sales Revenue.
Dear SAP Experts! Can anyone tell me the step by step procedure to create the new additional feilds in Sq02 extras , The Feilds and the Code for the following report. I am working on the Total Sales Revenue. Tables Used :BSID BSAD I want to Show a th
-
There aren't a lot of details in addition to what I put in the question field. Just got the FF beta v4 and used it fine, but when I attempted to launch it today, I got the error. The only info not listed there is the error title, XULRunner, which may
-
Changing serialVersionUID of objects serialized in a file.
For myResearch project I have created an application that saves it's data by placing its objects in an ArrayList and then serializing the ArrayList to file. Up untill now it has been going swimmingly over 18 months. However, I am now for seemingly no
-
Hi All, I have an requirement below..Please help. At present, We are following this process that only after release, the PO can be printed and send by email to the Vendor. Once released, the PO cannot be changed until cancel released with ME28. Now,