Hello,

I'm creating a program that will be dealing with multiple objects that extend Applet and a JFrame that will be displaying them. I created a test that swiched off between two applets I made. While I was creating the test, I noticed some things and have few questions regarding Applet and JFrame.

My first test involved one new applet and one I created that was used by an html file. From that test I realized the web applet failed to run (null pointer exceptoin). Why would an applet that normally works on web, fail to run in a JFrame? Particularly fails when init() is called.

After working around the issue of the first test by creating a different applet, there was another thing I noticed, the applet was covered by the frame of the window. How do I correct this issue?

Another issue I noticed is that after the switch I would need to click on the applet before KeyListener would work. How do I work around this?

The last question I have is if the code below is a good way to go or if there's a better way?

here's the code for the making the swich...

public void keyReleased(KeyEvent e)
{
//Gg is one the applets
Gg g = new Gg();
g.addKeyListener(g);

g.setSize(300,300);

//ex is the JFrame
ex.add(g);
ex.remove(this);
ex.validate();

Recommended Answers

All 26 Replies

Ok I just figured out some of my problems, but I still can't figure out how to make 0,0 be corner of the showing applet. Does anyone know how get applet not to go into border of the window? Do I have to adjust everything or is there a simpler way?

Also in my program the user will be able to choose their controls. What listener will allow me to listen to any button press whether it be from keyboard, mouse, game pad, or joy stick?

YOu can get away with borders if you want.just look at the actionlistener interface in javadocs for keyborad and mouse event.

If I use actionlistener, where do I add it? There's no addActionListener in JFrame or applet.

Does anyone know how to get an applet to fit properly in a JFrame, such that it doesn't go into edges of the window?

Why on earth are you putting an Applet in a JFrame?

Well I got some of my issues out of the way, can someone now tell me how to keep the key listener on the applet after I switch from one applet to another? Also If I want to make the window transparent, how would I go about doing that?

Why I'm using applet:
Well first of all I'm not that experienced with java so I don't know what's the right way or the wrong way to do anything. The reason I did it that way is because I saw it done that way.

Second what I thought was going out of the borders, wasn't doing that. So that issue is out of the way.

Third I wanted to use multiple applets such that each represented an individual screen such that one would be the menu screen and so on.

Applets are typically only used for small programs embedded in web-pages. If you are developing a regular desktop Java app then you would use JFrames and JPanel sub-components. The individual screens that you describe could be either one, depending upon how many top-level windows you wish to have.

JPanels are not standalone top-level windows, but can be placed in any other container component, such as JFrame, JSplitPane, JScrollPane, JTabbedPane, etc. By developing smaller classes that extend JPanel, you can easily create "sub-forms" that can be placed into containers in any manner you chose.

This tutorial covers a lot of these things in detail:
http://java.sun.com/docs/books/tutorial/uiswing/index.html

Most everything that you have coded so far can probably be moved to a JPanel with only minimal effort. Anything in init() can probably be done in the constructor. Code in start() may be okay in the constructor or perhaps a public method, depending upon what that code is doing.

Thanks for the info Ezzaral.
Got any links on how to produce a UI that can be any shape or size (in other words, get whatever is behind the window and display it before anything else)? Or is there a way to get the background transparent and not just a dull grey?

Also what's the best way to create a program with a set fps? A new thread or through an action listener that listens to a timer?

So lets say I want a window in the shape of a circle, I need to have that gray undecorated square window to be transparent such that I can draw a circle such that it looks as though the window is in the shape of a circle. So is there a way to A, get what's displayed behind the window and display it or B, make the gray color be transparent.

Ah, okay, got it. No, there isn't a straight-forward way to make transparent frames like that. The following article discusses a way to hack that effect though through use of screen shots:
http://www.onjava.com/pub/a/onjava/excerpt/swinghks_hack41/index.html

Crap.... and its even bugy -_-....

I guess I'll just have to wait for Sun to develop one.

Anyway I'm having some trouble trying draw stuff and have components.
If want to not have the screen clear (turn gray) and display those component, how do I go about it?

So lets say I have a TextFeild, a JFrame, and a JPanel which the TextFeild goes into. I extend the JPanel and have main in it where I do the drawing with graphics. How do I go about it.

Your explanation isn't very clear. Which component do you want to customize the drawing code for? Are you wanting to custom paint the background on the panel, yet not affect the text field?

Are you wanting to custom paint the background on the panel, yet not affect the text field?

Yip

Also I don't want the screen to be cleared every time I change the back ground. So if I change the background, the background is drawn first then the textfeild. Basicaly there's going to be an action listener that will be changing the background over an interval of time.

If you just override paintComponent() for the JPanel, you shouldn't have any problem.

new JPanel(){
  public void paintComponent(Graphics g){
    paintPanel(g);
  }
};

Thanks
It even worked with paint.

The only issue I'm having now is I need JFrame to always listen to keyboard, but when I add a textfield it's listening only to the textfield. Also my program will be using the keyboard to navigate, so how do I select and deselect a component such that the arrow keys can be listened to and from there move from component to component?

I just swiched TextField for JTextFeild and only the back ground or the Jtextfield only depending on whether I override paint (background shows) or PaintComponent(jtextFeild shows).

EDIT:

Never mind, I just had PaintComponent and not paintComponent.

The only issue I'm having now is I need JFrame to always listen to keyboard, but when I add a textfield it's listening only to the textfield. Also my program will be using the keyboard to navigate, so how do I select and deselect a component such that the arrow keys can be listened to and from there move from component to component?

Add your key bindings to the JFrame itself like so

JRootPane root = frame.getRootPane();
root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
  KeyStroke.getKeyStroke(KeyEvent.VK_UP,0),"UpAction");

root.getActionMap().put("UpAction",new AbstractAction(){
    public void actionPerformed(java.awt.event.ActionEvent e){
        upAction();
    }
});

but how do I move from component to component, what's the method call to select and deselect a component?

Thanks

You sure have a lot of time to help people out with this stuff.

By the way Will an alpha based image slow me down when doing animation at 12 fps at a screen size close to the screen resolution?

Couldn't really say on that one. You'll just have to test it and tweak if needed. A lot of factors go into FPS besides just the resolution because most apps are doing more than simply blitting an image to the screen each cycle of the animation loop.

To keep painting as lean and responsive as possible, try to keep everything that does not directly relate to rendering out of your paintComponent() code. The paint methods can be called by many other things other than your loop, so put code that updates things or performs calculation in another method if possible and just keep the minimum about of code needed to redender the component in the paintComponent() method itself.

Hello Mr.UNOwen,

I have same problem and i need solution if u got that.

I am creating one applet and i draw one object on it but

I want a window of applet in the shape of the objct that i draw on window.
i need that window transparent such that I can draw object such that it looks as though the window is in the shape of
that object.So is there a way to get what's displayed behind the window and display it.

Thanks,
Ajay Patel

You obviously didn't read any of the links posted about that then, or you would have your answer. There are ways to "hack" that appearance and I posted a link to one article on it, but Java doesn't generically support transparent top-level windows or non-rectangular windows.

Hi Ezzaral,

ya,u r right. i got one link after that post.

http://www.onjava.com/pub/a/onjava/excerpt/swinghks_hack41/index.html?page=3

in this we take screenshot of and put it in background of our window.
and this process is continuosly work in thread.
ok it nice and some what help ful to me. but window is still not moving.

ok in one of the above post Mr.UNOwen's question was to change the shape of window.
i found one link 4 that.
plz check this.

http://www-106.ibm.com/developerworks/java/library/j-iframe/

Thanking you,
Ajay Patel

continue of above...post

in that example that i see the image.actaully i put it but its not work 4 me.

can u help me..i put my code here..

-----------------------------------
TransparentBackground.java
-----------------------------------


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/


package swingdemo;
import java.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


/**
*
* @author vinod
*/


public class TransparentBackground extends JComponent implements ComponentListener, WindowFocusListener,
Runnable,MouseListener {


private JFrame frame;
private Image background;
private long lastupdate = 0;
public boolean refreshRequested = true;


@Override
protected void processMouseEvent(MouseEvent e) {
JOptionPane.showMessageDialog(null, "processMouseEvent Called");
}


public TransparentBackground(JFrame frame) {
this.frame = frame;
updateBackground( );
frame.addComponentListener(this);
frame.addMouseListener(this);
frame.addWindowFocusListener(this);
new Thread(this).setPriority(Thread.MAX_PRIORITY);
new Thread(this).start( );
}


public void componentShown(ComponentEvent evt) {
// JOptionPane.showMessageDialog(null, "componentShown Data");
repaint( );
}
public void componentResized(ComponentEvent evt)
{
JOptionPane.showMessageDialog(null, "componentResized Called");
repaint( );
}
public void componentMoved(ComponentEvent evt)
{
JOptionPane.showMessageDialog(null, "componentMoved Called");
repaint( );
}
public void componentHidden(ComponentEvent evt)
{
// JOptionPane.showMessageDialog(null, "componentHidden Called");
}



public void windowGainedFocus(WindowEvent evt) { refresh( ); }
public void windowLostFocus(WindowEvent evt) { refresh( ); }



public void refresh( ) {
if(frame.isVisible( )) {
repaint( );
refreshRequested = true;
lastupdate = new Date( ).getTime( );
}
}


public void run( ) {
try {
while(true) {
Thread.sleep(250);
long now = new Date( ).getTime( );
if(refreshRequested &&
((now - lastupdate) > 1000)) {
if(frame.isVisible( )) {
Point location = frame.getLocation( );
frame.setVisible(false);
updateBackground( );
frame.setVisible(true);
frame.setLocation(location);
refresh( );
}
lastupdate = now;
refreshRequested = false;
}
}
} catch (Exception ex) {
//p(ex.toString( ));
ex.printStackTrace( );
}
}


public void updateBackground( ) {
try {
Robot rbt = new Robot( );
Toolkit tk = Toolkit.getDefaultToolkit( );
Dimension dim = tk.getScreenSize( );
background = rbt.createScreenCapture(
new Rectangle(0,0,(int)dim.getWidth( ),
(int)dim.getHeight( )));
} catch (Exception ex) {
//p(ex.toString( ));
ex.printStackTrace( );
}
}


public void paintComponent(Graphics g) {
Point pos = this.getLocationOnScreen( );
Point offset = new Point(-pos.x,-pos.y);
g.drawImage(background,offset.x,offset.y,null);
}


public void mouseClicked(MouseEvent e) {
if(e.getButton()==MouseEvent.BUTTON3)
{
JOptionPane.showMessageDialog(null, "mouseClicked Called - 3");
}
if(e.getButton()==MouseEvent.BUTTON1)
{
JOptionPane.showMessageDialog(null, "mouseClicked Called - 1");
}
throw new UnsupportedOperationException("Not supported yet.");
}


public void mousePressed(MouseEvent e) {
// throw new UnsupportedOperationException("Not supported yet.");
}


public void mouseReleased(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}


public void mouseEntered(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}


public void mouseExited(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}



}


-----------------------
Trans.java
-----------------------



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/


package swingdemo;


import java.util.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;



/**
*
* @author vinod
*/
public class Trans {
public static void main(String[] args) {
JFrame frame = new JFrame("Transparent Window");
frame.setUndecorated(true);


TransparentBackground bg = new TransparentBackground(frame);
//bg.snapBackground( );
bg.setLayout(new BorderLayout( ));


JPanel panel = new JPanel( ) {
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
Image img = new ImageIcon("3250.png").getImage( );
g.drawImage(img,0,0,null);
}
};


panel.setOpaque(false);


bg.add("Center",panel);


frame.getContentPane( ).add("Center",bg);
frame.pack( );
frame.setSize(200,200);
frame.setLocation(500,500);
frame.setVisible(true);
}


}

please put any one image file inplace of 3250.png and check is it working or not?

Thank you,
Ajay Patel

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.