Use JWindow, JInternalFrame, JPanel, or JDialog

Hello,
My main window application extends a JFrame. When a component of the JFrame is mouse clicked,I want to open a popup window on top of this frame.
The opened window is used to receive input from the user; with these properties: title bar, resizeable, can close with the "X" on the right side of the title bar, no minimizable or maximizable buttons on the title bar.
1. I am very unsure whether I should use: a JWindow, JInternalFrame, JPanel, JDialog, JPopupMenu (probably not since I don't need a menu) to create the popup window. I think I should use JWindow, but am not sure.
2. Also, I am unsure whether I can use JWindow and JInternalFrame with JFrame as the main app window.
Thank you for your advice.

If you want a popup window on top of this frame, you can either choose JFrame, JDialog or JWindow. They all have the own characteristics.
JFrame: Usually application will use it as the base. Because It has a title bar with minimizable, maximizable and exit button.
JDialog: Usually work as a option / peference / about dialog (Ex. Just click the IE about to see). Because it has a smaller title bar with only maximizable and exit button and the model setting. If model is to TRUE, that means all the other area of the window will be disable except the opened dialog own.
JWindow: Usually use as a splash to display logo or welcome message.
JInternalFrame: It display inside a desktop panel of JFrame. Just like the multi-documents function inside the MS Words.

Similar Messages

  • Want to use JDeskTopPane in JPanel

    Hi
    I want to use JDeskTopPane in a JPanel. The reason is that I want to use some JInternalFrames within a particular panel of my application.
    I am using an applet so obviously I could use this.setContentPane() when loading the APPLET, however I need some kind of setContentPane() method on my JPanel which I am using.
    Not sure if you can do that to a JPanel.
    cheers,
    Oliver

    This section from the Swing tutorial shows you how to use a JDeskTopPane and JInternalFrame:
    http://java.sun.com/docs/books/tutorial/uiswing/components/internalframe.html

  • Using JWindow  problem..

    Hi
    I am using JWindow for showing a splash window before the application starts. First i use a JPasswordField for Login but i unable i type in it then i use progress bar and still it is unable to get any value for update.
    when i use JFrame it all works good.
    is there any method that JFrame borders not shown.
    Thanks

    The JPasswordField is in the splash screen?
    if so, the JWindow needs a parent/owner, otherwise it is unfocusable.
    there is a workaround, but let us know if this is the problem (no parent)

  • Can we use setinsets in JPanel?

    can we use setinsets in JPanel?

    Instead of posting twice in the wrong forum, how about posting once in the correct section next time?

  • Can we use setInsets into JPanel?

    can we use setInsets into JPanel?
    Advance wishes

    yes.So? If LayoutManagers handle insets and JPanels can have LayoutManagers, you will have Inset handling in JPanels.

  • Splash screen using JWindow

    HI ,
    i had crated a splash screen using JWindow and made
    JWindow.setVisible(true); during the loading time and then made
    Jwindow.dispose(); after it gets loaded...
    but it is not working a only a blank window is visible not its contents....what's wrong

    hi!
    import java.awt.Color;
    import java.awt.Insets;
    import javax.swing.JLabel;
    import javax.swing.JWindow;
    import javax.swing.border.LineBorder;
    * @author          : aniruddha<br>
    * @date          : Nov 22, 2006,  11:43:43 AM<br>
    * @source          : TestJwindow.java<br>
    * @project          : HelpForum<br>
    * @author aniruddha
    public class TestJwindow
         public static void main(String[] args)
              JWindow loadWindow = new JWindow();
              JLabel lblLoad = new JLabel("  Loading..........");
              if(loadWindow.isVisible())
                   loadWindow.dispose();
              else
                   loadWindow.getContentPane().setBackground(Color.gray);
                   lblLoad.setBorder(new LineBorder(Color.red, 3));
                   lblLoad.setForeground(Color.white);
                   loadWindow.add(lblLoad);
                   loadWindow.setSize(150, 50);
                   loadWindow.setLocationRelativeTo(null);
                   loadWindow.setVisible(true);
    }works fine with me..
    :)

  • Inserting a Gui program using JFrames and JPanel

    I'm trying to insert a chat program into a game that I've created! The chat program is using JFrames and JPanels. I want to insert this into a GridLayout and Panel. How can I go about doing this?

    whatever is in the frame's contentPane now, you add to a separate JPanel.
    you also add your chat stuff to the separate panel
    the separate panel is added to the frame as the content pane

  • Never used JWindow&JDialog and was very happy

    Hi guys!
    I am stuck on simple task. I wanted to place my jpanel into jwin or jdialog so this panel could resize and be dragged inside the JFrame. It would look very neat. Of course I don't want the stupid title bar.
    JWindow turned out to be not resizable and non-movable. Well, I saw people put mouse listeners on it but it does not solve resizability problem.
    JDialog (1.4 jdk) when undecorated is also not resizable (.setResizable(true))and not movable.
    Do you have any idea how to accomplish this task? Will be very grateful.

    I did my best and got almost what I wanted. Some things depend on their native implementations. Nothing I could do.
    I think that JWindows and JDialog are very tricky and devious components. One should stay away from them as far as possible because it's very difficult to make them do what you want: be simple, draggable, freely resizable and stay on top of their owner.

  • 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

  • Update JPanel in JDialog

    Hey,
    need some help please....
    I've searched long and hard but can't find anything.
    I've got an application that opens a JDialog, then jDialog has a JPanel within
    it.
    Once the JDialog has loaded on the screen i want to update the Jpanel based on
    a button click.
    My problem is that the JPanel wont update.
    I've made a simple program that displays the same behaviour.
    Frame with a button on it to open a JDialog :
    public class testFrame extends javax.swing.JFrame {
        /** Creates new form testFrame */
        public testFrame() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jButton1.setText("Show Dialog");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(150, 150, 150)
                    .addComponent(jButton1)
                    .addContainerGap(159, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(135, 135, 135)
                    .addComponent(jButton1)
                    .addContainerGap(142, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            testJDialog test = new testJDialog(this,true);
            test.setVisible(true);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new testFrame().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        // End of variables declaration
    }JDialog code :
    import javax.swing.JTree;
    * @author  wesley
    public class testJDialog extends javax.swing.JDialog {
        /** Creates new form testJDialog */
        public testJDialog(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("TitleBorder"));
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 347, Short.MAX_VALUE)
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 128, Short.MAX_VALUE)
            jButton1.setText("Add Tree");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(145, 145, 145)
                            .addComponent(jButton1)))
                    .addContainerGap(31, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            this.jPanel1.add(new JTree());
            this.pack();
            this.repaint();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    testJDialog dialog = new testJDialog(new javax.swing.JFrame(), true);
                    dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                        public void windowClosing(java.awt.event.WindowEvent e) {
                            System.exit(0);
                    dialog.setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration
    }Ive tried
    this.pack();
    this.repaint();but i cant get the JPanel to repaint.
    Im using Vista Java version
    C:\Users\wesley>java -version
    java version "1.6.0_03"
    Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
    Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)Cheers
    Wesley

    wesleyelder wrote:
    Thanks so much for taking the time to reply, that worked a treat.you're welcome
    i agree the netbeans code is a mess sometimes but when i just need a simple JDialog i sometimes use it, just lazy a guess :)But then you run into problems like this one. I'd much prefer to make my own simple JDialog:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    public class TestMyDialog
        private JPanel mainPanel = new JPanel();
        private JPanel centerPanel = new JPanel();
        public TestMyDialog()
            JButton addTreeBtn = new JButton("Add Tree");
            addTreeBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    addTreeAction();
            JPanel buttonPanel = new JPanel();
            buttonPanel.add(addTreeBtn);
            centerPanel.setBorder(BorderFactory.createTitledBorder("Title Border"));
            centerPanel.setPreferredSize(new Dimension(400, 200));
            centerPanel.setLayout(new BorderLayout());
            mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            mainPanel.setLayout(new BorderLayout(20, 20));
            mainPanel.add(centerPanel, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        private void addTreeAction()
            JTree tree = new JTree();
            tree.setOpaque(false);
            centerPanel.add(new JScrollPane(tree), BorderLayout.CENTER);
            centerPanel.revalidate();
        public JPanel getMainPanel()
            return mainPanel;
        private static void createAndShowUI()
            final JFrame frame = new JFrame("Test My Dialog");
            JPanel framePanel = new JPanel();
            framePanel.setBorder(BorderFactory.createEmptyBorder(200, 200, 200, 200));
            framePanel.setPreferredSize(new Dimension(500, 500));
            JButton showDialogBtn = new JButton("Show Dialog");
            showDialogBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    showDialogAction(frame);
            framePanel.add(showDialogBtn);
            frame.getContentPane().add(framePanel);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        private static void showDialogAction(JFrame frame)
            JDialog dialog = new JDialog(frame, "My Dialog", true);
            dialog.getContentPane().add(new TestMyDialog().getMainPanel());
            dialog.pack();
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • Using alpha in jpanel compoments

    hi all,
    I am overhiden jpanel and yours components using alpha and happens which components are drawing too in area left superior, and I dont know, why this happens, I wish post code here , but is to long... I do alpha in images, and no problems with that, but in compoments I dont know how make this... thanks
          class painel extends JPanel{
              public void paintComponent(Graphics g) {
                  System.out.println("pintando "+alpha);
                ((Graphics2D) g).setComposite(
                        AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                                                   alpha));
                g.setColor(getBackground());
               // g.fillRect(0,0,getWidth(),getHeight());
                 g.fillRect(0,0,getWidth(),getHeight());
    }

    I try setOpaque(true), but fail...
    import java.awt.AlphaComposite;
    import java.awt.Container;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.*;
    public class FadingExemple extends JFrame {
        public FadingExemple(){
        public static void main(String[] args) throws Exception {
           JFrame f = new JFrame();
           f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           FadingOut glassOut = new FadingOut();
           FadingIn glassIn = new FadingIn();
         JPanel contentPane = new JPanel();
           //contentPane.setLayout(new java.awt.GridLayout(10,10));
           contentPane.setLayout(new java.awt.FlowLayout());
           //for(int row = 0; row < 10; row++)
             //  for(int column = 0; column < 10; column++) {
                  contentPane.add(new JButton("Fading"));
                  contentPane.add(new JButton("323232"));
                  contentPane.add(new JButton("2347676767"));
           f.setContentPane(contentPane);
           f.pack();
           f.setSize(400,400);
           f.setVisible(true);
           try{Thread.sleep(500);}
           catch(InterruptedException e) {e.printStackTrace();}
           f.setGlassPane(glassOut);
           glassOut.setVisible(true);
           //glassOut.beginFade();
    glassOut.beginFade(0.70f);
           // usando glassOut e apos glassIn -> glassIn faz aparecer
           // usando somente glassIn -> glassIn faz desaparecer rapido
           try{Thread.sleep(900);}
           catch(InterruptedException e) {e.printStackTrace();}
           f.setGlassPane(glassIn);
           glassIn.setVisible(true);
           glassIn.beginFade();
        public static class FadingIn extends JPanel implements ActionListener
                  private float opacity = 1f;
                  private Timer fadeTimer;
                     public void beginFade() {
                fadeTimer = new javax.swing.Timer(75,this);
                fadeTimer.setInitialDelay(0);
                fadeTimer.start();
            public void actionPerformed(ActionEvent e) {
                   opacity -= .01;
                   System.out.println(opacity);
                if(opacity < 0) {
                    opacity = 0;
                    fadeTimer.stop();
                    fadeTimer = null;
                repaint();
               public void paintComponent(Graphics g) {
            ((Graphics2D) g).setComposite(
                        AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                                                   opacity));
                g.setColor(getBackground());
                g.fillRect(0,0,getWidth(),getHeight());
        public static class FadingOut extends JPanel
                implements ActionListener
            private float opacity = 0f;
            private Timer fadeTimer;
            public void beginFade() {
                fadeTimer = new javax.swing.Timer(75,this);
                fadeTimer.setInitialDelay(0);
                fadeTimer.start();
            public void beginFade(float opacity){
                this.opacity = opacity;
            public void actionPerformed(ActionEvent e) {
                opacity += .03;
                System.out.println(opacity);
                if(opacity > .5) {
                    opacity = 0.5f;
                    fadeTimer.stop();
                    fadeTimer = null;
                repaint();
            public void paintComponent(Graphics g) {
                ((Graphics2D) g).setComposite(
                        AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                                                   opacity));
                g.setColor(getBackground());
                g.fillRect(0,0,getWidth(),getHeight());
    }

  • Unable to paint (using paint() in JPanel) inside mouse listeners

    This is hard to explain but I'll do my best :)
    I've created a little game and at some point I needed to make images "move" on the JPanel (through paint()), on a checkers-based game board.
    The game works like so:
    it has a mouse listener for clicks and movement, and the main game process is THINK(), REPAINT(), which is repeated until the user wins (the above is inside a while).
    The mouse actions were added to the constructor so they are always active, THINK changes the enemy's locations, and REPAINT simply calls "paint()" again.
    The picture is either an enemy or the player, and it can only "rest" on squares.
    (e.g. point's x and y must be divided in 50).
    While doing that, I wanted to make the movement more sleek and clean,
    instead of them simply jumping from one square to the other with a blink of the eye.
    So, I've created MOVEACTOR, that "moves" an enemy or a player from its current point (actor.getPoint()) to the requested future square (futurePoint).
    //actor = enemy or player, has getPoint() that returnes the current point on the board where he rests on.
    //futurePoint = the new point where the enemy or player should be after the animation.
    //please ignore obvious stuff that has nothing to do with what I asked -- those will be deleted in the future, for they are only temporary checking extra lines and stuff.
    //also feel free to ignore the "jumpX" things. Those are just to change images, to imitate physical "jumping" animation.
    protected void moveActor(Actor actor, Point futurePoint)
              Point presentPoint = actor.getPoint();
              int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
              int addToX, addToY;
              if (futurePoint.getX() > x) addToX = 1;
              else addToX = -1;
              if (futurePoint.getY() > y) addToY = 1;
              else addToY = -1;
              Point middlePoint = new Point(x,y);
              int imageCounter = 0;
              while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
                   imageCounter++;
                   x+=addToX;
                   y+=addToY;
                   middlePoint.setLocation(x,y);
                   actor.setPoint(middlePoint);
                   /*if (imageCounter<=10) actor.setStatus("jump1");
                   else if (imageCounter<=40) actor.setStatus("jump2");
                   else if (imageCounter<=50) actor.setStatus("jump3");*/
                   repaint();
                   try {animator.sleep(1);} catch (InterruptedException e) {}
              //actor.setStatus("idle");
         }I use the above on several occasions:
    [1] When an enemy moves. Summary:
                             if (playerIsToVillainsRight) xToAdd = 50;
                             else if (playerIsToVillainsLeft) xToAdd = -50;
                             else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                             if (playerIsBelowVillain) yToAdd = 50;
                             else if (playerIsAboveVillain) yToAdd = -50;
                             else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                             Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                             moveActor(actors[currentVillain], futurePoint);[2] When the player moves. Summary (this is inside the mouseClicked listener):
    //mouseLocation = MouseWEvent.getPoint();
    //stl, str, etc = rectangles that represents future location of the player on the board.
              if (waitingForPlayer) {
                   if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                        moveActor(actors[0], stl.getLocation());
                        waitingForPlayer = false;
                   if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                        moveActor(actors[0], str.getLocation());
                        waitingForPlayer = false;
                   if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                        moveActor(actors[0], sbl.getLocation());
                        waitingForPlayer = false;                                   
                   if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                        moveActor(actors[0], sbr.getLocation());
                        waitingForPlayer = false;
    SO ... WHAT IS THE QUESTION?!?
    What I see when I run the game:
    the animation of the enemy (first code) works, but the animation of the player (second code, inside the mouse listeners) -- doesn't!
    The purpose of the moveActor is to move the enemy or player pixel by pixel, until its in the future point,
    instead of skipping the pixels between the squares and going straight for the future location.
    So what comes out is, that the enemy is moving pixel by pixel, and the player simply jumps there!
    I doublechecked and if I use moveActor with the player OUTSIDE the mouse listener, it works (i think).
    Any ideas what is the source of this problem?
    Hope I made myself clear enough :D
    Thanks,
    Eshed.

    I don't know if thats what happens, nor how to fix the thread problems. The mosue actions are "threaded" by default, no? And the moving thing happens after the mouse was clicked, and if the enemy's moving the user can still move his mouse and get responses, like "enemy didn't move yet" and stuff.
    Here's the complete GamePanel.java:
    //drawings
    import javax.swing.ImageIcon;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    //events
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    //tools
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.MediaTracker;
    import java.awt.Dimension;
    //panels, buttons, etc
    import javax.swing.JPanel;
    /** The Game Panel.
    *The panel's size is 500x500, and each square is squaresized 50.
    *This is where the game actually "exists". Here its being updated, drawn, etc.*/
    public class GamePanel extends JPanel implements Runnable
         private static final int PWIDTH = 500;                              //Width of the panel.
         private static final int PHEIGHT = 500;                              //Height of the panel.
         private static final int SQUARESIZE = 50;                         //Size of each square in the panel.
         private boolean working = false;                                   //Game keeps going until this is FALSE.
         private volatile Thread animator;                                   //The animation thread.
         private ImageIcon stand,fall;                                        //Images for the background - ground and water.
         private static ImageHandler ih;                                        //An image handler for image loading.
         private int numOfImages = 0;                                        //Number of total images (max image qunatity).
         private Actor[] actors;                                                  //The actors: [0] is the player, rest are enemies.
         private Point mouseLocation;                                        //Saves the current mouse location for checking where the mouse is
         protected Rectangle stl, str, sbl, sbr;                              //squares around the player, for mouse stuff.
         protected Rectangle v1, v2, v3, v4, v5;                              //squares around each villain, for mouse stuff.
         protected Rectangle wholeBoard = new Rectangle(0,0,PWIDTH,PHEIGHT);
         protected boolean waitingForPlayer = true;
         private int currentVillain = 1;
         private boolean inSight = false;
         // in methods other than the listeners.
         /** Waits for the Window (or whatever this panel loads in) to settle in before doing anything.*/
         public void addNotify()
              super.addNotify();                                                                           //When the super finishes...
              go();                                                                                                         //..go, go, go!
         /** Starts the game.*/
         private void go()
              if (animator==null || !working)     {                                        //if the game isn't in process,
                   animator = new Thread(this);                                        //make the animator as the main process,
                   animator.start();                                                                      //and start it (because of the runnable it launches "run()".
         /**Constructor of the Game Panel.*/
         public GamePanel()
              numOfImages = 14;                                                                      //Total image num.
              ih = new ImageHandler(this,numOfImages);               //Setting a new image handler for the images.
              ih.addImage("player_idle", "images/p_idle.png");          //Adding images.
              ih.addImage("villain_idle", "images/v_idle.png");
              ih.addImage("stand", "images/stand.gif");
              ih.addImage("fallpng", "images/fall.png");
              ih.addImage("fall", "images/fall.gif");
              ih.addImage("ghost", "images/ghost.gif");
              ih.addImage("villain_angry", "images/v_angry.png");
              ih.addImage("player_angry", "images/p_angry.png");
              ih.addImage("player_jump1", "images/p_j1.gif");
              ih.addImage("player_jump2", "images/p_j2.gif");
              ih.addImage("player_jump3", "images/p_j3.gif");
              ih.addImage("villain_jump1", "images/v_j1.gif");
              ih.addImage("villain_jump2", "images/v_j2.gif");
              ih.addImage("villain_jump3", "images/v_j3.gif");
              setPreferredSize(new Dimension(PWIDTH,PHEIGHT));     //Setting size of the panel.
              setFocusable(true);                                                                                //This and the next makes the window "active" and focused.
              requestFocus();
              /** Mouse hovering settings.*/
              addMouseMotionListener( new MouseMotionAdapter()
                   /** When the mouse is moving, do these stuff.*/
                   public void mouseMoved(MouseEvent e1)
                         *  |  stl  |       | str   |          stl = squareTopLeft
                         *  |_______|_______|_______|       str = squareTopRight
                        *   |       |current|       |         current = player's location
                        *   |_______|_______|_______|       sbl = squareBottomLeft
                        *   |  sbl  |       |  sbr  |       sbr = squareBottomRight
                        *   |_______|_______|_______|
                        mouseLocation = e1.getPoint();
                        Dimension defaultSquareDimension = new Dimension(50,50);
                        //current-player-location points
                        Point topLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY());
                        Point topRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY());
                        Point bottomLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY()+50);
                        Point bottomRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY()+50);
                        //four-squares-around-the-player points
                        //T = top, B = bottom, R = right, L = left
                        Point ptl = new Point((int)topLeft.getX()-50,(int)topLeft.getY()-50);
                        Point ptr = new Point((int)topRight.getX(),(int)topRight.getY()-50);
                        Point pbl = new Point((int)bottomLeft.getX()-50,(int)bottomLeft.getY());
                        Point pbr = new Point((int)bottomRight.getX(),(int)bottomRight.getY());
                        //ghosts
                        stl = new Rectangle (ptl, defaultSquareDimension);
                        str = new Rectangle (ptr, defaultSquareDimension);
                        sbl = new Rectangle (pbl, defaultSquareDimension);
                        sbr = new Rectangle (pbr, defaultSquareDimension);
                        Rectangle player = new Rectangle(topLeft, defaultSquareDimension);     //rectangle of player
                        if (stl.contains(mouseLocation) && !hoveringVillain(stl))
                             actors[8] = new Actor("ghost", ptl);
                             else actors[8] = null;
                        if (str.contains(mouseLocation) && !hoveringVillain(str))
                             actors[9] = new Actor("ghost", ptr);
                             else actors[9] = null;
                        if (sbl.contains(mouseLocation) && !hoveringVillain(sbl))
                             actors[10] = new Actor("ghost", pbl);
                             else actors[10] = null;
                        if (sbr.contains(mouseLocation) && !hoveringVillain(sbr))
                             actors[11] = new Actor("ghost", pbr);
                             else actors[11] = null;
                   private boolean hoveringVillain(Rectangle r)
                        boolean onVillain = false;
                        for (int i=1; i<=5 && !onVillain; i++) onVillain = actors.getRect().equals(r);
                        return onVillain;
              /** Mouse-click settings.
              Note: only usable after moving the mouse. /
              addMouseListener (new MouseAdapter()
                   /** When the mouse button is clicked */
                   public void mouseClicked (MouseEvent me)
                        mouseClickedAction(me);
         private boolean hoveringVillain(Rectangle r)
              boolean onVillain = false;
              for (int i=1; i<=5 && !onVillain; i++) onVillain = actors[i].getRect().equals(r);
              return onVillain;
         public void mouseClickedAction(MouseEvent me)
              System.out.println("Point: "+me.getX()+","+me.getY());
              if (waitingForPlayer) {
                   //causes error if the mouse wasn't moved uptil now. try it.
                   mouseLocation = me.getPoint();
                   if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                        moveActor(actors[0], stl.getLocation());
                        waitingForPlayer = false;
                   if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                        moveActor(actors[0], str.getLocation());
                        waitingForPlayer = false;
                   if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                        moveActor(actors[0], sbl.getLocation());
                        waitingForPlayer = false;                                   
                   if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                        moveActor(actors[0], sbr.getLocation());
                        waitingForPlayer = false;
              } else MiscTools.shout("Wait for the computer to take action!");
              if (actors[0].getPoint().getY() == 0){
                   for (int i=1; i<=5; i++){
                             actors[i].setStatus("angry");
                   //repaint();
                   MiscTools.shout("Game Over! You Won!");
         /** First thing the Game Panel does.
         Initiating the variables, and then looping: updating, painting and sleeping./
         public void run() {
    Thread thisThread = Thread.currentThread();                                                  //Enables the restart action (two threads needed).
    init();                                                                                                                                            //Initialize the variables.
    while (animator == thisThread && working){                                                  //While the current thead is the game's and it's "on",
                   think();                                                                                                                             //Update the variables,
                   repaint();                                                                                                                             //Paint the stuff on the panel,
                   try {Thread.sleep(5);} catch (InterruptedException ex) {}                    //And take a wee nap.
         /** Initializing the variables.*/
         private void init()
              currentVillain = 1;
              working = true;                                                                                //Make the game ready for running.
              inSight = false;
              actors = new Actor[12];                                                                      //Six actors: player and 5*villains.
              actors[0] = new Actor("player", 200, 450);                                             //The first actor is the player.
              int yPoint = 50;                                                                           //The Y location of the villains (first row).
              /* ACTORS ON TOP, RIGHT, LEFT
              actors[1] = new Actor ("villain", 0, 350);
              actors[2] = new Actor ("villain", 0, 150);
              actors[3] = new Actor ("villain", 50, 0);
              actors[4] = new Actor ("villain", 250, 0);
              actors[5] = new Actor ("villain", 450, 0);
              actors[6] = new Actor ("villain", 450, 200);
              actors[7] = new Actor ("villain", 450, 400);
              /* ACTORS ON TOP*/
              for (int i=1; i<actors.length-4; i++){                                                  //As long as it doesnt go above the array...
                   actors[i] = new Actor ("villain", yPoint, 0);                                   //init the villains
                   actors[i].setStatus("idle");
                   yPoint+=100;                                                                           //and advance in the Y axis.
         /** Updating variables.*/
         private void think()
              if (!waitingForPlayer){
                   //initialize
                   int playerX = (int)actors[0].getPoint().getX();
                   int playerY = (int)actors[0].getPoint().getY();
                   boolean moved = false;
                   wholeBoard = new Rectangle(0,0,500,500);     //needed to check whether an actor is inside the board
                   //for (int in = 0; in<=5; in++) actors[in].setStatus("idle"); //"formatting" the actor's mood
                   if (playerY <= 1000) inSight = true;     //first eye contact between the player and villains.
                   int closestVillainLevel = 0;
                   int[] vills = closestVillain();
                   int moveCounter = 0;
                   if (inSight) {
                        while (!moved){               //while none of the villains made a move
                        moveCounter++;
                        if (moveCounter == 5) moved = true;
                        else{
                             currentVillain = vills[closestVillainLevel];
                             int villainX = (int)actors[currentVillain].getPoint().getX();
                             int villainY = (int)actors[currentVillain].getPoint().getY();
                             //clearing stuff up before calculating things
                             boolean playerIsBelowVillain = playerY > villainY;
                             boolean playerIsAboveVillain = playerY < villainY;
                             boolean playerIsOnSameRowAsVillain = playerY == villainY;
                             boolean playerIsToVillainsRight = playerX > villainX;
                             boolean playerIsToVillainsLeft = playerX < villainX;
                             boolean playerIsOnSameColumnAsVillain = playerX == villainX;
                             //System.out.println("\n-- villain number "+currentVillain+" --\n");
                             int xToAdd = 0, yToAdd = 0;
                             if (playerIsToVillainsRight) xToAdd = 50;
                             else if (playerIsToVillainsLeft) xToAdd = -50;
                             else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                             if (playerIsBelowVillain) yToAdd = 50;
                             else if (playerIsAboveVillain) yToAdd = -50;
                             else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                             Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                             if (legalPoint(futurePoint)){
                                  moveActor(actors[currentVillain], futurePoint);
                                  moved = true;
                                  //System.out.println("\nVillain "+currentVillain+" is now at "+actors[currentVillain].getPoint());
                             else closestVillainLevel=circleFive(closestVillainLevel);
                        } //end of else
                        } //end of while
                        //currentVillain = circleFive(currentVillain); //obsolete
                   } //end of ifInSight
                   waitingForPlayer = true;
         private boolean legalPoint(Point fp)
              return (wholeBoard.contains(fp) && !onPeople(fp) && legalSquare(fp));
         private boolean legalSquare(Point p)
              if ( (p.getX()==0 || p.getX()%100==0) && (p.getY()/50)%2!=0 ) return true;
              if ( (p.getX()/50)%2!=0 && (p.getY()==0 || p.getY()%100==0) ) return true;
              return false;
         //return the closest villain to the player, by its level of distance.
         public int[] closestVillain()
              //System.out.println("Trying to find the closest villain...");
              double[] gaps = new double[5];     //the distances array
              //System.out.println("The villains' distances are: ");
              for (int i=0; i<5; i++){
                   gaps[i] = distanceFromPlayer(actors[i+1].getPoint());     //filling the distances array
                   //System.out.print(gaps[i]+", ");
              int[] toReturn = new int[5];
              double smallestGapFound;
              double[] arrangedGaps = smallToLarge(gaps);
              for (int level=0; level<5; level++){
                   smallestGapFound = arrangedGaps[level];
                   for (int i=1; i<=5; i++){
                        if (smallestGapFound == distanceFromPlayer(actors[i].getPoint())){
                             toReturn[level] = i;
              return toReturn;
         private double[] smallToLarge(double[] nums)
              //System.out.println("\nArranging array... \n");
              double[] newArray = new double[5];
              int neweye = 0;
              double theSmallestOfTheArray;
              for (int i=0; i<nums.length; i++){
                   theSmallestOfTheArray = smallest(nums);
                   //System.out.println("\t\t>> Checking whether location "+i+" ("+nums[i]+") is equal to "+theSmallestOfTheArray);
                   if (nums[i] == theSmallestOfTheArray && nums[i]!=0.0){
                        //System.out.println("\t\t>> Adding "+nums[i]+" to the array...");
                        newArray[neweye] = nums[i];
                        //System.out.println("\t\t>> Erasing "+nums[i]+" from old array...\n");
                        nums[i] = 0.0;
                        neweye++;
                        i=-1;
              /*System.out.print("\nDONE: ");
              for (int i=0; i<newArray.length; i++)
                   System.out.print("["+newArray[i]+"] ");
              System.out.println();*/
              return newArray;
         private double smallest (double[] nums)
                   //System.out.print("\tThe smallest double: ");
                   double small = 0.0;
                   int j=0;
                   while (j<nums.length){               //checking for a starting "small" that is not a "0.0"
                        if (nums[j]!=0.0){
                             small = nums[j];
                             j = nums.length;
                        } else j++;
                   for (int i=1; i<nums.length; i++){
                        if (small>nums[i] && nums[i]!=0.0){
                             small = nums[i];
                   //System.out.println(small+".");
                   return small;
         private double distanceFromPlayer(Point vp)
              Point pp = actors[0].getPoint(); //pp=plaer's point, vp=villain's point
              double x = Math.abs(vp.getX() - pp.getX());
              double y = Math.abs(vp.getY() - pp.getY());
              return Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
         private int circleFive(int num)
                   if (num>=5) return 0;
                   else return num+1;
         private boolean onPeople(Point p)
              for (int jj=0; jj<=5; jj++)
                   if (jj!=currentVillain && p.equals(actors[jj].getPoint()))
                        return true;
              return false;
         /** Painting the game onto the Game Panel.*/
         public void paintComponent(Graphics g)
              Graphics2D graphics = (Graphics2D)g;                                                            //Reset the graphics to have more features.
              //draw bg
              graphics.setColor(Color.white);                                                                                //"format" the panel.
              graphics.fillRect(0,0,500,500);
         char squareType = 'f';                                                                                                    //First square's type (stand or fall).
         for (int height=0; height<PHEIGHT; height=height+SQUARESIZE){     //Painting the matrix bg.
                   for (int width=0; width<PWIDTH; width=width+SQUARESIZE){
                        if (squareType=='f') {                                                                                               //If a "fall" is to be drawn,
                             ih.paint(graphics, "fallpng", new Dimension(width,height));          //Draw a non-animated image to bypass white stuff.
                             ih.paint(graphics, "fall", new Dimension(width,height));               //Draw the water animation.
                             squareType = 's';                                                                                                    //Make the next square a "stand".
                        } else if (squareType=='s'){                                                                                //If a "stand" is to be drawn,
                             ih.paint(graphics, "stand", new Dimension(width,height));          //Draw the ground image,
                             squareType = 'f';                                                                                                    //and make the next square a "fall".
                   if (squareType=='f') squareType = 's';                                                                 //After finishing a row, switch again so
                   else squareType = 'f';                                                                                                    // the next line will start with the same type (checkers).
              for (int i=actors.length-1; i>=0; i--){                                                                           //Draw the actors on the board.
                   if (actors[i]!=null)
                        ih.paint(graphics, actors[i].currentImage(), actors[i].getPoint());
         /** Restart the game.
         Or, in other words, stop, initialize and start (again) the animator thread and variables./
         public void restart()
              System.out.println("\n\n\nRESTARTING GAME\n\n\n");
              animator = null;                                                                                                                   //Emptying the thread.
              init();                                                                                                                                                 //Initializing.
              animator = new Thread(this);                                                                                     //Re-filling the thread with this panel's process.
              animator.start();                                                                                                                   //launch "run()".
         protected void moveActor(Actor actor, Point futurePoint)
              Point presentPoint = actor.getPoint();
              int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
              int addToX, addToY;
              if (futurePoint.getX() > x) addToX = 1;
              else addToX = -1;
              if (futurePoint.getY() > y) addToY = 1;
              else addToY = -1;
              Point middlePoint = new Point(x,y);
              int imageCounter = 0;
              while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
                   imageCounter++;
                   x+=addToX;
                   y+=addToY;
                   middlePoint.setLocation(x,y);
                   actor.setPoint(middlePoint);
                   /*if (imageCounter<=10) actor.setStatus("jump1");
                   else if (imageCounter<=40) actor.setStatus("jump2");
                   else if (imageCounter<=50) actor.setStatus("jump3");*/
                   repaint();
                   try {animator.sleep(1);} catch (InterruptedException e) {}
              //actor.setStatus("idle");

  • (Another) problem with custom painting using JApplet and JPanel

    Hi all,
    I posted regarding this sort of issue yesterday (http://forums.sun.com/message.jspa?messageID=10883107). I fixed the issue I was having, but have run into another issue. I've tried solving this myself to no avail.
    Basically I'm working on creating the GUI for my JApplet and it has a few different JPanels which I will be painting to, hence I'm using custom painting. My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    public class TetrisClone extends JApplet {
         public void init() {
              setSize( 450, 500 );
              Container content = getContentPane();
              content.add( new mainGUI(), BorderLayout.CENTER );
              content.add( new rightGUI() , BorderLayout.LINE_END );
    class mainGUI extends JPanel {
         // Main bit where blocks fall
         public mainGUI() {
              setBackground( new Color(68,75,142) );
              setPreferredSize( new Dimension( 325, 500 ) );
              validate();
         public Dimension getPreferredSize() {
              return new Dimension( 450, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              // As a test. This shows up fine.
              g.setColor( Color.black );
              g.fillRect(10,10,100,100);
              g.setColor( Color.white );
              g.drawString("Main",45,55);
    class rightGUI extends JPanel {
         BufferedImage img = null;
         int currentLevel = 0;
         int currentScore = 0;
         int currentLines = 0;
         public rightGUI() {
              // The right panel. Has quite a few bits. Starts here..
              FlowLayout flow = new FlowLayout();
              flow.setVgap( 20 );
              setLayout( flow );
              setPreferredSize( new Dimension( 125, 500 ) );
              setBackground( new Color(27,34,97) );
              setBorder( BorderFactory.createMatteBorder(0,2,0,0,Color.black) );
              // Next block bit
              JPanel rightNext = new JPanel();
              rightNext.setPreferredSize( new Dimension( 100, 100 ) );
              //rightNext.setBackground( new Color(130,136,189) );
              rightNext.setOpaque( false );
              rightNext.setBorder( BorderFactory.createEtchedBorder(EtchedBorder.LOWERED) );
              Font rightFont = new Font( "Courier", Font.BOLD, 18 );
              // The player's playing details
              JLabel rightLevel = new JLabel("Level: " + currentLevel, JLabel.LEFT );
              rightLevel.setFont( rightFont );
              rightLevel.setForeground( Color.white );
              JLabel rightScore = new JLabel("Score: " + currentScore, JLabel.LEFT );
              rightScore.setFont( rightFont );
              rightScore.setForeground( Color.white );
              JLabel rightLines = new JLabel("Lines: " + currentLines, JLabel.LEFT );
              rightLines.setFont( rightFont );
              rightLines.setForeground( Color.white );
              JPanel margin = new JPanel();
              margin.setPreferredSize( new Dimension( 100, 50 ) );
              margin.setBackground( new Color(27,34,97) );
              JButton rightPause = new JButton("Pause");
              try {
                  img = ImageIO.read(new File("MadeBy.gif"));
              catch (IOException e) { }
              add( rightNext );
              add( rightLevel );
              add( rightScore );
              add( rightLines );
              add( margin );
              add( rightPause );
              validate();
         public Dimension getPreferredSize() {
                   return new Dimension( 125, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              g.setColor( Color.black );
              g.drawString( "blah", 425, 475 ); // Doesn't show up
              g.drawImage( img, 400, 400, null ); // Nor this!
              System.out.println( "This bit gets called fine" );
    }Any help would be greatly appreciated. I've read loads of swing and custom painting tutorials and code samples but am still running into problems.
    Thanks,
    Tristan Perry

    Many thanks for reminding me about the error catching - I've added a System.out.println() call now. Anywhoo, the catch block never gets run; the image get call works fine.
    My problem was/is:
    "My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:"
    I guess I should have expanded on that. Basically whatever I try to output in the public void paintComponent( Graphics g ) method of the rightGUI class doesn't get output.
    So this doesn't output anything:
    g.drawString( "blah", 425, 475 ); // Doesn't show up
    g.drawImage( img, 400, 400, null ); // Nor this!
    I've checked and experimented with setOpaque(false), however this doesn't seem to be caused by any over-lapping JPanels or anything.
    Let me know if I can expand on this :)
    Many thanks,
    Tristan Perry
    Edited by: TristanPerry on Dec 10, 2009 8:40 AM

  • Help: How to use JWindow as Popup

    Hi there,
    I am developing a program & I wanted to design it with a screen like the Mac OS (tiger?) desktop. That is menu (button bar) at the bottom of the screen (the program's screen - Not the OS).
    I thought I should use a JWindow to do it.
    HOW I WOULD LIKE THE POPUP TO BEHAVE:
    - Only appears when a user moves the mouse towards the bottom of the screen.
    - To disappear (hide) when the user clicks somewhere else on the screen [when focus is lost(?)]
    - To change its position relative to the program. That is, if the program is resized etc...
    I NEED YOUR HELP ON
    The design issues I should take into consideration. I mean interfaces I should implement etc...
    Thanks in advance.
    Yours,
    Me

    Okay, sorry for the late reply, I dont go on the net much.
    With the focus issues, it could be very tricky to know when exactly the Window has lost focus cause a component within the window could still have the focus, hence the window would be in focus.
    One way, could be to add a common FocusListener to all the components within the window by using a recursion method, and allow this FocusListener to determine when all the elements within the window have lost focus, so as to call the window hiding function
    public void addFocusListener(Component c, FocusListener fl) {
      c.addFocusListener(fl);
      if(c instanceof Container) {
         Container cn = (Container)c;
         for(int i = 0; i < cn.getComponents().length; i++) {
             addFocusListener(cn.getComponent(i), fl);
    // also the focus listener could be like this
    class FocusChecker implements FocusListener {
       public void focusLost(FocusEvent e) {
          Component source = (Component)e.getSource();
          if(popupWindow.isAncestorOf(source)) {
              if(!popupWindow.isFocussed()) { // check if the window has a focussed component
                 moveWindowIntoHiding();  // call the method to hide to window
    }This is just a general guideline. Think around this to hide the window when it looses focus
    ICE

  • Theory: Displaying JPanels in JDialogs

    Hi all,
    I went ahead and developed my classes as JPanels, as I thought it would be more extensible than if I made them JDialogs directly.
    But I didn't think it through. Now when I want to add them to a JDialog, I need to make the JDialog inside the class, so the class can call dispose on it (I actually call setVisible(false)... is one way better than the other?).
    This isn't really a hassle, though it defeats the point of making my class a JPanel. What's the accepted practice here? Do people make classes as JPanels, then add them to things? Is there a better way of doing this?
    Would I be better off just making my class extend JDialog and do away with the JPanel? (although I'm aiming for extensibility, it's really all theoretical as I can't envision myself or anyone else reusing these classes).
    Just want to know way most people do it.
    Cheers,
    Radish21

    Ok, that works for my app. But is this a publicy accepted way of doing things?
    Before I get too far, I just want to make sure I'm not doing things ass-about.

Maybe you are looking for

  • Worst ever Customer support in my life

    Hello Team, My Name is Anish Mathew and you can reach at my number xxxxxxxxxxx).I would like to report one of the worst customer support I have ever experienced in my life. I am not sure which email address I should be sending this,so marked on all a

  • Multiple devices - 1 Apple ID, time for another ID?

    Hi As a family we currently only use 1 Apple ID - this is the ID on the computer that has Itunes on, any icloud stuff and then we use it on 4 devices belonging to each of us. This was I can keep track of what the children are doing plus we share all

  • Getting "Error: 0x80070654" when trying to install SCCM 2012 R2 Console from Software Center

    What I did: Created a Package Source share on the Site Server Gave the Package Source Share the following Share permissions: SCCM Admins: Full Control, Domain Computers: Full Control, Local Admins: Full Control. Copied the "Program Files\Microsoft Co

  • Populating a poplist in a query

    I am populating a poplist at runtime (from another master table) depending on the selected value in a field before that. From the populated description I get the code and keep insert this to the based table which is used to insert the entered data. W

  • Updating a LONG column !!!!

    I have a column defined as a LONG in a table, I am trying to update that column through a loop, everytime I update I have to concatenate that with a new string, that's my requirement. example: update my_long_table set my_long_column = my_long_column