Images in JApplet
Hi!
I am trying to convert a game application, made using Java - Swing combination, to an JApplet.
First I installed the newest JRE1.3.1 from the java.sun.com and used the HTMLConverter.
Testing revealed that the JApplet runs quite Ok in the Appletviewer.
When I try to run it in Netscape 6.1 the game works otherwice except that it doesn't have any
of it's pictures which are either in gif - or jpg formats. The Java Console doesn't tell me anything that might indicate a problem.
The interesting part comes when I try to run the same JApplet inside IE5.5. I get a message
that states that the requested html-page (or one of its components) could not be found. At the
same time thought an instance of the Netscape 6.1 is being launched and, to my surprise, the
JApplet runs Ok in it.
If I try to run the JApplet in Opera 5.12 I just get a message saying that a connection to the
running virtual machine could not be established.
At home I use Linux and KDE's browser Konqueror. That's the only one that gives a securityexception for the read operation of the images.
At work, where I have Win 2000, I have tried to play with policytool in order to grant the required reading permissions, but I haven't succeeded yet.
I would appreciate any help in solving this mystery.
Jussi
Image map;
URL url = null;
try
url = new URL(getCodeBase()+"usa.gif");
catch(MalformedURLException e)
map = getToolkit().createImage(url);
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(map,0);
try {tracker.waitForID(0);}
catch (InterruptedException e){} .
//usa.gif is the name of the file
Noah
Similar Messages
-
Hello to all Java expect coder, i would like to load an image to an applet but after it flash once time then it just disappear.
Below is my code :
* SodaVendingMachineApplet.java
* Created on June 8, 2008, 4:08 PM
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.ImageIcon.*;
* @author nicholas_tse
public class SodaVendingMachineApplet extends javax.swing.JApplet {
private ImageIcon soda;
private ImageIcon lemon;
private ImageIcon orange;
private Graphics g;
// To draw image
@Override
public void paint(Graphics g)
soda = new ImageIcon("D:/Java/SodaMachine/cola_5.jpg");
soda.paintIcon(this, g, 30, 40);
/** Initializes the applet SodaVendingMachineApplet */
@Override
public void init() {
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
} catch (Exception ex) {
ex.printStackTrace();
/** This method is called from within the init() method to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jRadioButton3 = new javax.swing.JRadioButton();
jRadioButton4 = new javax.swing.JRadioButton();
jRadioButton5 = new javax.swing.JRadioButton();
jRadioButton6 = new javax.swing.JRadioButton();
jLabel1.setText("Soda");
jLabel2.setText("Lemon");
jLabel3.setText("Orange");
jRadioButton1.setText("Regular");
jRadioButton2.setText("Diet");
jRadioButton3.setText("Regular");
jRadioButton4.setText("Diet");
jRadioButton5.setText("Regular");
jRadioButton6.setText("Diet");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton2)
.addGap(18, 18, 18))
.addComponent(jRadioButton1)))
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(jLabel1)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(49, 49, 49)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButton4)
.addComponent(jRadioButton3))))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jRadioButton6)
.addComponent(jRadioButton5)))
.addGroup(layout.createSequentialGroup()
.addGap(63, 63, 63)
.addComponent(jLabel3)))
.addContainerGap(107, Short.MAX_VALUE))
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(69, 69, 69)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton2))
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton4))
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton5)
.addGap(23, 23, 23))
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jRadioButton6)))
.addContainerGap(175, Short.MAX_VALUE))
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JRadioButton jRadioButton3;
private javax.swing.JRadioButton jRadioButton4;
private javax.swing.JRadioButton jRadioButton5;
private javax.swing.JRadioButton jRadioButton6;
// End of variables declaration
}The image just flash once.
I create using NetBeans IDE via JApplet forms.
I know how to createa button and don't know how to adjust the location. Please help.
Thanks for your help.In the future, Swing related questions should be posted in the Swing forum.
Swing is different than AWT. The design of your applet is wrong.
You should not be overriding the paint() method of the applet.
In Swing you add components to the content pane. So in your case you would add a JPanel with your image to the content pane of the applet.
Search the Swing forum and you will find examples of adding a "background image" to a panel.
I know how to createa button and don't know how to adjust the location. Please help. Then don't use an IDE. Learn how to Layout Managers and design the GUIs on your own. Spend your time learning Java, not the IDE.
Read the JButton API and you will find a link to the Swing tutorial that give an example of using buttons on a frame. -
Drag Drop images/icons JApplet
Hi! I would like to implement a Drag Drop of images/icons between two JPanels in a JApplet. Can someone give me a working example of the code that I have to implement ???
Thanks to you !!!!
TGuidoThe standard procedure is to post a small message to make your old post go to the top
-
Drag Drop icon/image in JApplet
Hi! I would like to implement a Drag Drop of images/icons between two JPanels in a JApplet. Can someone give me a working example of the code that I have to implement ???
Thanks to you !!!!
TGuidoThis should help:
http://java.sun.com/docs/books/tutorial/uiswing/misc/example-1dot4/index.html#BasicDnD -
Displaying image in JApplets which runs on Tomcat?
hi everyone,,,
i've JApplet including label have an image
MyLabel.setIcon(new ImageIcon("images/java.jpeg"));the applets should runs on server - Tomcat -
first i got error in Java Console
<-----filepermission images/java.jpeg read----->
and i put permission in my java.policy
located in security folder
after that; applet run but the image doesnot displayed on the label????
any help please,,,
thanx in advancei think the problem is with java.policy
here is my java.policy file
/* AUTOMATICALLY GENERATED ON Mon Feb 11 11:39:08 EET 2008*/
/* DO NOT EDIT */
grant codeBase "file:/usr/java/jre1.6.0_03/lib/ext/*" {
permission java.security.AllPermission;
permission java.io.FilePermission "<<ALL FILES>>", "read, write, execute, delete";
grant codeBase "file:/usr/java/packages/lib/ext/*" {
permission java.security.AllPermission;
permission java.io.FilePermission "<<ALL FILES>>", "read, write, execute, delete";
grant {
permission java.io.FilePermission "images/java.jpeg", "read, write, execute";
grant {
permission java.io.FilePermission "java.jpeg", "read, execute, delete, write";
}; -
Setting a background image on JApplet
Hi all,
I am new to swing programming. i have to develop a web enabled pgm. for the gui i need to set a background image. i saw some postings in this forum but they didn't satify my requirement. my main class extends from JApplet & it uses a borderLayout. in this i'm putting 2 panels. i need to set the background of the WEST region an image. i used
getLayeredPane().add(label, new Integer(-1))
to add the background image. but when i added the panel to the container then the panel is not getting displayed. i added like
Container c = getContentPane().
c.setLayout(new BorderLayout());
c.add(panel,BorderLayout.NORTH);
here label is a JLabel, panel is a JPanel.
Can somebody help me with a solution. what i should be doing to get everything displayed.
Thanks in advancecheck this post : http://forum.java.sun.com/thread.jsp?forum=57&thread=316074
-
Hi All
my code
Image img = new Image();
img = getImage(getDocumentBase(), "images/db_logo2.gif");
no error found when compile but the image wun show, anyone knows?Try using
URL imageURL;
Class cl = this.getClass();
imageURL = cl.getResource("/images/db_logo2.gif");
img = getImage(imageURL); -
JApplet and the Images --PLEASE reply fast
the problem is i am trying to put a .gif image into JApplet. no matter what i do it just DOESNT WANNA WORK! can anyone please post an example of working one?
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.lang.Object.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.LineBorder.*;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.*;
import java.applet.*;
import java.util.Random;
public class MoveTheSquare extends JApplet implements ActionListener
public static int size = 100;
public static int life = 80;
public static int eneLife=50;
private AudioClip ohboy2= getAudioClip(getDocumentBase(), "ohboy2.wav");
// public Image bricks = getImage(getDocumentBase(),"bricks.gif");
public static void main(String[] args)
ApplicationFrame frame = new ApplicationFrame();
frame.setBounds(50, 50, 900, 900);
frame.setVisible(true);
new ApplicationFrame();
private static class ApplicationFrame extends JFrame
public ApplicationFrame()
super("Move the Sticky Figure!");
// setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 600);
JPanel content = new JPanel();
((JPanel) getContentPane()).setOpaque(true);
// new WindowListener(1);
ImageIcon bricks = new ImageIcon("bricks.gif");
JLabel backlabel = new JLabel(bricks);
getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
backlabel.setBounds(0,0,20000,2560);
setLocation(500,600);
//WindowListener1 = new WindowAdapter() {
//public void windowClosing(WindowEvent e) {
//System.exit(0);
//setVisible(true);
initUi();
private void initUi()
Container cp = getContentPane();
Image img = getImage(getDocumentBase(), "bricks.gif" );
cp.add(new MyPanel(img));
cp.setLayout( new BorderLayout(0, 10) );
// addWindowListener1();
cp.add( new JLabel(" Move the Sticky with the arrow keys:"), BorderLayout.NORTH );
// Create the playing board and the squar
Square sq = new Square( new Point(100, 100), 10 );
Board board = new Board(sq);
cp.add( board, BorderLayout.CENTER );
// Register Key Bindings to move the square around. Read about the
InputMap im = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getRootPane().getActionMap();
// The LEFT arrow will move the suare to pixels two the left
MoveSquareAction moveLeft = new MoveSquareAction(board, -3, 0);
KeyStroke keyStrokeLeft = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
im.put( keyStrokeLeft, "left" );
am.put( "left", moveLeft );
// The RIGHT arrow will move the suare to pixels two the right
MoveSquareAction moveRight = new MoveSquareAction(board, 3, 0);
KeyStroke keyStrokeRight = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
im.put( keyStrokeRight, "right" );
am.put( "right", moveRight );
// The UP arrow will move the suare two pixels up
MoveSquareAction moveUp = new MoveSquareAction(board, 0, -3);
KeyStroke keyStrokeUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
im.put( keyStrokeUp, "up" );
am.put( "up", moveUp );
// The DOWN arrow will move the suare two pixels down
MoveSquareAction moveDown = new MoveSquareAction(board, 0, 3);
KeyStroke keyStrokeDown = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
im.put( keyStrokeDown, "down" );
am.put( "down", moveDown );
pack();
// Class that represents the playing board
private static class Board extends JPanel
private Square square;
public Board(Square sq)
square = sq;
setOpaque(true);
setBorder( new LineBorder(Color.GREEN));
int x=1;
public void paintComponent(Graphics g)
super.paintComponent(g);
g.drawImage( img, currentX, currentY, this );
if (x==1)
Point location = square.getLocation();
String coordX = String.valueOf(location.x);
String coordY = String.valueOf(location.y);
String slife = String.valueOf(life);
//g.drawImage(bricks, 0, 0, 500, 16, this);
g.setColor(Color.red);
g.fillRect(240,240,250,250);
g.setColor(Color.GREEN);
g.fillRect(0,00,40,40);
g.setColor(Color.black);
g.drawLine(location.x-5,location.y+5,location.x,location.y);
g.drawLine(location.x+5,location.y+5,location.x,location.y);
g.drawLine(location.x,location.y,location.x,location.y-7);
g.drawLine(location.x-4,location.y-4,location.x,location.y-7);
g.drawLine(location.x+4,location.y-4,location.x,location.y-7);
g.fillOval(location.x-3,location.y-15,8,8);
g.drawString(coordX,20,20);
g.drawString(coordY,20,30);
g.drawString("YOUR LIFE:", 00,70);
g.drawString(slife,70,70);
Random generator = new Random();
int takeaway = generator.nextInt(25);
int fight = generator.nextInt(50);
if (fight==4)
x=0;
life= life-takeaway;
JOptionPane.showMessageDialog(null, "YOU ARE BEING ATTACKED!!!!! YOU LOST HEALTH:" +takeaway);
slife = String.valueOf(life);
g.drawString(slife,70,70);
if (life<=0)
JOptionPane.showMessageDialog(null, "you lose. bye.");
System.exit(0);
if (((location.x>=240) && (location.y>=240)) &&((location.x<=490) && (location.y<=490)))
JOptionPane.showMessageDialog(null, "you Win! bye.");
System.exit(0);
Random generator = new Random();
int fight = generator.nextInt(50);
if (fight==1)
x=1;
public Square getSquare()
return square;
// The Action class that implements moving the square:
private static class MoveSquareAction extends AbstractAction
// The board this action acts on:
Board board;
// The number of pixels to move in the X- and Y-directions:
int pixelsToMoveX;
int pixelsToMoveY;
public MoveSquareAction(Board board, int pixelsToMoveX, int pixelsToMoveY)
this.board = board;
this.pixelsToMoveX = pixelsToMoveX;
this.pixelsToMoveY = pixelsToMoveY;
public void actionPerformed(ActionEvent e)
// Move the square and repaint the board:
board.getSquare().moveX(pixelsToMoveX);
board.getSquare().moveY(pixelsToMoveY);
board.repaint();
// Class that represents the black square we move around
private static class Square
private Point location;
private int size;
public Square(Point loc, int size)
location = loc;
this.size = size;
public Point getLocation()
return location;
public int getSize()
return size;
public void moveX(int pixels)
location.x += pixels;
public void moveY(int pixels)
location.y += pixels;
public void actionPerformed(ActionEvent e)
ohboy2.loop();//sound
} -
Hi Sun Team and Swing Fans!
I am trying to embed Hypertext Markup Language in my Swing applet..or sould I say..I am trying to add an HTML link in my Swing applet...
The body looks something like that:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class images extends JApplet implements ActionListener {
bla bla bla .... My program
Is there a way to do that and if there is, how do I implement it?
Thank you very much in advance, Albert.Howdy,
If you just want a simple link on your page you could either draw you link on the page and then when mouse down get the coords to see if over your link then:
try {newURL = new URL("http://www.counter-strike.net");}
catch (MalformedURLException e1){}
getAppletContext().showDocument(newURL);
for example. Or you could embed a JEditorPane with HyperlinkListener, in that case you will need to import Javax.swing.event (I think). -
Help please, not able to load images in a subclass of a japplet
I've created this board for a project, but now I am stuck, I cannot seem to get images to appear, instead they come up as a nullpointerexception:
public class Board extends JLayeredPane implements MouseListener, MouseMotionListener{
private Container contentPane;
private JLayeredPane jlp;
private boolean pieceSelected;
private timepanel time;
Image bimage;
ImageIcon board;
JLabel brd;
Image pimage;
ImageIcon piece;
JLabel pce;
private Graphics g;
private pieceLayout pieces;
private String piecename;
private JLabel jl;
boolean selected;
private int offset;
boolean changepos;
boolean moving;
private int brdwidth;
private int brdheight;
private Timer countdown;
private updateTimer ut;
private String cb;
private clientinterface ci;
private JFrame j;
private int playerturn;
public Board(clientinterface ci, JFrame j, Hashtable images, ArrayList names,
ImageIcon brdicon, URL cb)
j.setSize(500,450);
countdown = new Timer();
selected = false;
jlp = this;
jlp.setPreferredSize(new Dimension(500, 450));
changepos = false;
//contentPane = getContentPane();
//this.setPreferredSize(new Dimension(500,400));
jlp.setBounds(0,0,500,450);
jlp.setLocation(0,0);
jlp.setOpaque(true);
jlp.setLayout(null);
System.out.println(this.getSize() + "(((())))" );
if(j.getWidth() > 400)
offset = j.getWidth() - 400;
else
offset = 0;
System.out.println("Width is: " + j.getWidth() + " height: " + j.getHeight());
brdwidth = j.getWidth()-offset;
brdheight = j.getHeight();
System.out.println(images.size());
System.out.println(j.getWidth() + " " + j.getHeight() + " " + offset);
brd = new JLabel(brdicon);
brd.setBounds(0,0,j.getWidth()-offset, j.getHeight());
brd.setSize(new Dimension(400,400));
brd.setLocation(0,0);
brd.setOpaque(true);
jlp.add(brd, new Integer(-5));
jlp.setBounds(0,0,j.getWidth(), j.getHeight());
jlp.setVisible(true);
time = new timepanel(jlp);
time.setLocation(j.getWidth()-offset, 0);
System.out.println(images.toString() + "++++++++");
pieces = new pieceLayout(jlp, j.getWidth()-offset, names, cb);
pieces.setLocation(0,0);
pieces.setPreferredSize(new Dimension(400,400));
pieces.setBounds(0,0,400,400);
pieces.setVisible(true);
time.setBounds(400,0, 100, 400);
time.setVisible(true);
ut = new updateTimer(time);
jlp.add(pieces, new Integer(2));
jlp.add(time, new Integer(2));
//this.add(jlp);
j.setLayeredPane(jlp);
addMouseMotionListener(this);
addMouseListener(this);
//j.getContentPane().add(jlp);
//j.setContentPane(this);
j.validate();
//j.getContentPane().setLayout(null);
//j.setContentPane(this);
j.paintAll(j.getGraphics());
public void run()
//this.repaint();
this.paintAll(this.getGraphics());
time.repaint();
public void mouseDragged(MouseEvent e)
JLabel temp;
moving = true;
//pce.setLocation(e.getX(), e.getY());
//pieces.getPiece(pieces.translatecoords(e.getX(),e.getY())).setLocation(e.getX(),e.getY());
int piecepos = pieces.translatecoords(e.getX(), e.getY());
/*if(pieces.hasPiece(piecepos) && moving)
pieces.setSelected(piecepos);
temp = pieces.getPiece(piecepos);
//pieces.movePiece(e.getX(), e.getY());
temp.setLocation(e.getX(), e.getY());
//this.repaint();
public void mouseClicked(MouseEvent e)
Point xpoin;
System.out.println("Hello, clicked");
/*pce.setLocation(e.getX(), e.getY());
Point p = pce.getLocation();
System.out.println(p.toString());*/
System.out.println("\n" + e.getX() + " " + e.getY());
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
public void mouseReleased(MouseEvent e)
if(selected)
Point xp;
int x = e.getX();
int y = e.getY();
int bp = pieces.translatecoords(x,y);
xp = pieces.posToPoint(bp);
pieces.snapToSquare(xp.x, xp.y, bp);
selected = false;
moving = false;
//pieces.updateBoard(bp, piecename);
public void mouseMoved(MouseEvent e)
public void mousePressed(MouseEvent e)
Point xpoin;
int pos = pieces.translatecoords(e.getX(),e.getY());
System.out.println("\n" + pieces.translatecoords(e.getX(),e.getY()));
if(pieces.hasPiece(pos, e.getX(), e.getY()))
piecename = pieces.getName(pos);
System.out.println("Found a piece!");
pieces.setSelected(pos);
xpoin = pieces.posToPoint(pos);
selected = true;
public void paintComponent(Graphics g)
//super.paintComponents(g);
//System.out.println("Painting");
time.repaint();
public void start()
countdown.schedule(ut, 0, 1000);
public void setupBoard()
//setSize(getSize().width < 400 ? 400 : getSize().width,
//getSize().height < 400 ? 400 : getSize().height);
//getLayeredPane().add(brd, new Integer(-5));
public void sendInfo(String info)
//parse information
public class pieceLayout extends JLayeredPane
JLabel pce1;
private JLabel selected;
private Hashtable pieceList;
private ArrayList names;
private int width;
private Hashtable piecesOnBoard;
private char boardstate[]= {'R','N','B','Q','K','B','N','R',
'P','P','P','P','P','P','P','P',
'p','p','p','p','p','p','p','p',
'r','n','b','q','k','b','n','r'
private String posnm[] = {
"a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8",
"a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7",
"a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6",
"a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5",
"a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4",
"a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3",
"a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2",
"a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1"
JLayeredPane thePane;
private Hashtable ht;
private Hashtable board;
private Hashtable b2p;
private Hashtable p2b;
private Hashtable piecePos;
private Hashtable objToName;
private Hashtable posnames;
private URL codebase;
public pieceLayout(JLayeredPane p, int twidth, ArrayList pnames, URL cb)
pieceList = new Hashtable(20);
codebase = cb;
names = pnames;
selected = new JLabel();
piecesOnBoard = new Hashtable(32);
ht = new Hashtable(6);
board = new Hashtable(64);
b2p = new Hashtable(64);
p2b = new Hashtable(64);
piecePos = new Hashtable(64);
objToName = new Hashtable(32);
posnames = new Hashtable(64);
fillnames();
getImages();
setImages();
width = twidth;
thePane = p;
System.out.println(piecesOnBoard.size());
showBoard();
private void fillnames()
int size = posnm.length;
for(int i = 0; i < size; i++ )
posnames.put(new Integer(i), new String(posnm));
showPos();
private void getImages()
Pattern p = Pattern.compile(".+\\.GIF");
Pattern p1 = Pattern.compile(".+\\.gif");
Pattern p2 = Pattern.compile("board.+");
Pattern p3 = Pattern.compile(".+board.+");
for(int i = 0; i < names.size(); i++)
Matcher m = p.matcher((String)names.get(i));
Matcher m1 = p1.matcher((String)names.get(i));
Matcher m2 = p2.matcher((String)names.get(i));
Matcher m3 = p3.matcher((String)names.get(i));
if(m.matches() || m1.matches())
//System.out.println("Files are: " + dirs[i].getName());
if(!m2.matches() && !m3.matches())
String piecename = new String((String)names.get(i));
// System.out.println("Files were: " + dirs[i].getName());
Image tpimage = Toolkit.getDefaultToolkit().createImage(piecename);
Image pimage = tpimage.getScaledInstance(35,35, Image.SCALE_DEFAULT);
//ImageIcon piece = new ImageIcon(pimage);
pieceList.put(new String(piecename), pimage);
System.out.println(pieceList.toString());
System.out.println(pieceList.size() + "((**))(())");
private void setImages()
int listsize = names.size();
if(!pieceList.isEmpty())
int index = 0;
for(int i = 0; i < listsize; i++)
String pieceName = (String)names.get(index);
String hKey = getHashKey(pieceName);
System.out.println(hKey);
if((hKey.compareTo("blackking") == 0) || (hKey.compareTo("blackqueen") == 0) ||
(hKey.compareTo("whiteking") == 0) || (hKey.compareTo("whitequeen") == 0))
Image tpiece = (Image)pieceList.get(new String(hKey));
ImageIcon piece = new ImageIcon(tpiece);
pce1 = new JLabel(piece);
piecesOnBoard.put(new String(hKey), pce1);
else
System.out.println("multiples " + hKey);
createMultiples(hKey, pieceName);
if(i == listsize-1)
index = 0;
else
index++;
System.out.println(pieceName + " " + hKey + "1234567890");
private void createMultiples(String key, String hname)
JLabel piecet;
String name;
if(key == "blackpawn" || key == "whitepawn")
name = key;
for(int i = 0; i < 8; i++)
//System.out.println(name+i);
String tempname = name+i;
Image piece = (Image)pieceList.get(new String(name));
ImageIcon pieces = new ImageIcon(piece);
piecet = new JLabel(pieces);
piecesOnBoard.put(new String(tempname), piecet);
else if(key == "blackknight" || key == "whiteknight")
name = key;
for(int i = 0; i < 2; i++)
//System.out.println(name+i);
String tempname = name+i;
Image piece = (Image)pieceList.get(new String(name));
ImageIcon pieces = new ImageIcon(piece);
piecet = new JLabel(pieces);
piecesOnBoard.put(new String(tempname), piecet);
if(!ht.containsKey(new String(key)))
ht.put(new String(key+0), new Integer(0));
else if(key == "blackbishop" || key == "whitebishop")
name = key;
for(int i = 0; i < 2; i++)
System.out.println(name+i);
String tempname = name+i;
Image piece = (Image)pieceList.get(new String(name));
System.out.println(piece.toString());
ImageIcon pieces = new ImageIcon(piece);
piecet = new JLabel(pieces);
piecesOnBoard.put(new String(tempname), piecet);
if(!ht.containsKey(new String(key)))
ht.put(new String(key+0), new Integer(0));
else if(key == "blackrook" || key == "whiterook")
name = key;
for(int i = 0; i < 2; i++)
System.out.println(name+i);
String tempname = name+i;
Image piece = (Image)pieceList.get(new String(name));
ImageIcon pieces = new ImageIcon(piece);
piecet = new JLabel(pieces);
piecesOnBoard.put(new String(tempname), piecet);
if(!ht.containsKey(new String(key)))
ht.put(new String(key+0), new Integer(0));
Hopefully this will format alright, but my question is, is that why is it giving me this error... it happens in the create multiples function(the last function in this code block) this is a jlayeredpane which is called by a JApplet. Any ideas on the loading? Its in the getImages() fuction.These are the lines it dies on.... the System.out.println(piece.toString()); precisely. I don't know if I am not getting the images from the directory right... or if I need to make sure this is in a JAR file or not.
{ name = key; for(int i = 0; i < 2; i++) { System.out.println(name+i); String tempname = name+i; Image piece = (Image)pieceList.get(new String(name)); System.out.println(piece.toString()); ImageIcon pieces = new ImageIcon(piece); piecet = new JLabel(pieces); piecesOnBoard.put(new String(tempname), piecet); } if(!ht.containsKey(new String(key))) { ht.put(new String(key+0), new Integer(0)); } -
Background image for a JApplet
Hi everybody.
I have a app with some textfields, buttons and some JLabels.
I want to put a image as background.
How can I do that?
Thanks in advance.JApplet (and JFrame and any root container) has a Container that it uses to hold everything else, its contentPane. I would create a JPanel and make it my applet's contentPane and then add everything to this contentPane. To show an image on the contentPane/JPanel, I'd simply Google Background image jpanel. I'd get and then read this: [http://faq.javaranch.com/java/BackgroundImageOnJPanel]
(I've actually bookmarked this page as it gets asked here so often). -
JApplet won't switch image??
Hi everyone...
My JApplet was supposed to display a new image when the sign up button is pressed..
But it doesn't.. Here take a look at my source code!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.applet.*;
public class JFrameApplet extends JApplet implements Runnable
private Thread th;
private Image icon;
Image background;
public void init()
background = getImage(getCodeBase(), "background.gif");
Container content = getContentPane();
content.setLayout(new FlowLayout());
JButton signUp = (new JButton("Sign Up"));
JButton logIn = (new JButton("Login"));
signUp.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
getIcon();
content.add(signUp);
content.add(logIn);
private void getIcon()
MediaTracker tracker = new MediaTracker(this);
icon = getImage(getCodeBase(), "icon.png");
tracker.addImage(icon, 1);
try
tracker.waitForAll();
catch(Exception exception)
System.out.println("Error displaying new image.");
private void getImages()
public void start()
th = new Thread(this);
th.start();
public void destroy()
th.stop();
public void run()
public void stop()
th.stop();
public void update(Graphics g)
public void paint(Graphics g)
g.drawImage(background, 0, 0, this);
}Wow thanks, the following code helped my out :)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.applet.*;
public class JFrameApplet extends JApplet implements Runnable
private Thread th;
Image background, icon;
public void init()
background = getImage(getCodeBase(), "background.gif");
Container content = getContentPane();
content.setLayout(new FlowLayout());
JButton signUp = (new JButton("Sign Up"));
JButton logIn = (new JButton("Login"));
signUp.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent evt)
icon = getImage(getCodeBase(), "icon.gif");
content.add(signUp);
content.add(logIn);
private void getImages()
public void start()
th = new Thread(this);
th.start();
public void destroy()
th.stop();
public void run()
public void stop()
th.stop();
public void update(Graphics g)
public void paint(Graphics g)
g.drawImage(background, 0, 0, this);
g.drawImage(icon, 0, 0, this);
}Here you are, 5 duke stars! -
JApplet Image Buttons not init().
I have created a JApplet where it contains image buttons. When I run the applet in a web page I get an error message, not inialised.
I have been informed that the reason is the image buttons. Does the getCodeBase() method form part of the solution and if so does anyone know how.
I have been going mad trying to find a solution.
ThanksI have created a JApplet where it contains image buttons. When I run the applet in a web page I get an error message, not inialised.
I have been informed that the reason is the image buttons. Does the getCodeBase() method form part of the solution and if so does anyone know how.
I have been going mad trying to find a solution.
Thanks -
Hi,
Is there a way to save me applet as an image (eps, gif, bmp, whatever)? I would like to have a button that will save the JApplet as an image. Thanks.
[email protected]Luckily for you, Java has created a Robot object which has a createScreenCapture method. Turning what it gives you into something useful is a little more difficult but not that much ...
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import java.awt.image.BufferedImage;
import java.awt.Robot;
import java.awt.Point;
import java.awt.Component;... Main class code ...
public static void saveComponentAsJPEG(Component cmp, String jpegfile) {
Rectangle d = cmp.getBounds();
try {
Robot r = new Robot();
Point p = cmp.getLocationOnScreen();
d.x = p.x;
d.y = p.y;
BufferedImage bi = r.createScreenCapture(d);
saveImageAsJPEG(bi, jpegfile);
catch (Exception e) { e.printStackTrace(); }
public static void saveImageAsJPEG(BufferedImage bi, String filename) {
try {
ByteArrayOutputStream boutstream = new ByteArrayOutputStream();
JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(boutstream);
enc.encode(bi);
FileOutputStream fimage = new FileOutputStream(new File(filename));
boutstream.writeTo(fimage);
fimage.close();
catch (Exception e) { System.out.println(e); }
}I think that should do it for you, I am using this code in a program I am writing currently and it seems to work for me, but I have to call the function using SwingUtilities.invokeLater() or else the display is always in need of repaint when the picture is taken.
Good luck.
Will -
I have a JApplet here:
http://www.jujubees.org/java_photo_album/photoAlbum.html
the code is coming along well but I have one major problem. The images seem to take for ever to download even with a high speed cable connection (so god only knows how long a dial up would take). What technique can I use to make sure the images are being cached in the web browser? Also is there a way to check and see if the browser has cached a certain image? If you want to see the code then I could post it.I have a JApplet here:
http://www.jujubees.org/java_photo_album/photoAlbum.htm
the code is coming along well but I have one major
problem. The images seem to take for ever to download
even with a high speed cable connection (so god only
knows how long a dial up would take). What technique
can I use to make sure the images are being cached in
the web browser? Also is there a way to check and see
if the browser has cached a certain image? If you want
to see the code then I could post it.Well you could check to see if the images are being cached by printing out the details of your images, byte size and so on. If you want the browser to cache all the images what you could do is feed the location of the images into the applet, with a parameter for instance, then create a thread that iterates over the images in the directory and loads them into a hashtable of some kind. So the rendering would be faster. Or put them into a .jar/.zip, would be faster. You don't have to wait for all the images to load to display the first one.
Unless you are manually coding the images in your code you can be fairly certain that the browser is not going to. Perhaps with advanced browsers like Opera, but even then, no.
See ya
Michael
Maybe you are looking for
-
I have used Pagemaker for 20 years and upgraded each time. I have had it on my desktop and used it extensively. Three months ago, I had my old computer stolen from my car. I tried to download my disk but the case which had the serial information prin
-
Ajax submit failed error message=403 Forbidden
This message is sometimes displayed at the ePrint center website when attempting to log in. I would like to give a few tips just in case you run into this error message on the site. The first thing I would try is clear your browser cache this someti
-
Adding a column in the MSS Approval view
What are the options for adding a column in the MSS approval view (CATS regular) ?
-
Jbo-26066 Error during rollback error
Hi All, I ve developed an application which runs fine 95% of the time..but few times it throws this exception. Im unable to find out the possible reason behind this. The exception does not point to any of my code. Pls help me on this.. Thanks, Sreera
-
Best ways to transfer files to network isolated VMs?
I'm looking at creating a DHCP scope and have some IP addresses that would be static for such items as routers, printers, etc. I've been told various ways depending on your point of view. I'm curious on what everyone's perspective is.For example, I h