Jcomponent vs jframe

hey all, im kinda new in java programming but i like this language alot, i was trying to look online for some GUI code, well i found a lot of sample swing code, some of them extends JComponent while the other extends JFrame...
what exactly is the difference, please ellaborate and be clear as much as you can...
thnx in advance

A JFrame is a top-level window. Usually, your GUI application will have one single JFrame.
JComponent is the base-class for all widgets, such as JButton, JLabel, JTree, etc. You add your widgets to a container, e.g. a JPanel (which also derives from JComponent btw), which at some point is added, directly or indirectly, to your top-level frame.
code, some of them extends JComponent while the other
extends JFrame...It's not very often that you actually need to extend a JComponent, and there is almost never a good reason to extend JFrame.

Similar Messages

  • Drawing with double buffering to a JFrame

    I want to create a simple JFrame and draw stuff to it via Graphic object using double buffering.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering. ( 'cause i read somewhere that swing components automaticly use double buffering ). And is this the righ approuch ( or whatever it's spelled ) ?

    I want to create a simple JFrame and draw stuff to it
    Don't do that.
    If you want to do custom rendering then use JPanel or JComponent, not JFrame.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering.
    No.
    You're also painting outside the standard paint cycle, which is a Bad Idea.
    So, essentially, everything your suggesting is the wrong way to go about things.
    In its most simple form, double buffering works something like this, though there are a whole load of subtleties to consider (such as component resizing for a start)
    public class Foo extends JComponent
        private BufferedImage image = null;
        protected void paintComponent(Graphics g)
            if (image != null)
                image = createImage(getWidth(), getHeight());
                paintBuffer(ig);
            g.drawImage(image, 0, 0, this);
        private void paintBuffer()
            Graphics ig = image.getGraphics();
            // do the rendering
            ig.dispose();
    }

  • Problems with setFullScreenWindow() - crash to desktop

    Hello everyone,
    I am trying to make my application have an option to go "full screen" (ie without decoration and start menu etc). Everything was going well, untill I tested a bit more thoroughly with dual moniters (which I have to support) I made a moniter chooser and everything - it wall works apart from these random crashes that happen.
    The following is a small exmple that shows whats going on (at least it does on my computer):
    import java.awt.BorderLayout;
    import java.awt.GraphicsEnvironment;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    public class Test extends JComponent
         private JFrame f1;
         private JFrame f2;
         private JLabel l;
         public Test()
              f2 = new JFrame("test");
              f2.setVisible(true);
              f2.setSize(200,200);
              f2.addKeyListener(new EscapeOutKeyListener());
              l = new JLabel("Press ALT+F4 to exit fullscreen.", SwingConstants.CENTER);
              f2.add(l, BorderLayout.CENTER);
         public static void main(String[] args)
              Test t = new Test();
         class EscapeOutKeyListener implements KeyListener
              @Override
              public void keyPressed(KeyEvent e)
                   if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
                        GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(null);
                        f1.setVisible(false);
                        f2.add(l, BorderLayout.CENTER);
                        f2.validate();
                   if (e.getKeyCode() == KeyEvent.VK_SPACE)
                        f1 = new JFrame("test");
                        f1.setUndecorated(true);
                        f1.setVisible(true);
                        f1.setSize(200,200);
                        f1.setResizable(false);
                        f1.addKeyListener(new EscapeOutKeyListener());
                         f1.add(l);
                         GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(f1);
              @Override
              public void keyReleased(KeyEvent arg0){}
              @Override
              public void keyTyped(KeyEvent arg0){}
    }The best way of re-producing it I have found is opening the application, pressing "space" (go fullscreen) press "escape" (cancel full screen) then move the window from one moniter to the next. The crash I get is:
    # A fatal error has been detected by the Java Runtime Environment:
    # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x6d0b6ad0, pid=18340, tid=17800
    # JRE version: 6.0_21-b07
    # Java VM: Java HotSpot(TM) Client VM (17.0-b17 mixed mode, sharing windows-x86 )
    # Problematic frame:
    # C [awt.dll+0xb6ad0]
    # An error report file with more information is saved as:
    # C:\Users\tofuser\scworkspace\subclipsejava\hs_err_pid18340.log
    # If you would like to submit a bug report, please visit:
    # http://java.sun.com/webapps/bugreport/crash.jsp
    # The crash happened outside the Java Virtual Machine in native code.
    # See problematic frame for where to report the bug.
    I hope someone can help!
    Thanks
    Edit: I't isn't happening very often with my example program, it happens prety much every time with my main one. It took about 10 tries of maximizing, minimizing and moving from one moniter to the other to get it to happen...

    I've spent so long trying to find an answer to this, as soon as I post it I work it out! (though most times that happens but I work it out while writing the thread, nothing like organising things into questions to spot mistakes!)
    I tried adding the launching/destroying full screen to the event dispatch thread (below if anyone finds this and doesnt know what I mean):
    SwingUtilities.invokeLater(new Runnable(){
        @Override
            public void run()
                //do the full screen stuff here
    });and it has not happened since! At least posting it might help others that come accross this problem.
    Thanks anyway, even though no one probably saw the post ^_^

  • Embedding JavaFX v1.2 Scene's in Swing

    Before I start... SUN DOES NOT SUPPORT THIS AND IT IS LIKELY TO CHANGE... hopefully we get official support in a future release, please :)
    +"Note: We also recognize the need for the inverse (embedding a JavaFX scene into a Swing app), however that is not supported with 1.2 as it requires a more formal mechanism for manipulating JavaFX objects from Java code. The structure of these JavaFX objects is a moving target (for some very good reasons) and we're not ready to lock that down (yet). However,as with most software, this can be hacked (see Rich & Jasper's hack on Josh's blog) but know that you are laying compatibility down on the tracks if you go there. "+ Source: http://weblogs.java.net/blog/aim/archive/2009/06/insiders_guide.html
    But if you really really want this now read on.
    After a lengthy investigation and some help from others (including the jfxtra's project) here is how to Embed a JavaFX scene in your Swing application:
    First, start your java application with javafx and not java! This will fix any potential class path issues and really does solve a lot of issues you will have 'patching' the JVM with JavaFX (if that is even possible). JavaFX will happily run a Java project (with the JVM) even if there is not one JavaFX class in your project.
    Next, you need to create a Java Interface for your JavaFX object to implement:
    package mix.javastuff;
    * This is a Java Interface that your JavaFX class should implement.
    * This will define how Java will interact with your JavaFX class.
    * @author ahhughes
    public interface TextDisplay {
        public void setText(String text);
    }Next, you need to create your JavaFX object... it must extend Scene and you are to provide any interaction with Java you will need to implement a java interface:
    package mix.javafxstuff;
    import mix.javastuff.TextDisplay;
    import javafx.scene.Scene;
    import javafx.scene.text.Text;
    import javafx.scene.text.Font;
    import javafx.scene.effect.Reflection;
    import javafx.scene.text.TextOrigin;
    * Here is a very simple scene, that implements a java interface
    * That allows Java (or JavaFX) to setText on the Scene's content.
    public class TextDisplayJavaFXScene extends Scene , TextDisplay {
        override public function setText(text:String):Void{
            content = Text {
                    font : Font {size: 44}
                    x: 0, y: 0
                    textOrigin: TextOrigin.TOP
                    content: text
                    effect: Reflection {}
    }Finally, you need to use some reflection and some under the hood magic to get your JavaFX object and wrap in in a SwingScene (which just so happens to extend JComponent).
    package mix.javastuff;
    import com.sun.javafx.tk.swing.SwingScene;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javafx.reflect.FXClassType;
    import javafx.reflect.FXContext;
    import javafx.reflect.FXFunctionMember;
    import javafx.reflect.FXLocal;
    import javafx.reflect.FXLocal.ObjectValue;
    import javafx.scene.Scene;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    * Example of how to inject JavaFX into your Swing app.
    public class Main {
        private static final FXLocal.Context context = FXLocal.getContext();
        private static TextDisplay textDisplayJavaFXScene;// javafx scene & java interface
        public static void main(String[] args) {
            //Get the JavaFX Object, that has 'extends Scene, SomeJavaInterface'
         FXClassType instanceType = context.findClass("mix.javafxstuff.TextDisplayJavaFXScene");
         ObjectValue objectInstance = (ObjectValue) instanceType.newInstance();
         textDisplayJavaFXScene = (TextDisplay) objectInstance.asObject();
            //Wrap this in a SwingScene using refection
            JComponent textDisplayJavaFXSwingScene = sceneInstanceToJComponent((Scene)textDisplayJavaFXScene);
            //Now let's show the JComponent+JavaFXScene in a simple Swing App.
            createSimpleSwingApp(textDisplayJavaFXSwingScene);
         * This method wraps the Scene with a JComponent. This is what you can add
         * to your Swing application.
         * @param scene the JavaFX object that extends javafx.scene.Scene.
         * @return the javafx.scene.Scene wrapped by a JComponent.
         public static JComponent sceneInstanceToJComponent(Scene scene) {
             FXClassType sceneType = FXContext.getInstance().findClass("javafx.scene.Scene");
             ObjectValue obj = FXLocal.getContext().mirrorOf(scene);
             FXFunctionMember getPeer = sceneType.getFunction("impl_getPeer");
             FXLocal.ObjectValue peer = (ObjectValue) getPeer.invoke(obj);
             SwingScene swingScene = (SwingScene)peer.asObject();
             return (JComponent) swingScene.scenePanel;
         * OK, this method is just to show you this in action.... the real stuff
         * you are interested is in the methods above.
         * @param javaFXTextDisplaySwingScene
        private static void createSimpleSwingApp(JComponent javaFXTextDisplaySwingScene){
             JFrame frame = new JFrame();
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setSize(500,500);
             frame.setAlwaysOnTop(true);
              JPanel panel = new JPanel();
              panel.setLayout(new FlowLayout());
            //create a swing interface to interact with textDisplayJavaFXScene.setText()
            final JTextField textInputField = new JTextField("Set THIS Text!");
              panel.add(textInputField);
              JButton button = new JButton("Send to JavaFX!");
              panel.add(button);
              button.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        textDisplayJavaFXScene.setText(textInputField.getText());
            //add the JavaFX SwingScene to the Swing's JPanel
             panel.add(javaFXTextDisplaySwingScene);
            //display the swing app
             frame.add(panel);
             frame.setVisible(true);
    }That's it!

    morningstar wrote:
    You can refer to this article for how to embeded javaFX scene into SWING:
    [JavaFX Scene embedded in SWING Window|http://www.javafxgame.com/javafx-scene-swing-java/]
    [http://www.javafxgame.com/javafx-scene-swing-java/|http://www.javafxgame.com/javafx-scene-swing-java/]
    Hi morningstar, this article is good and it too helped me out A LOT! It shows how to embed a JavaFX scene in swing but doesn't show you how to interact with JavaFX objects FROM your Java/Swing code. Wrapping the JavaFX node in a SwingScene doesn't offer a way for the Java/Swing code to interact with the underlying JavaFX objects.
    How can you set the text in the JavaFX Text node from the Java/Swing code in the linked article? You can't, all you can do is have the JavaFX objects reference BACK to public static fields in your Java code (not the best):
    Java Class:
    public class JavaFXToSwingTest extends JFrame {
        public static JTextField tf = new JTextField("JavaFX for SWING");
        //other code
    JavaFX Class:
        text = JavaFXToSwingTest.tf.getText();  On the other hand, the code in the first post exposes the JavaFX objects through java interfaces as well as wrapping them in a SwingScene. This means that you can do YourJavaFXObject.setText("Blah"); from inside your Java/Swing code, rather handy! :)
    Edited by: AndrewHughes on Jul 27, 2009 12:25 AM

  • Help!! How to put more than one JComponent on one JFrame

    Hi!
    I'm having a big problem. I'm trying to create an animation that is composed of various images. In one JComponent I have an animation of a sprite moving left and right on the screen(Which works right now). On another JComponent I have a still image that I want to put somewhere on the screen. For some reason I can only see what I add last to the JFrame. Can somebody help me? Thanks
    P.S I don't want to have all the images on the same JComponent. I want to have different classes for different images or animations. You can get the sprites I use from here http://www.flickr.com/photos/59719950@N00/
    import java.awt.Color;
    import javax.swing.JFrame;
    public class ScreenSaverViewer
         public static void main(String[] args)
         Character characterGame = new Character();
         basketballHoop hoopz = new basketballHoop();
         //Clock clock = new Clock();
         JFrame app = new JFrame("Screensaver");
            app.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            app.getContentPane().add(hoopz);
            //app.getContentPane().add(clock);
            app.getContentPane().add(characterGame);
            app.setSize (450,450);
            app.setBackground (Color.black);
            app.setLocation (300,200);
            app.setVisible (true);
            characterGame.run();
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import java.util.ArrayList;
    public class Character extends JComponent
        BufferedImage backbuffer;
        int sliderSpeed = 1;
        int sliderX = 1;
        int sliderY = 1;
        int direction = 1;
        Image myImg = Toolkit.getDefaultToolkit().getImage ("/home/climatewarrior/Sprites_gabriel/muneco_0.png");
        private Image fetchImage(int x)
             ArrayList<Image> images = new ArrayList<Image>();
             for (int i = 0; i < 4; i++)
                  images.add(i, Toolkit.getDefaultToolkit().getImage ("/home/climatewarrior/Sprites_gabriel/muneco_" + i + ".png"));
             return images.get(x);
        private void displayGUI()
            int appWidth = getWidth();
            int appHeight = getHeight();
            backbuffer = (BufferedImage) createImage (appWidth, appHeight);
            Graphics2D g2 = backbuffer.createGraphics();
            g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.drawImage (myImg, sliderX, sliderY, getWidth() / 2 * direction, getHeight() / 2, this);
            g2.dispose();
            repaint();
        public void paintComponent (Graphics g)
            super.paintComponent(g);
            if (backbuffer == null)
                 displayGUI();
            g.drawImage(backbuffer, 0, 0, this);
       public void run ()
            while(true)
                   sliderX = -(getWidth() - getWidth()/2);
                   sliderY = getHeight()/3;
                   int x = 0;
                   int increment = 1;
                   do
                   sliderX += increment;
                   if (sliderX % 30 == 0)
                             myImg = fetchImage(x);
                             direction = -1;
                             x++;
                             if (x == 4)
                             x = 0;
                   displayGUI();
                   } while (sliderX <= getWidth() + (getWidth() - getWidth()/2));
                   do
                   sliderX -= increment;
                   if (sliderX % 30 == 0)
                        myImg = fetchImage(x);
                        direction = 1;
                        x++;
                        if (x == 4)
                             x = 0;
                   displayGUI();
                   } while (sliderX >= -(getWidth() - getWidth()/2));
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class Clock extends JComponent
        BufferedImage backbuffer;
        Image myImg = Toolkit.getDefaultToolkit().getImage("/home/climatewarrior/Sprites_gabriel/score_board.png");
        public void paintComponent (Graphics g)
             g.drawImage(myImg, 250, 100, getWidth()/2, getHeight()/3, null);
             super.paintComponent (g);
             repaint();
    }

    Here's a file I had hanging around. It's about as simple as they come, hopefully not too simple!
    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.JFrame;
    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 static final String DUKE_FILE = "http://java.sun.com/" +
                  "products/plugin/images/duke.wave.med.gif";
        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(DUKE_FILE));
            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
            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();
        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();
    }

  • Why isn't my JComponent being painted onto JFrame

    I am using the Card class from Sun's enum examples. The Card class extends JComponent and each card has an Image field storing its graphic. My problem is that when getContentPane().add(card) is called, it doesn't show up on the JFrame. I have overridden paint() in both the Card class and JFrame to see if either will work, but they haven't. I'd appreciate any help.
    import java.util.List;
    import java.util.LinkedList;
    import java.awt.*;
    import javax.swing.JComponent;
    public class Card extends Component {
        public enum Rank {
            DEUCE (2),
            THREE (3),
            FOUR (4),
            FIVE (5),
            SIX (6),
            SEVEN (7),
            EIGHT (8),
            NINE (9),
            TEN (10),
            JACK (10),
            QUEEN (10),
            KING (10),
            ACE (11, 1);
    private final int value1, value2;
        Rank (int val) {
        this.value1 = val;
        this.value2 = 0;
        Rank (int val, int val2) {
        this.value1 = val;
        this.value2 = val2;
    public int val1() { return this.value1; }
    public int val2() { return this.value2; }
        public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
        private final Rank rank;
        private final Suit suit;
        private Image image;
        private static final List<Card> protoDeck = new LinkedList<Card>();
        public Card(Rank rank, Suit suit, String img) {
            super();
            this.rank = rank;
            this.suit = suit;
            this.image = Toolkit.getDefaultToolkit().createImage(img);
    // is the below method implementation right?
    public void paint(Graphics g) {
    boolean x = g.drawImage(image, 0, 0, null);
        public Rank rank() { return rank; }
        public Suit suit() { return suit; }
        public Image getImg() { return this.image; }
        public String toString() { return rank + " of " + suit; } 
        // Initialize prototype deck
        static {
            for (Suit suit : Suit.values()) {
                for (Rank rank : Rank.values()) {
                    String imgPath = "C:/Documents and Settings/Administrator/Desktop/java/BlackJack/" + rank + suit + ".jpg";
                    protoDeck.add(new Card(rank, suit, imgPath));
        public static LinkedList<Card> newDeck() {
            return new LinkedList<Card>(protoDeck); // Return copy of prototype deck
    import java.util.LinkedList;
    import java.util.Collections;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BlackJack extends JFrame {
    private LinkedList<Card> deck;
    private LinkedList<Card> plCrds;
    private Card card;
    public BlackJack() {
    super();
    plCrds = new LinkedList<Card>();
    setSize(400, 500);
    deck = Card.newDeck();
    card = dealPl();
    getContentPane().add(card);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
    public static void main(String[] args) {
    BlackJack bj = new BlackJack();
    public void paint(Graphics g) {
    g.drawImage(card.getImg(), 5, 5, this);
    private Card dealPl() {
    Card c = deck.remove();
    plCrds.add(c);
    return c;
         }

    Never override the painting methods of your top level contaier (ie. JFrame).
    Custom painting is done by overriding the paintComponent(...) method of JComponent or JPanel.
    So because you are using the Card class in a Swing application you need to extend JComponent as suggested above and override paintComponent(...), not paint(...);
    Also why do you think you even need to override any paint method to draw the cards. Just add you Cards to a panel using a null layout. Read the Swing tutorial on layout managers, specifically the section on "Absolute Positioning";
    http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html
    Better yet use the appropriate combination of layout managers to get your desired look so you don't need to worry about a null layout.

  • Need to convert JApplet to JFrame

    I need to write code for where I have 60 balls bouncing around inside a window. The client will then be able to select a button and it will pull out a ball with the number 1-60 written on it. The user will be able to do this up to 7 times. Each time it is done the past numbers that have already appeared can not reappear. What I am stuck on right now is geting my balls into a JFrame. Can anyone give advice or show how to. I currently have my 60 balls running in a JApplet. Here is the JAVA code and the HTML code. Thanks!
    Here is the JAVA code
    import java.awt.*;
    import java.applet.*;
    import java.util.*;
    import javax.swing.*;
    class CollideBall{
    int width, height;
    public static final int diameter=20;
    //coordinates and value of increment
    double x, y, xinc, yinc, coll_x, coll_y;
    boolean collide;
    Color color;
    Graphics g;
    Rectangle r;
    //the constructor
    public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c){
    width=w;
    height=h;
    this.x=x;
    this.y=y;
    this.xinc=xinc;
    this.yinc=yinc;
    color=c;
    r=new Rectangle(150,80,130,90);
    public double getCenterX() {return x+diameter/2;}
    public double getCenterY() {return y+diameter/2;}
    public void alterRect(int x, int y, int w, int h){
    r.setLocation(x,y);
    r.setSize(w,h);
    public void move(){
    if (collide){  
    double xvect=coll_x-getCenterX();
    double yvect=coll_y-getCenterY();
    if((xinc>0 && xvect>0) || (xinc<0 && xvect<0))
    xinc=-xinc;
    if((yinc>0 && yvect>0) || (yinc<0 && yvect<0))
    yinc=-yinc;
    collide=false;
    x+=xinc;
    y+=yinc;
    //when the ball bumps against a boundary, it bounces off
    if(x<6 || x>width-diameter){
    xinc=-xinc;
    x+=xinc;
    if(y<6 || y>height-diameter){
    yinc=-yinc;
    y+=yinc;
    //cast ball coordinates to integers
    int x=(int)this.x;
    int y=(int)this.y;
    //bounce off the obstacle
    //left border
    if(x>r.x-diameter&&x<r.x-diameter+7&&xinc>0&&y>r.y-diameter&&y<r.y+r.height){
    xinc=-xinc;
    x+=xinc;
    //right border
    if(x<r.x+r.width&&x>r.x+r.width-7&&xinc<0&&y>r.y-diameter&&y<r.y+r.height){
    xinc=-xinc;
    x+=xinc;
    //upper border
    if(y>r.y-diameter&&y<r.y-diameter+7&&yinc>0&&x>r.x-diameter&&x<r.x+r.width){
    yinc=-yinc;
    y+=yinc;
    //bottom border
    if(y<r.y+r.height&&y>r.y+r.height-7&&yinc<0&&x>r.x-diameter&&x<r.x+r.width){
    yinc=-yinc;
    y+=yinc;
    public void hit(CollideBall b){
    if(!collide){
    coll_x=b.getCenterX();
    coll_y=b.getCenterY();
    collide=true;
    public void paint(Graphics gr){
    g=gr;
    g.setColor(color);
    //the coordinates in fillOval have to be int, so we cast
    //explicitly from double to int
    g.fillOval((int)x,(int)y,diameter,diameter);
    g.setColor(Color.white);
    g.drawArc((int)x,(int)y,diameter,diameter,45,180);
    g.setColor(Color.darkGray);
    g.drawArc((int)x,(int)y,diameter,diameter,225,180);
    public class BouncingBalls extends Applet implements Runnable {
    Thread runner;
    Image Buffer;
    Graphics gBuffer;
    CollideBall ball[];
    //Obstacle o;
    //how many balls?
    static final int MAX=60;
    boolean intro=true,drag,shiftW,shiftN,shiftE,shiftS;
    boolean shiftNW,shiftSW,shiftNE,shiftSE;
    int xtemp,ytemp,startx,starty;
    int west, north, east, south;
    public void init() {  
    Buffer=createImage(getSize().width,getSize().height);
    gBuffer=Buffer.getGraphics();
    ball=new CollideBall[MAX];
    int w=getSize().width-5;
    int h=getSize().height-5;
    //our balls have different start coordinates, increment values
    //(speed, direction) and colors
    for (int i = 0;i<60;i++){
    ball=new CollideBall(w,h,50+i,20+i,1.5,2.0,Color.white);
    /* ball[1]=new CollideBall(w,h,60,210,2.0,-3.0,Color.red);
    ball[2]=new CollideBall(w,h,15,70,-2.0,-2.5,Color.pink);
    ball[3]=new CollideBall(w,h,150,30,-2.7,-2.0,Color.cyan);
    ball[4]=new CollideBall(w,h,210,30,2.2,-3.5,Color.magenta);
    ball[5]=new CollideBall(w,h,360,170,2.2,-1.5,Color.yellow);
    ball[6]=new CollideBall(w,h,210,180,-1.2,-2.5,Color.blue);
    ball[7]=new CollideBall(w,h,330,30,-2.2,-1.8,Color.green);
    ball[8]=new CollideBall(w,h,180,220,-2.2,-1.8,Color.black);
    ball[9]=new CollideBall(w,h,330,130,-2.2,-1.8,Color.gray);
    ball[10]=new CollideBall(w,h,330,10,-2.1,-2.0,Color.gray);
    ball[11]=new CollideBall(w,h,220,230,-1.2,-1.8,Color.gray);
    ball[12]=new CollideBall(w,h,230,60,-2.3,-2.5,Color.gray);
    ball[13]=new CollideBall(w,h,320,230,-2.2,-1.8,Color.gray);
    ball[14]=new CollideBall(w,h,130,300,-2.7,-3.0,Color.gray);
    ball[15]=new CollideBall(w,h,210,90,-2.0,-1.8,Color.gray);*/
    public void start(){
    if (runner == null) {
    runner = new Thread (this);
    runner.start();
    /* public void stop(){
    if (runner != null) {
    runner.stop();
    runner = null;
    public void run(){
    while(true) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    try {runner.sleep(15);}
    catch (Exception e) { }
    //move our balls around
    for(int i=0;i<MAX;i++)
    ball[i].move();
    handleCollision();
    repaint();
    boolean collide(CollideBall b1, CollideBall b2){
    double wx=b1.getCenterX()-b2.getCenterX();
    double wy=b1.getCenterY()-b2.getCenterY();
    //we calculate the distance between the centers two
    //colliding balls (theorem of Pythagoras)
    double distance=Math.sqrt(wx*wx+wy*wy);
    if(distance<b1.diameter)
    return true;
    return false;
    private void handleCollision()
    //we iterate through all the balls, checking for collision
    for(int i=0;i<MAX;i++)
    for(int j=0;j<MAX;j++)
    if(i!=j)
    if(collide(ball[i], ball[j]))
    ball[i].hit(ball[j]);
    ball[j].hit(ball[i]);
    public void update(Graphics g)
    paint(g);
    public void paint(Graphics g)
    gBuffer.setColor(Color.lightGray);
    gBuffer.fillRect(0,0,getSize().width,getSize().height);
    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
    //paint our balls
    for(int i=0;i<MAX;i++)
    ball[i].paint(gBuffer);
    g.drawImage (Buffer,0,0, this);
    Here is the HTML code
    <html>
    <body bgcolor="gray">
    <br><br>
    <div align="center">
    <applet code="BouncingBalls.class" width="1000" height="650"></applet>
    </div>
    </body>
    </html>

    In the future, Swing related questions should be posted in the Swing forum.
    First you need to convert your custom painting. This is done by overriding the paintComponent() method of JComponent or JPanel. Read the Swing tutorial on [Custom Painting|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html].
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Problem with KeyAdapter and JButtons in a Jframe

    yes hi
    i have searched almost most of the threads here but nothing
    am trying to make my frame accepts keypress and also have some button on the frame here is the code and thank you for the all the help
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPg extends JFrame implements ActionListener
                private int width;
                private int hight;
                public    JPanel north;
                public    JPanel se;
                public    JButton start;
                public    JButton quit;
                public    Screen s;//a Jpanel
                public    KeyStrokeHandler x;
        public RPg() {
               init();
               setTitle("RPG");
               setSize(width,hight);
               setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               setResizable(false);
               setVisible(true);
               x=new KeyStrokeHandler();
             addKeyListener(x);
             public void init() {
               north=new JPanel();
               Container cp = getContentPane();
               s=new Screen();
               this.width=s.width;
               this.hight=s.hight+60;
              start=new JButton("START");
                  start.addActionListener(this);
              quit=new JButton("QUIT");
                  quit.addActionListener(this);
              north.setBackground(Color.DARK_GRAY);
              north.setLayout(new FlowLayout());
              north.add(start);
              north.add(quit);
              cp.add(north, BorderLayout.NORTH);
              cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPg rpg = new RPg();
       public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
       class KeyStrokeHandler extends KeyAdapter {
               public void keyTyped(KeyEvent ke) {}
               public void keyPressed(KeyEvent ke){
                  int keyCode = ke.getKeyCode();
                  if ((keyCode == KeyEvent.VK_M)){
                     System.out.println("it works");
               public void keyReleased(KeyEvent ke){}

    Use the 'tab' key to navigate through 'contentPane > start > quit' focus cycle. 'M' key works when focus is on contentPane (which it is on first showing). See tutorial pages on 'Using Key Bindings' and 'Focus Subsystem' for more.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPG extends JFrame implements ActionListener {
        private int width;
        private int hight;
        public JPanel north;
        public JPanel se;
        public JButton start;
        public JButton quit;
        public Screen s;    //a Jpanel
        public RPG() {
            init();
            setTitle("RPG");
            setSize(width,hight);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setResizable(false);
            setVisible(true);
        public void init() {
            north=new JPanel();
            Container cp = getContentPane();
            registerKeys((JComponent)cp);
            s=new Screen();
            this.width=s.width;
            this.hight=s.hight+60;
            start=new JButton("START");
                start.addActionListener(this);
            quit=new JButton("QUIT");
                quit.addActionListener(this);
            north.setBackground(Color.DARK_GRAY);
            north.setLayout(new FlowLayout());
            north.add(start);
            north.add(quit);
            cp.add(north, BorderLayout.NORTH);
            cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPG rpg = new RPG();
        public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
        private void registerKeys(JComponent jc)
            jc.getInputMap().put(KeyStroke.getKeyStroke("M"), "M");
            jc.getActionMap().put("M", mAction);
        Action mAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("it works");
    class Screen extends JPanel {
        int width, hight;
        public Screen() {
            width = 300;
            hight = 300;
            setBackground(Color.pink);
    }

  • Problem with Background image and JFrame

    Hi there!
    I've the following problem:
    I created a JFrame with an integrated JPanel. In this JFrame I display a background image. Therefore I've used my own contentPane:
    public class MContentPane extends JComponent{
    private Image backgroundImage = null;
    public MContentPane() {
    super();
    * Returns the background image
    * @return Background image
    public Image getBackgroundImage() {
    return backgroundImage;
    * Sets the background image
    * @param backgroundImage Background image
    public void setBackgroundImage(Image backgroundImage) {
    this.backgroundImage = backgroundImage;
    * Overrides the painting to display a background image
    protected void paintComponent(Graphics g) {
    if (isOpaque()) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    if (backgroundImage != null) {
    g.drawImage(backgroundImage,0,0,this);
    super.paintComponent(g);
    Now the background image displays correct. But as soon as I click on some combobox that is placed within the integrated JPanel I see fractals of the opened combobox on the background. When I minimize
    the Frame they disappear. Sometimes though I get also some fractals when resizing the JFrame.
    It seems there is some problem with the redrawing of the background e.g. it doesn't get redrawn as often as it should be!?
    Could anyone give me some hint, on how to achieve a clear background after clicking some combobox?
    Thx in advance

    I still prefer using a border to draw a background image:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.border.*;
    public class CentredBackgroundBorder implements Border {
        private final BufferedImage image;
        public CentredBackgroundBorder(BufferedImage image) {
            this.image = image;
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            int x0 = x + (width-image.getWidth())/2;
            int y0 = y + (height-image.getHeight())/2;
            g. drawImage(image, x0, y0, null);
        public Insets getBorderInsets(Component c) {
            return new Insets(0,0,0,0);
        public boolean isBorderOpaque() {
            return true;
    }And here is a demo where I load the background image asynchronously, so that I can launch the GUI before the image is done loading. Warning: you may find the image disturbing...
    import java.awt.*;
    import java.io.*;
    import java.net.URL;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class BackgroundBorderExample {
        public static void main(String[] args) throws IOException {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame f = new JFrame("BackgroundBorderExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextArea area = new JTextArea(24,80);
            area.setForeground(Color.WHITE);
            area.setOpaque(false);
            area.read(new FileReader(new File("BackgroundBorderExample.java")), null);
            final JScrollPane sp = new JScrollPane(area);
            sp.setBackground(Color.BLACK);
            sp.getViewport().setOpaque(false);
            f.getContentPane().add(sp);
            f.setSize(600,400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            String url = "http://today.java.net/jag/bio/JagHeadshot.jpg";
            final Border bkgrnd = new CentredBackgroundBorder(ImageIO.read(new URL(url)));
            Runnable r = new Runnable() {
                public void run() {
                    sp.setViewportBorder(bkgrnd);
                    sp.repaint();
            SwingUtilities.invokeLater(r);
    }

  • Problem displaying CheckboxGroup on JFrame

    I was recently assigned the task of creating exams. I am trying to create a CheckboxGroup in a class that was passed the Graphics2D tool. This code compiles with no errors when I call it's method:
    setLayout(new GridLayout(1, 5));
              CheckboxGroup cbg = new CheckboxGroup();
              add(new Checkbox("Never", cbg, false));
              add(new Checkbox("Almost Never", cbg, false));
              add(new Checkbox("Sometimes", cbg, false));
              add(new Checkbox("Almost All The Time", cbg, false));
              add(new Checkbox("All The Time", cbg, false));
    but nothing displays on my JFrame, I tried to draw it with this line(g2 is my Graphics2D tool):
    g2.draw(cbg);
    but I get an error when compiling that says draw doesn't work. Am I totally off-track with this or is there a simple Graphics2D method that I use to draw this CheckboxGroup?

    hiwa: Thanks for the tip, I won't mix those libraries anymore
    pete: Here is all of my code so far sorry it's sloppy, I'm just getting back into coding after one semester of Intro to Computer Science using Java almost a year ago::/*this class has main function**************************************************/
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    public class PDS_Questionnaire
         public static void main(String[] args)
              //declare JFrame window dimensions
              int WIDTH = 500;
              int HEIGHT = 400;
              //create JFrame
              JFrame frame = new JFrame();
              frame.setSize(HEIGHT, WIDTH);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              //create object of painter class to install onto frame
              ScoreCard survey = new ScoreCard();
              //add object to frame and set visible
              frame.add(survey);
              frame.setVisible(true);
    /*********************end of class***************************************/
    /****************************new class**********************************/
    //this class is the JFrame painter, it initiates the Graphics2D class then passes the
    //Graphics object to PDS_Scorer so that the PDS_Scorer class can draw on the patientsCard
    import javax.swing.JComponent;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class ScoreCard extends JComponent
         public ScoreCard()
         public void paintComponent(Graphics g)
              //recover Graphics2D
              Graphics2D g2 = (Graphics2D) g;
                    //create another class and pass the Graphics2D tool
              PDS_Scorer patientsCard = new PDS_Scorer(g2);
                    //call method to draw the check boxes
              patientsCard.drawCheckBoxes();
    /*********************end of class***************************************/
    /****************************new class**********************************/
    import javax.swing.JComponent;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.Checkbox;
    import java.awt.CheckboxGroup;
    public class PDS_Scorer extends JComponent
         public PDS_Scorer(Graphics2D gTwo)
              g2 = gTwo;
         public void partA_Scorer()
         public void partB_Scorer()
         public void partC_Scorer()
         public void partD_Scorer()
         public void partE_Scorer()
         public void partF_Scorer()
         public void drawCheckBoxes()
    //           draw3DRect(int x, int y, int width, int height, boolean raised)
    //      Draws a 3-D highlighted outline of the specified rectangle.
              g2.draw3DRect(10, 10, 10, 10, true);   //this works
              setLayout(new GridLayout(1, 5));
              CheckboxGroup cbg = new CheckboxGroup();
              add(new Checkbox("Never", cbg, false));
              add(new Checkbox("Almost Never", cbg, false));
              add(new Checkbox("Sometimes", cbg, false));
              add(new Checkbox("Almost All The Time", cbg, false));
              add(new Checkbox("All The Time", cbg, false));
            //g2.drawString("One Lazy Fox", 22.5, 55.5);
         private Graphics2D g2;
    }

  • Trying to scroll a JComponent with JScrollPane but can't do it. :(

    Hi, what im trying to do seems to be simple but I gave up after trying the whole day and I beg you guys help.
    I created a JComponent that is my map ( the map consists only in squared cells ). but the map might be too big for the screen, so I want to be able to scroll it. If the map is smaller than the screen,
    everything works perfect, i just add the map to the frame container and it shows perfect. But if I add the map to the ScrollPane and them add the ScrollPane to the container, it doesnt work.
    below is the code for both classes Map and the MainWindow. Thanks in advance
    package main;
    import java.awt.Color;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowStateListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    public class MainWindow implements WindowStateListener {
         private JFrame frame;
         private static MainWindow instance = null;
         private MenuBar menu;
         public Map map = new Map();
         public JScrollPane Scroller =
              new JScrollPane( map,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         public JViewport viewport = new JViewport();
         private MainWindow(int width, int height) {
              frame = new JFrame("Editor de Cen�rios v1.0");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setVisible(true);
              menu = MenuBar.createMenuBar();
              JFrame.setDefaultLookAndFeelDecorated(false);
              frame.setJMenuBar(menu.create());
              frame.setBackground(Color.WHITE);
              frame.getContentPane().setBackground(Color.WHITE);
                                    // HERE IS THE PROBLEM, THIS DOESNT WORKS   <---------------------------------------------------------------------------------------
              frame.getContentPane().add(Scroller);
              frame.addWindowStateListener(this);
    public static MainWindow createMainWindow(int width, int height)
         if(instance == null)
              instance = new MainWindow(width,height);
              return instance;               
         else
              return instance;
    public static MainWindow returnMainWindow()
         return instance;
    public static void main(String[] args) {
         MainWindow mWindow = createMainWindow(800,600);
    public JFrame getFrame() {
         return frame;
    public Map getMap(){
         return map;
    @Override
    public void windowStateChanged(WindowEvent arg0) {
         map.repaint();
    package main;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import javax.swing.Scrollable;
    public class Map extends JComponent  implements Scrollable{
         private Cell [] mapCells;
         private String mapPixels;
         private String mapAltura;
         private String mapLargura;
         public void createMap(String pixels , String altura, String largura)
              mapPixels = pixels;
              mapAltura = altura;
              mapLargura = largura;
              int cells = Integer.parseInt(altura) * Integer.parseInt(largura);
              mapCells = new Cell[cells];
              //MainWindow.returnMainWindow().getFrame().getContentPane().add(this);
              Graphics2D grafico = (Graphics2D)getGraphics();
              for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                   mapCells[i] = new Cell( horiz, vert,Integer.parseInt(mapPixels));
                   MainWindow.returnMainWindow().getFrame().getContentPane().add(mapCells);
                   grafico.draw(mapCells[i].r);
                   horiz = horiz + Integer.parseInt(mapPixels);
                   if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                        horiz = 0;
                        vert = vert + Integer.parseInt(mapPixels);
              repaint();
         @Override
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              System.out.println("entrou");
              Graphics2D g2d = (Graphics2D)g;
              if(mapCells !=null)
                   for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                        g2d.draw(mapCells[i].r);
                        horiz = horiz + Integer.parseInt(mapPixels);
                        if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                             horiz = 0;
                             vert = vert + Integer.parseInt(mapPixels);
         @Override
         public Dimension getPreferredScrollableViewportSize() {
              return super.getPreferredSize();
         @Override
         public int getScrollableBlockIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;
         @Override
         public boolean getScrollableTracksViewportHeight() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public boolean getScrollableTracksViewportWidth() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public int getScrollableUnitIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;

    Im so sorry Darryl here are the other 3 classes
    package main;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.filechooser.FileNameExtensionFilter;
    public class MenuActions {
         public void newMap(){
              final JTextField pixels = new JTextField(10);
              final JTextField hCells = new JTextField(10);
              final JTextField wCells = new JTextField(10);
              JButton btnOk = new JButton("OK");
              final JFrame frame = new JFrame("Escolher dimens�es do mapa");
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
              btnOk.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
              String txtPixels = pixels.getText();
              String hTxtCells = hCells.getText();
              String wTxtCells = wCells.getText();
              frame.dispose();
              MainWindow.returnMainWindow().map.createMap(txtPixels,hTxtCells,wTxtCells);         
              frame.getContentPane().add(new JLabel("N�mero de pixels em cada c�lula:"));
              frame.getContentPane().add(pixels);
              frame.getContentPane().add(new JLabel("Altura do mapa (em c�lulas):"));
              frame.getContentPane().add(hCells);
              frame.getContentPane().add(new JLabel("Largura do mapa (em c�lulas):"));
              frame.getContentPane().add(wCells);
              frame.getContentPane().add(btnOk);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(300, 165);
              frame.setResizable(false);
             frame.setVisible(true);
         public Map openMap (){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showOpenDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: manipular o mapa aberto
              return new Map();          
         public void save(){
         public void saveAs(){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showSaveDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: Salvar o mapa aberto
         public void exit(){
              System.exit(0);          
         public void copy(){
         public void paste(){
    package main;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    public class MenuBar implements ActionListener{
         private JMenuBar menuBar;
         private final Color color = new Color(250,255,245);
         private String []menuNames = {"Arquivo","Editar"};
         private JMenu []menus = new JMenu[menuNames.length];
         private String []arquivoMenuItemNames = {"Novo","Abrir", "Salvar","Salvar Como...","Sair" };
         private KeyStroke []arquivoMenuItemHotkeys = {KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_A,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.SHIFT_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.ALT_MASK)};
         private JMenuItem []arquivoMenuItens = new JMenuItem[arquivoMenuItemNames.length];
         private String []editarMenuItemNames = {"Copiar","Colar"};
         private KeyStroke []editarMenuItemHotKeys = {KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK),
                                                                 KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK)};
         private JMenuItem[]editarMenuItens = new JMenuItem[editarMenuItemNames.length];
         private static MenuBar instance = null;
         public JMenuItem lastAction;
         private MenuBar()
         public static MenuBar createMenuBar()
              if(instance == null)
                   instance = new MenuBar();
                   return instance;                    
              else
                   return instance;
         public JMenuBar create()
              //cria a barra de menu
              menuBar = new JMenuBar();
              //adiciona items a barra de menu
              for(int i=0; i < menuNames.length ; i++)
                   menus[i] = new JMenu(menuNames);
                   menuBar.add(menus[i]);
              //seta a hotkey da barra como F10
              menus[0].setMnemonic(KeyEvent.VK_F10);
              //adiciona items ao menu arquivo
              for(int i=0; i < arquivoMenuItemNames.length ; i++)
                   arquivoMenuItens[i] = new JMenuItem(arquivoMenuItemNames[i]);
                   arquivoMenuItens[i].setAccelerator(arquivoMenuItemHotkeys[i]);
                   menus[0].add(arquivoMenuItens[i]);
                   arquivoMenuItens[i].setBackground(color);
                   arquivoMenuItens[i].addActionListener(this);
              //adiciona items ao menu editar
              for(int i=0; i < editarMenuItemNames.length ; i++)
                   editarMenuItens[i] = new JMenuItem(editarMenuItemNames[i]);
                   editarMenuItens[i].setAccelerator(editarMenuItemHotKeys[i]);
                   menus[1].add(editarMenuItens[i]);
                   editarMenuItens[i].setBackground(color);
                   editarMenuItens[i].addActionListener(this);
              menuBar.setBackground(color);
              return menuBar;                    
         @Override
         public void actionPerformed(ActionEvent e) {
              lastAction = (JMenuItem) e.getSource();
              MenuActions action = new MenuActions();
              if(lastAction.getText().equals("Novo"))
                   action.newMap();
              else if(lastAction.getText().equals("Abrir"))
                   action.openMap();
              else if(lastAction.getText().equals("Salvar"))
                   action.save();               
              else if(lastAction.getText().equals("Salvar Como..."))
                   action.saveAs();               
              else if(lastAction.getText().equals("Sair"))
                   action.exit();               
              else if(lastAction.getText().equals("Copiar"))
                   action.copy();               
              else if(lastAction.getText().equals("Colar"))
                   action.paste();               
    package main;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    public class Cell extends JComponent{
         public float presSub = 0;
         public double errPressInfer = 0.02;
         public double errPressSup = 0.02;
         public float profundidade = 1;
         public Rectangle2D r ;
         public Cell(double x, double y, double pixel)
              r = new Rectangle2D.Double(x,y,pixel,pixel);          
    Edited by: xnunes on May 3, 2008 6:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • New to java: how to replace an image extending a JComponent?

    Hi,
    I'm new to Java and I have a question about Swing:
    I have a class called ActiveImage (entends JComponent, implements     MouseMotionListener, MouseWheelListener) which takes an Image and displays it. It also receives some mouse events for zooming and moving it around. I display it in a JFrame using:
    content = getContentPane();
    content.setLayout(new BorderLayout());
    image = toolkit.getImage (filename);
    ActiveImage activeImage = new ActiveImage(image);
    content.add(activeImage, BorderLayout.CENTER);
    (This code is in a class extending JFrame.)
    This works fine. However, this JFrame also contains a JToolbar with two buttons. Now when I click one of them, I want to replace the image with another one. I've tried removing it and creating a new ActiveImage to add that to content, but that didn't work very well. remove() resulted in a NullPointerException.
    My question: what would be the best way to go about this?
    Many thanks for any help,
    Diederick de Vries

    B.T.W., this is the trace:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at ActiveImage.ActiveImageFrame$1.actionPerformed(ActiveImageFrame.java:60)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
            at java.awt.Component.processMouseEvent(Component.java:5488)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
            at java.awt.Component.processEvent(Component.java:5253)
            at java.awt.Container.processEvent(Container.java:1966)
            at java.awt.Component.dispatchEventImpl(Component.java:3955)
            at java.awt.Container.dispatchEventImpl(Container.java:2024)
            at java.awt.Component.dispatchEvent(Component.java:3803)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
            at java.awt.Container.dispatchEventImpl(Container.java:2010)
            at java.awt.Window.dispatchEventImpl(Window.java:1766)
            at java.awt.Component.dispatchEvent(Component.java:3803)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)Just before this, it says "button clicked". The function that calls the setImage() goes:
    theButton.addActionListener (new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
              System.out.println("button clicked");
              activeImage.setImage(image);
    });Reading the trace, I would think that the exception has something to do with this last code, since it stops there (line 60 is the setImage()). If the setImage() function itself was where the fault was, wouldn't the trace end there?
    I'm really at a loss here ... :-(

  • How to add background color in JFrame

    I have three classes, Car, CarComponent, and CarViewer. I don't know how to code background color. Do I add it to CarViewer where the JFrame is or CarComponent?
    CarViewer:
    import javax.swing.JFrame;
    public class CarViewer
       public static void main(String[] args)
          JFrame frame = new JFrame();
          frame.setSize(300, 400);
          frame.setTitle("Two cars");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          CarComponent component = new CarComponent();
          frame.add(component);
          frame.setVisible(true);
    }CarComponent
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JComponent;
       This component draws two car shapes.
    public class CarComponent extends JComponent
       public void paintComponent(Graphics g)
          Graphics2D g2 = (Graphics2D) g;
          Car car1 = new Car(0, 0);
          int x = getWidth() - 60;
          int y = getHeight() - 30;
          Car car2 = new Car(x, y);
          car1.draw(g2);
          car2.draw(g2);     
    }

    What JSG said, plus I really don't think it's a good idea to instantiate new Car objects in a paintComponent override. Painting methods should be restricted to painting activities, as a matter of principle.
    One alternative is to construct your Car instances in a separate method and call repaint() when done; another is to provide a Car method say moveTo(int x, int y) OR refactor the draw(Graphics g) method of Car to draw(Graphics g, int x, int y). Both these suggest that you maintain the Car references as instance fields of CarViewer.
    In future (not this time), Swing related questions should be posted in the [Swing forum|http://forums.sun.com/forum.jspa?forumID=57]
    db

  • A Grow Box for a JFrame

    I am this >||< (font size 8) close to getting this JGrowBox class thing to work exactly the way I want it to, and then, everybody can have a nice little grow box thingie to "attatch" to their JFrames. Ooooh.
    I have three problems. First, if the user tries to resize the frame normally (grabs the very corner of the JFrame) then the JFrame resizes in its normal ugly way, without repainting its components (which means that the JGrowBox thing just stays where it is, which looks stupid.) Second, if the user grabs the actual JGrowBox the way you can with all other stupid Windoze programs, the JFrame flickers horribly, and the CPU goes nuts. Third, I use static byte array representations of the GIF images. This is kinda lame. I'm guessing all the cool Java widgets use Java2D somehow.
    The dimensions used for the customized JComponent are specific to the arrangment of the rest of the layout. The JGrowBox is actually in the BorderLayout.EAST of a 18-pixel tall JPanel "status bar" thingie, which is in the BorderLayout.SOUTH of the contentPane. I didn't feel like going through the hassle of getting the thing to be universally positioned at the bottom-right of the parent JFrame, regardless of layout.
    The images are just a 16x16 screen captures of the Windows 2000 and Windows XP grow boxes, respectively, with the window grey replaced with black and black set as the transparent color, and then sort of converted into a static byte array. I suppose it might be a bit more space-saving to just use Java2D to draw out all the pixels and stuff, but I hate doing that kinda crap.
    Code:
    * JGrowBox.java
    * Created on July 28, 2005, 1:54 PM
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * @author [email protected]
    public class JGrowBox
        extends JComponent {
        // the associated JFrame window parent of the grow box
        private JFrame parent = null;
        // where the user clicked the mouse to resize using the grow box
        private Point p0 = null;
        // the image of the grow box thinga-ma-jigger
        private Image image = null;
        /** Creates a new instance of JGrowBox */
        public JGrowBox(final JFrame parent) {
            this.parent = parent;
            // get the name of the operating system
            String OS_NAME = System.getProperty("os.name");
            // anybody got GIFs for KDE or GNOME?
            if (OS_NAME.equals("Windows 2000")) {
                image = new ImageIcon(WINDOWS_2000_GROW_BOX.BYTES).getImage();
            else if (OS_NAME.equals("Windows XP")) {
                image = new ImageIcon(WINDOWS_XP_GROW_BOX.BYTES).getImage();
            // this stuff is specific to a given arrangement
            setSize(new Dimension(18, 15));
            setPreferredSize(new Dimension(18, 15));
            setMaximumSize(new Dimension(18, 15));
            setMinimumSize(new Dimension(18, 15));
            setFocusable(false);
            // getting the first mouseClick and changing the cursor and stuff
            addMouseListener(new MouseAdapter() {
                public void mouseEntered(MouseEvent e) {
                    parent.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
                public void mouseExited(MouseEvent e) {
                    parent.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                public void mousePressed(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        p0 = e.getPoint();
                public void mouseReleased(MouseEvent e) {
                    if (!contains(e.getPoint())) {
                        parent.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            // when the user drags the mouse, resize the parent JFrame (ugly!)
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseDragged(MouseEvent e) {
                    Point p1 = e.getPoint();
                    parent.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
                    Rectangle bounds = parent.getBounds();
                    int x = bounds.width + (p1.x - p0.x);
                    int y = bounds.height + (p1.y - p0.y);
                    Point p2 = new Point(x, y);
                    int xMax = Toolkit.getDefaultToolkit().getScreenSize().width;
                    parent.setSize(Math.min(p2.x, xMax), p2.y);
            // hide the grow icon when the parent window is maximized
            parent.addComponentListener(new ComponentAdapter() {
                public void componentResized(ComponentEvent e) {
                    if (parent.getExtendedState() == JFrame.MAXIMIZED_BOTH) {
                        setVisible(false);
                    else {
                        setVisible(true);
        public void paintComponent(Graphics g) {
            if (image != null) {
                g.drawImage(image, 3, 3, this);
        public boolean contains(Point p) {
            Rectangle r = getBounds();
            return (p.x >= 0 && p.x <= r.width &&
                    p.y >= 0 && p.y <= r.height);
    class WINDOWS_2000_GROW_BOX {
        public final static byte[] BYTES = {
      71,   73,   70,   56,   57,   97,   16,    0,   16,    0,   -9,    0,    0,    0,    0,    0,
      -1,   -1,   -1,  -44,  -48,  -56, -110, -116, -106, -100, -102,  -69,    0,    0,   -1,    0,
       0, -128, -118, -103,  -35,  115,  126,  -96,   10,   36,  106,   10,   35,  103,    9,   32,
      95,   11,   37,  107,   13,   39,  109,   35,   54,  106,   10,   36,  105,    8,   27,   77,
      12,   39,  108,   14,   40,  109,   15,   42,  110,   15,   41,  110,   16,   42,  111,   17,
      44,  112,   17,   43,  112,   18,   45,  113,   19,   46,  114,   20,   47,  115,   15,   35,
      84,   21,   48,  116,   21,   48,  115,   22,   49,  116,   23,   50,  117,   24,   51,  118,
      25,   52,  119,   27,   54,  120,   28,   55,  121,   29,   56,  122,   30,   57,  123,   31,
      58,  124,   32,   59,  125,   34,   61,  126,   36,   63, -128,   37,   64, -127,   38,   65,
    -126,   30,   58,  123,   32,   60,  125,   33,   61,  126,   34,   62,  127,   39,   67, -125,
      41,   70, -123,   40,   68, -125,   41,   69, -124,   42,   70, -123,   43,   71, -122,   44,
      72, -121,   45,   74, -120,   45,   73, -120,   46,   75, -119,   47,   75, -118,   48,   77,
    -117,   49,   78, -116,   48,   76, -118,   50,   79, -115,   51,   80, -115,   52,   81, -114,
      53,   82, -113,   54,   83, -112,   54,   83, -113,   55,   84, -111,   56,   85, -110,   56,
      85, -111,   57,   86, -110,   58,   87, -109,   59,   88, -108,   60,   89, -107,   61,   91,
    -106,   61,   90, -107,   62,   91, -106,   63,   93, -104,   63,   92, -105,   64,   93, -104,
      65,   94, -103,   66,   95, -102,   67,   96, -101,   68,   98, -100,   69,   99,  -99,   68,
      97, -101,   70,  100,  -99,   72,  102,  -97,   71,  101,  -98,   73,  104,  -96,   73,  103,
    -96,   74,  104,  -95,   75,  105,  -94,   76,  107,  -93,   77,  108,  -92,   77,  107,  -92,
      76,  106,  -94,   78,  109,  -91,   79,  110,  -91,   80,  111,  -90,   82,  113,  -88,   81,
    112,  -89,   83,  114,  -87,   84,  115,  -86,   85,  116,  -85,   87,  118,  -84,   89,  120,
    -82,   88,  119,  -83,   90,  121,  -81,   89,  120,  -83,  105, -115,  -53,   91,  123,  -80,
      93,  125,  -78,   92,  123,  -80,   91,  122,  -81,   93,  124,  -79,   95,  126,  -77,   94,
    125,  -78,   96,  127,  -76,   97, -128,  -76,   98, -126,  -75,   98, -127,  -75,  100, -125,
    -73,  100, -124,  -73,   99, -126,  -74,  101, -123,  -72,  103, -121,  -70,  102, -123,  -71,
    102, -122,  -71,  105, -119,  -68,  104, -120,  -69,  107, -117,  -67,  106, -118,  -68,   31,
      59,  102,   36,   64,  104,  107, -116,  -66,  108, -115,  -66,  110, -113,  -64,  109, -114,
    -65,  112, -111,  -62,  111, -112,  -63,  113, -110,  -61,  112, -112,  -63,  114, -109,  -61,
    116, -107,  -59,  115, -109,  -60,  115, -108,  -60,  118, -105,  -57,  117, -106,  -58,  120,
    -103,  -55,  119, -104,  -56,  121, -102,  -54,  119, -104,  -57,  122, -101,  -54,  121, -102,
    -55,  124,  -99,  -52,  123, -100,  -53,  125,  -98,  -51, -117,  -83,  -32,   72,  124,  -61,
    126,  -96,  -50,  124,  -99,  -53,  126,  -97,  -51, -127,  -93,  -48, -128,  -95,  -49, -125,
    -91,  -46, -126,  -92,  -47, -123,  -89,  -44, -124,  -90,  -45, -121,  -87,  -42, -122,  -88,
    -43, -118,  -84,  -40,  106,  -98,  -36,   97, -119,  -72, -123,  -85,  -38, -120,  -85,  -41,
    -117,  -82,  -39, -119,  -84,  -41, -114,  -80,  -37, -115,  -81,  -38, -116,  -82,  -39, -112,
    -77,  -35, -113,  -79,  -36, -110,  -75,  -33, -111,  -77,  -34, -111,  -76,  -34, -107,  -72,
    -30, -108,  -73,  -31, -109,  -74,  -32, -106,  -71,  -30, -107,  -72,  -31, -104,  -69,  -28,
    -105,  -70,  -29, -102,  -67,  -26, -103,  -68,  -27,  109,  -93,  -34, -100,  -65,  -25, -101,
    -66,  -26, -102,  -67,  -27,  -97,  -61,  -22,  -98,  -63,  -23,  -98,  -62,  -23,  -99,  -64,
    -24,  -95,  -59,  -20,  -96,  -61,  -21,  -93,  -57,  -18,  -95,  -60,  -21,  -93,  -58,  -19,
    -97,  -73,  -46,  -95,  -72,  -46,   45,   88, -126,   74,  122,  -87,  -94,  -58,  -20,  -91,
    -55,  -17,  -90,  -54,  -16,  -70,  -52,  -34,   78,  -99,  -29,   74, -114,  -51,  109,  -71,
      -9,  -85,  -52,  -25, -124,  -81,  -47,   65, -115,  -62,  124,  -78,  -40,  -86,  -43,  -12,
    -77,  -63,  -53,  105, -127, -113,   67,  -98,  -51,   73,  -86,  -38,  103,  -74,  -33,   77,
    -70,  -21,  104,  -57,  -23,  -72,  -27,  -13, -127,  -45,  -23, -104,  -33,  -13,  -61,  -18,
      -6, -111,  -36,  -16, -101,  -49,  -37, -101,  -34,  -25,  127,  -47,  -37,  -85,  -27,  -40,
    -111,  -28,  -65,  -99,  -21,  -57,    0, -128,    0,  -48,   -8,  -51,   -1,   -1,    0, -128,
    -128,    0,  -69,  -73,  -97,  -83,  -99,  105,  123,  110,   81,  -87,  -91, -100,   -1,    0,
       0, -128,    0,    0, -110, -118, -118, -128, -128, -128,   64,   64,   64,   33,   -7,    4,
       1,    0,    0,    0,    0,   44,    0,    0,    0,    0,   16,    0,   16,    0,    0,    8,
      59,    0,    1,    8,   28,   72,  -80,  -96,  -63, -125,    8,   19,    6,   72,   88,   48,
    -128,   63, -122,    3,   29,   62, -124,   40,   17,   34, -128, -118,   11,   21,   -6,  123,
    -24,   80,   35,  -57, -115,    8,   49, -126,   60,   40, -110,  -93,  -63, -110,   23,   39,
      70,    4, -119,  114,  -27,  -57, -105,   22,   99,   50,   12,    8,    0,   59
    class WINDOWS_XP_GROW_BOX {
        public final static byte[] BYTES = {
      71,   73,   70,   56,   57,   97,   16,    0,   16,    0,   -9,    0,    0,   -8,  -70,   43,
    -45,  -94,  -97,    0,   90,  -20,  -39,  -39,  -40,    2,  106,   -2,  -26,  111,   82,  113,
    111,  100,  -11,  -11,  -15,  -14,  -14,  -18,  121,  -98,  -66,  -52,  -51,  -53, -111, -103,
    -48,  111,  114,  -78,  -83,  -80,  -45,  -13,  -21,  -76,  -30,  -36,  -53,  -74,  -57,   -8,
       0,    0,    0,    1,  -79,    3,  -39,  -30,   -7,  -98,  -74,  -41,  -36,   10,   25,   73,
    124,  -10,   -2,   -5,  -11,  -32,   77,   47,    0,   75,  -30,  -91,  -90,  -91,  -28,  -24,
      -8,  101,  -79,   -8,   53,  112,  -12,   83, -118,   -9, -110,  -44,   -8,  -84,  -88, -103,
       1,   19, -117,   62, -106,   -1,  -17,  -19,  -34,    3,  101,  -15,   33, -105,  -76,  -82,
    -70,  -19,  -77,  -14,   -5,   -7,  -56,   76,    0,   90,  -12,  -15,  -17,  -30,  -44,  -37,
      -8,  120,  -56,  -21,   20,   72,  -69,    0,  -98,  -57,    0,   60,  116,  -65,  -63,  -65,
       1,   68,  -48,    1,  -37,    0,   81,  -90,   -8,  -74,  123,    0,  -28,  -28, -109,  -51,
    -42,   -7,  -59,  -59,  -59,   -8, -103,  116, -105,  -78,  -17,  -97,  -95,  -98, -122, -119,
    -65,  -10,  -84,   76,   75,   75,   74,    1,   67,  -49, -122, -126, -122,    3,  113,   -1,
       8,   85,  -35,  104, -107,  -11, -100, -103, -100,  -33,  -33,  -35,    0,   30,  -95,  -86,
      47,   10,  -20,  -23,  -40,  -38,  -43,  -61,   -7,   -7,   -7,  -35,  -75,  -59,   44,   44,
      43,  -17,  -18,  -13,   43, -112,   -1,    0,   61,  -36,   98,   98,   98,  -63,  -59,  -27,
      -3,  -49,  108,    6,   44,  -86,  -45,  -59,  -80,   -2,   -3,   -6,  -28,  -27,  -28,   50,
    106,  -63,  -79,  -77,  -80,  -61,  -49,   -7,   85,  -68,  -44,  -16,  -45,  -18,   35,   89,
    111, -104,  -49,  -52,   53,  -84,  -56,  -86,  -85,  -69,    0,   88,  -26, -113, -115, -114,
      65, -110,  -89,   74,  -83,   96,  -70,  -70,    0,  -77,  118, -111,   -5,  -17,  -41,  -14,
    -13,   -8,  -19,  -21,  -26,   21, -124,  -24,  -45,  -41,  -19,    0,   72,  -15,  124,  121,
    119,  -94,  -98, -105,   22,  106,  -18,  -28,  -12,   -5,  -21,  -52,  -67,    6, -124,   92,
      -4,  -36, -111,    0,   85,  -22,  -99, -106,  -74,  -54, -114,   82,    0,   83,  -31,   97,
    -85,  -70,  -37,  -35,  117,  -19,  -28,  -58,   -5,   -9,  -12,  120,  -72,  -53,   18,  -92,
    -55,   -1,   -1,   -1,   81,  -22,   70, -112,   -7, -123,    7,   49,  -39,  105,   40,   19,
    -11,   -4,   -5,   -5,  -10,  -20,  -72,   94,  108,    3,   54,  -66,  -71,  -71,  -70,  120,
    -84, -121,    1,   97,  -21,    8,   49,  -39,  -24,  -25,  -25,  -55,  -49,  -22,  -11,  -13,
    -27,   -5,  -62,   59,   32, -122,   -2,    0,   54,  -21,    7,  120,  -92,  105, -107,  -52,
      36,  106,  -11,  -20,  -20,  -18,   -5,  -10,  -25,   34,  120,   -7,    0,   25,  -49,  -69,
    -67,  -36,   27,   94,  -27,   80, -102, -100,  -23,  -70,   83,  -21, -124,   89,    2,  107,
    -12,   80,  -80,  -90,  106, -114,  -96,   44,   89,  -60,    1,  100,   -7,    0,   81,  -27,
      -8,   -7,   -3,  -46,  -61,  -37,    0,   38,  -59,  -72,  -76,  -94,  -25,  -31,  -37,   39,
      96,  -27,   -6,  -63,   14,   -4,  -13,   -3, -109,  -92,  -73,    0,   38,  -45,   41, -103,
    -56,   27,   90,  -15,  -59,  -39,  127,  -74,  -67,  -68,   23,   85,  -33,   15,   92,  -25,
      10,  102,  -12,   -2,  -20,  -22,  -23,  -26,  -33,    3,   62,  -56,    6,   77,  -42,  -16,
    -16,  -21,    4,   84,  -25,  -24,  -27,  -45,   -4,   -4,   -5,    0,   55,  -45,  -96,  -64,
      43,    0,   85,  -27,   -1,  -17,  -53,  -33,  -28,  -50,    6,   88,  -28,  -31,  -26,  -24,
       0,   96,   -8,    0,   84,  -29,    0,  101,   -3,   -9,  -17,  -25,    0,   96,   -4,  -57,
    -53,   45,   -2,   -5,  -18,   -2,   -2,   -2,  -64,  -70,  -84,   63,   64,   61,  -11,  -12,
    -36,  -48,  -44,   80,  -69,  -85,  -66,  -60,  -58,   30,    0,  123,    2,    1,  114,  -34,
      -5,   -5,  -27, -110, -111, -107,   -9,  -21,  -32,  -97, -105, -127,   -6,  -23,   78,   -7,
    -26,   96,   58, -104,  -26,  -46,  -45,  -46,   42, -107,  -22,   -4,   -4,   -1,   -1,   -1,
    -83, -112,   -1,   -1,   50, -119,   -3,   32,   45,   52,   17,   20,   18,  108,  108,  108,
    -40,  -68, -113,   73, -123,  -43,   33, -115,  -34,  -15,  -14,  -23,   70,  -87, -109,  -13,
    -29,  -30,   21,  126,  -32,    3,  104,   -6,   -3,   -2,   -2,  -65,  -36,  -57,   21,  111,
      -9,   -1,   -2,   -3,   37,  -20,   32,   17,   78,  -33,  -21,  -24,  -32,   11,  104,   -9,
      14,   80,  -19,   -8,   -4,   -3,   -2,   -5,   -5,  -42,  -48,  -59,  -11,  -11,  -22,  -48,
    -33, -107, -122, -112,  105,  112,   89, -118,  -21,  -24,  -40,  126,  -92,  -14,  -97,  -96,
    -53,  -33,  -62,  -24,  -49,  -79,   59,  127,  109,   76,    7,   79,  -22,   33,   -7,    4,
       1,    0,    0,   17,    0,   44,    0,    0,    0,    0,   16,    0,   16,    0,    0,    8,
      61,    0,   35,    8,   28,   72,  -80,  -96,  -63, -125,    8,   19,   42,   36,   72, -118,
    -44,  -62, -127,   13,   -7,   60,   20,  -56,   71,  -30,  -60, -123,   13,    5,  102,   76,
      24,   49,   66,  -57, -124,   21,   41,   90,  -68,   88,  112,  -93,   73, -121,   37,   73,
      73,  -20,   -8, -111,   96,  -56,    8,   47,   95, -110, -100,   25,   33,   32,    0,   59
    }

    Yes, <expletive deleted>, I know what Google is.You need to calm down.I was perfectly calm. You're the one saying "Oh, but maybe you don't know what a "google" is.", which intended or not, sounds like you're calling me a jackass for not looking it up myself. Nevermind the fact that you said in the post before that that you didn't even know what it was called. So why should I assume that searching the web for "grow box" is going go give me any results at all that have to do with what you're trying to do?
    Hmm, perhaps you are just being argumentative, and
    wasting my time, but I'll assume that there are
    enough people out there like you who don't understand
    what the purpose of that doohickey in the southeast
    corner of a window is to make responding to your
    questions worth my time. I'm not doing it to waste your time. I'm quite sure I've never seen what you linked to on an application before. At least not like what that link showed. If you had said, for example, like Internet Explorer has that little larger box in the lower right corner which acts as a larger handle for window resizing, then I might have understood you from the start.
    By the way, are you
    suggesting by your question that it is perhaps
    unnecessary to fulfill the expectations of the end
    user with respect to the graphical user interface of
    a Java program, just because the given defacto Java
    component already has very nearly the bare minimum
    functionality expected of a comparable gui component
    that can be found in any other relatively advanced
    development kit?I would expect that a frame-like container component that supports manual resizing by the user would supply some location to click to initiate that resize. How is up to the component.
    Okay, so why would you need a handle to resize the
    frame?
    Reason #1: Because it aids the user in resizing the
    window. It's a bigger, albeit not by much, area on
    the screen for which the user can aim for in the
    mouse movement action to "grab" onto a portion of the
    current window in order to resize it, reducing the
    amount of time wasted on window arrangement.As mentioned above, if something like what IE has, or Netscape or FireFox has in the lower right, then fine.
    Reason #2: Because I'll bet you dollars to donuts
    that the web browser you are using right now to view
    this rapidly decaying topic has one. Shouldn't your
    program be at least as good as, say,
    IExploder? Why not at least try to make your
    Java program seem like it didn't just fall off the
    Swing turnip truck?I wouldn't use the terms "at least as good as" and IE in the same sentence. But that's just me. But as I mentioned above, I don't think you were clear on what you were talking about.
    You started by saying "grow box" like this was some common name for something assuming everyone would know what you were talking about. Then when asked, you admitted you didn't know what it was really called, which as mentioned, I think precludes one from "googling" that term, as the results, IMO, can be assume to not necessarily be what you are talking about. Then you post a specific link to a site that you say is more or less what you have in mind, but that's refering to very old Mac applications as an example, instead of (as in your most recent post) just refering to a very common modern application as an example.
    Reason #3: Because, maybe it looks cooler that way.
    I mean, geez, man. You don't have to
    o use it. It was just an idea. Gawd.I think you need to calm down. If you can't be more clear initially what you're talking or give modern references to site examples, then you shouldn't expect everyone on a text-only forum can read your mind and figure out what you really are looking for.
    Addressing the second problem I was having with this
    class, adding this line:
    System.setProperty("sun.awt.noerasebackground",
    ound", "true");
    gets rid of the flicker, but not the performance hit.
    Got this from the misnamed not_a_genius in "Re:
    : Transparent windows."
    (http://forum.java.sun.com/thread.jspa?threadID=391403
    &messageID=3067048#3067048).http://www.javadesktop.org/forums/thread.jspa?threadID=6437&tstart=15
    You basically are either going to have to live with the performance hit or the flicker, from what I can see. At least til Java 6 next year. Or you can check
    https://swinglabs.dev.java.net/
    and see if they have a fix that is backwards compatible with Java 1.5. I thought I heard said that they made something available to fix the "gray rectangle" problem... I could be wrong about that, though.
    Anyway, for real info, you can read thru:
    http://weblogs.java.net/blog/chet/archive/2005/04/swing_update_no_1.html

  • Use of JInternalFrame in populated JFrame?

    Hi,
    For my application I'm working on a simple Help screen (I do not want to use JavaHelp). The help screen I have developed is based on a JInternalFrame. This help screen is to be filled with HTML formatted text, that I load at start up. The loading of the text file works fine.
    The application displays everything in a JFrame. When request the helpscreen is also to be displayed.
    At start up I only display a JPanel taking up only (the middle) part of the JFrame. When I request the help screen, it is displayed to the right of the JPanel.
    When I request the help screen when my JFrame has content, it is not shown. Would you know why that is? Does the help screen have to compete for screen space, and failing in it? Should I use something of an Z-order to get my Help screen to be displayed over the other content of the JFrame?
    Abel
    The following (non compilable code, it contains errors :-( ) might show what I'm trying to do:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.IOException;
    import javax.swing.*;
    public class HelpScreenPlace extends JFrame implements ActionListener {
         static HelpScreenPlace helpScreenPlace;
         static JMenuBar menuBar;
         static JMenu menu;
         static JMenuItem hMenuItem;
         static JInternalFrame helpFrame;
         static JEditorPane editorScrollPane;
         static int WIDTH = 450;
         static int HEIGHT = 350;
         static JTextField userNameField;
         static JLabel unameLabel = new JLabel("Username: ", SwingConstants.RIGHT);
         static JTextField passwordField;
         static JLabel passLabel = new JLabel("Password: ", SwingConstants.RIGHT);
         public HelpScreenPlace () {
              super("HelpScreenPlace");
              menuBar = new JMenuBar();
              menu = new JMenu ("Help");
              menu.setMnemonic(KeyEvent.VK_H);
              menu.getAccessibleContext().setAccessibleDescription("Help menu");
              menuBar.add(menu);          
              // The help contents functionality
              // TODO help functionality
              hMenuItem = new JMenuItem ("Help Contents");
              hMenuItem.setMnemonic(KeyEvent.VK_H);
              // What to do to get the keyboard shortcut F1 (no ALTMASK and the like)?
              hMenuItem.addActionListener(this);
              menu.add(hMenuItem);
              add(menuBar);
         public static void createAndShowGUI() {
              helpScreenPlace = new HelpScreenPlace();
              // Add a login panel (without functionality
              JPanel logInPanel = new JPanel();
              logInPanel.setLayout(new GridLayout (3, 2)); // 3 rows, 2 columns
              logInPanel.setBounds (WIDTH, HEIGHT, WIDTH, HEIGHT);
              userNameField = new JTextField ("jdoe", 10);
              passwordField = new JPasswordField("unanimous_unite", 10);
              logInPanel.add (unameLabel);
              logInPanel.add (userNameField);
              logInPanel.add(passLabel);
              logInPanel.add(passwordField);
              JComponent okButton = createButtonPanel();
              logInPanel.add(okButton);
              // An empty panel to fill up the empty spot after the button
              JPanel emptyPanel = new JPanel();
              emptyPanel.setBackground(Color.WHITE);
              logInPanel.add(emptyPanel);
              logInPanel.setSize(WIDTH, HEIGHT);
              logInPanel.setVisible (true);
         static JComponent createButtonPanel() {
              JPanel panel = new JPanel(new GridLayout(0,1));
              JButton okButton = new JButton("OK");
              okButton.setActionCommand("OK");
              // okButton.addActionListener(this); // Cannot use this in static reference (1st error)
              panel.add(okButton);
              return panel;
         public void actionPerformed (ActionEvent event) {
              String message = event.getActionCommand();
              if (message.equals("Help Contents")) {
                   helpFrame = new HelpFrame(); //  cannot convert from HelpScreenPlace.HelpFrame to JInternalFrame (2nd error)
                   helpFrame.setVisible(true);
                   add(helpFrame);
         public static void main(String[] args) {
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
         private class CloseListener extends WindowAdapter {
              public void windowClosing (WindowEvent we) {
                   System.exit(0);
            // - Syntax error on token "class", invalid Type
         // - Syntax error on token "extends", throws expected (etc on errors)
         private static class HelpFrame() extends JInternalFrame {
              super ("Help",
                        true,          // HelpFrame is resizable
                        true,          // HelpFrame is closable
                        true,          // HelpFrame is maximixable
                        true);          // HelpFrame is iconifiable
              // Get the helpPane from the model
              helpPane = model.getHelpPane();
              helpPane.setBackground(Color.WHITE);
              // Add helpPane to JScrollPane
              JEditorPane editorPane = getHelpPane();
              JScrollPane editorScrollPane = new JScrollPane(editorPane);
              editorScrollPane.setVerticalScrollBarPolicy(
                        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              editorScrollPane.setSize(250, 500);
              // editorScrollPane.setPreferredSize(new Dimension(250, 500));
              editorScrollPane.setMinimumSize(new Dimension(10, 10));
              add(editorScrollPane);
         JEditorPane getHelpPane() {
              JEditorPane pane = new JEditorPane();
              pane.setEditable(false); // Not editable
              java.net.URL helpURL = HelpFrame.class.getResource("HelpWindow.html");
              if (helpURL != null) {
                   try {
                        System.out.println ("Getting help file " + helpURL);
                        pane.setPage(helpURL);
                   } catch (IOException e) {
                        System.out.println ("Attempted to read a bad URL: " + helpURL);
              } else {
                   System.out.println ("Couldn't find file: HelpWindow.html");
              return pane;
    }For what it's worth, this is the HelpWindow.html file:
    <html>
    <body>
    This is the help file for this project.<p>
    <p>
    <p>
    <p>
    <p>
    <p>
    <p>
    <p>
    </body>
    </html>

    JInternalFrame's are meant to live in JDesktopPanes. Of course, they dont' strickly have to, but you aren't going to get it to act properly like an internal frame without jumping thru a lot of hoops. At least try packing or setting the size of the internal frame when you add it. If your layout is a border layout, then you're probably replacing the contents of the frame. And anyway, I don't see in your code where you are actually adding the main UI to the frame in the first place.
    Of course, you can wrap your whole UI in a JDesktopPane so that the main display is a panel filling the whole desktop pane on a layer, then add the help frame in there on a higher layer.
    Or maybe just not worry about internal frames and use a JDialog or another JFrame instead.
    Edited by: bsampieri on Apr 15, 2008 10:57 AM

Maybe you are looking for