Flashing JFrame

Hi,
I would like to create a JFrame with two specifal features:
1. JFrame should not grab focus while maximized from minimized state.
2. When a JFrame created or became maximized from minimized state, it should flash in the Windows bar until a user will grant a focus to it. (like as in ICQ clients [url http://i.imgur.com/dKwJV.jpg]flashing example ).
Does anybody know how the second requirement can be implemented?
Little self-explained example:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JFrameTest {
    private static JFrame childFrame;
    public static Container getParentContentPane() {
        JPanel panel = new JPanel();
        JButton button = new JButton("Create\\Restore child frame");
        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                createOrRestoreChildFrame();
        panel.add(button);
        return panel;
    private static void createOrRestoreChildFrame() {
        if (childFrame == null) {
            childFrame = new JFrame("Child Frame");
            childFrame.setLocation(200, 200);
            childFrame.add(new JLabel("Child Frame"));
            childFrame.pack();
            setChildFrameVisible();
        } else {
            setChildFrameVisible();
    private static void setChildFrameVisible() {
        childFrame.setFocusableWindowState(false);
        childFrame.setVisible(true);
        flashInWindowsBar(childFrame);
        childFrame.toFront();
        childFrame.setFocusableWindowState(true);
     * Should Make child frame flash in Windows bar.
     * Currently, it does not work for me.
     * Could anybody help me to fix this please? )
    private static void flashInWindowsBar(JFrame childFrame) {
        childFrame.setState(JFrame.ICONIFIED);
        childFrame.toFront();
    private static void createAndShowGUI() {
        JFrame parentFrame = new JFrame("JFrame Demo");
        parentFrame.setLocation(100, 100);
        parentFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        parentFrame.setContentPane(getParentContentPane());
        parentFrame.pack();
        parentFrame.setVisible(true);
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
}Thanks!
Edited by: user1106343 on Nov 30, 2010 2:10 AM
Edited by: user1106343 on Nov 30, 2010 2:11 AM

In the future, you should at least alert users that you've cross-posted (which is frowned upon):
http://stackoverflow.com/questions/4305837/flashing-jframe
http://www.coderanch.com/t/518839/GUI/java/Flashing-JFrame

Similar Messages

  • Play a flash file inside a container or component like jframe or jpanel

    sir ,
    i want to embed a flash file inside a jframe or jpanel,
    is it possible ,please give me related reference of URL providing
    plugin for this.
    i will be very thankful for this great help.
    it is very importent for me.
    bye

    I think JMF will support flash files.

  • Flash SWF file within Swing JFrame

    I was wondering whether its possible to open a Flash swf file within a JFrame
    I am looking for a solution similar to the usage of Flash Activex control in .NET
    thanks in advance
    Vikas

    I have read the forum link and other such entries in this forum. I have found the following:
    1.) JFlash - a java based flash player. https://jflash.dev.java.net/
    Could'nt find the app or the official site
    2.) a few projects on sourceforge.org :
    java flash bridge where you embed the flash inside an Integrated Browser Component
    3.) SWT Flash integration.
    I do not find any of these solutions satisfactory.except the SWT/Flash integration which I havent tried.
    My question is that isnt there an easier and simpler way to :
    Embed Flash into Swing app where actionscript and java can communicate.
    I am aware of Remoting and web services. But It is a desktop app I am talking about.
    Can anyone suggest anything?
    thanks in advance..
    from a very frustrated programmer....

  • How to do flashing titlebar's JFrame

    I'm developing a chat Application and have to notify users when a new message is Arriving.
    How to do for flashing titlebar of the JFrame message Window?
    thanks greatly some smarter help.

    That's a good question but I don't think that's possible unless you use a modal dialog or something. Here
    are some other options though: why not make the frame come to the front of all windows when a new
    message comes kind of like the messenger service? You can make the frame's content flash maybe?
    you can sound an alarm maybe? Use combinations of these suggestions maybe?

  • How can I stop a JFrame from painting it's background on setVisible?

    When a JFrame is set visible it will paint its background before it paints whatever is in the contentPane. This gives an ugly gray flash before the content pane is painted. I can't use the solution of setting the JFrame's background color because the content pane is displaying an image, not a simple color. I need the image to be the first thing displayed when the frame is set visible. Seems related to doublebuffering some how, but I'm not sure what to do. The same problem presents itself with a JWindow IF it has a parent JFrame. Below is code that will demonstrate this problem.
    import java.awt.Color;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Test extends JFrame{
    JPanel panel = new JPanel();
    public static void main(String[] args) {
    new Test().setVisible(true);
    private Test(){      
    getContentPane().add(panel);
    // setBackground(Color.white); // <-- uncomment this to remove flash.
    panel.setBackground(Color.white);
    setSize(640, 480);
    super.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    I can't use the solution of setting the JFrame's background color because the content pane is displaying an image, not a simple colorMy question to you is what difference does it make?. Like it or not, JFrame is either going to set the background with the LAF control color or the color you specified. Take a look at the source code and you will see that JFrame calls a protected frameinit method where it gets and sets the backgroud color. The only feasible solution is shown below:
    import java.awt.Color;
    import javax.swing.*;
    public class Test extends JFrame {
       JPanel panel = new JPanel();
       public static void main(String[] args) {
          UIManager.put("control",Color.white);  // added by V.V.
          new Test().setVisible(true);
       private Test() {
          getContentPane().add(panel);
          panel.setBackground(Color.white);
          setSize(640, 480);
          super.setDefaultCloseOperation(EXIT_ON_CLOSE);
    };o)
    V.V.

  • How to add a JMenubar and a JTable in a JFrame in a single application

    Hi all,
    I require an urgent help from you.I am a beginer in programming Swing.I want to add a menu,combobox,and a table in a single application.I did coding as below:
    package com.BSS;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class newssa extends JFrame
         public JMenuBar menuBar;
         public JToolBar toolBar;
         public JFrame frame;
         private JLabel jLabel1;
         private JLabel jLabel2;
         private JLabel jLabel3;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel6;
         private JComboBox jComboBox1;
         private JComboBox jComboBox2;
         private JComboBox jComboBox3;
         private JComboBox jComboBox4;
         private JComboBox jComboBox5;
         private JComboBox jComboBox6;
         private JTable jTable1;
         private JScrollPane jScrollPane1;
         private JPanel contentPane;
         public newssa()
              super();
              initializeComponent();
              this.setVisible(true);
         private void initializeComponent()
              jLabel1 = new JLabel();
              jLabel2 = new JLabel();
              jLabel3 = new JLabel();
              jLabel4 = new JLabel();
              jLabel5 = new JLabel();
              jLabel6 = new JLabel();
              jComboBox1 = new JComboBox();
              jComboBox2 = new JComboBox();
              jComboBox3 = new JComboBox();
              jComboBox4 = new JComboBox();
              jComboBox5 = new JComboBox();
              jComboBox6 = new JComboBox();
              frame=new JFrame();
              //Included here
              JMenuBar menuBar = new JMenuBar();
              JMenu general = new JMenu("General");
         menuBar.add(general);
         JMenu actions =new JMenu("Actions");
         menuBar.add(actions);
         JMenu view=new JMenu("View");
         menuBar.add(view);
         JMenu Timescale=new JMenu("TimeScale");
         menuBar.add(Timescale);
         Timescale.add("Today CTRL+D");
         Timescale.add("Current Week CTRL+W");
         Timescale.add("Current Month CTRL+M");
         Timescale.add("Current Quarter CTRL+Q");
         Timescale.add("Current Year CTRL+Y");
         Timescale.add("Custom TimeScale CTRL+U");
         JMenu start=new JMenu("Start");
         menuBar.add(start);
         JMenu options=new JMenu("Options");
         menuBar.add(options);
         JMenu help=new JMenu("Help");
         menuBar.add(help);
         JFrame.setDefaultLookAndFeelDecorated(true);
         frame.setJMenuBar(menuBar);
         frame.pack();
         frame.setVisible(true);
         toolBar = new JToolBar("Formatting");
         toolBar.addSeparator();
              //Before this included new
              String columnNames[] = { "ColorStatus", "Flash", "Service Order","Configuration","Configuration Description"};
              // Create some data
              String dataValues[][] =
                   { "blue", "flash", "ORT001" },
                   { "AVCONF", "av configuration with warrenty"}
              // Create a new table instance
              //jTable1 = new JTable( dataValues, columnNames );
              jTable1 = new JTable(dataValues,columnNames);
              jScrollPane1 = new JScrollPane(jTable1);
              contentPane = (JPanel)this.getContentPane();
              //scrollPane = new JScrollPane( table );
              //topPanel.add( scrollPane, BorderLayout.CENTER );
              // jLabel1
              jLabel1.setText("Service Centers");
              // jLabel2
              jLabel2.setText("Service Areas");
              // jLabel4
              jLabel3.setText("Skills");
              jLabel4.setText("Availablity Types");
              // jLabel5
              jLabel5.setText("From Date");
              // jLabel6
              jLabel6.setText("To");
              // jComboBox1
              jComboBox1.addItem("Coimbatore");
              jComboBox1.addItem("Chennai");
              jComboBox1.addItem("Mumbai");
              jComboBox1.addItem("New Delhi");
              jComboBox1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox1_actionPerformed(e);
              // jComboBox2
              jComboBox2.addItem("North Zone");
              jComboBox2.addItem("South Zone");
              jComboBox2.addItem("Central Zone");
              jComboBox2.addItem("Eastern Zone");
              jComboBox2.addItem("Western Zone");
              jComboBox2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox2_actionPerformed(e);
              // jComboBox3
              jComboBox3.addItem("Microsoft Components");
              jComboBox3.addItem("Java Technologies");
              jComboBox3.addItem("ERP");
              jComboBox3.addItem("Others");
              jComboBox3.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox3_actionPerformed(e);
              // jComboBox4
              jComboBox4.addItem("One");
              jComboBox4.addItem("Two");
              jComboBox4.addItem("Three");
              jComboBox4.addItem("Four");
              jComboBox4.addItem("Five");
              jComboBox4.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox4_actionPerformed(e);
              // jComboBox5
              jComboBox5.addItem("12/12/2004");
              jComboBox5.addItem("13/12/2004");
              jComboBox5.addItem("14/12/2004");
              jComboBox5.setEditable(true);
              jComboBox5.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox5_actionPerformed(e);
              // jComboBox6
              jComboBox6.addItem("12/11/2004");
              jComboBox6.addItem("13/11/2004");
              jComboBox6.addItem("14/11/2004");
              jComboBox6.setEditable(true);
              jComboBox6.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jComboBox6_actionPerformed(e);
              // jTable1
              jTable1.setModel(new DefaultTableModel(4, 4));
              // jScrollPane1
              jScrollPane1.setViewportView(jTable1);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 2,29,84,18);
              addComponent(contentPane, jLabel2, 201,33,76,18);
              addComponent(contentPane, jLabel3, 384,32,59,18);
              addComponent(contentPane, jLabel4, 2,77,85,18);
              addComponent(contentPane, jLabel5, 197,79,84,18);
              addComponent(contentPane, jLabel6, 384,80,60,18);
              addComponent(contentPane, jComboBox1, 85,32,100,22);
              addComponent(contentPane, jComboBox2, 276,32,100,22);
              addComponent(contentPane, jComboBox3, 419,30,100,22);
              addComponent(contentPane, jComboBox4, 88,76,100,22);
              addComponent(contentPane, jComboBox5, 276,79,100,22);
              addComponent(contentPane, jComboBox6, 421,78,100,22);
              addComponent(contentPane, jScrollPane1, 33,158,504,170);
              // newssa
              this.setTitle("SSA Service Scheduler");
              this.setLocation(new Point(0, 0));
              this.setSize(new Dimension(560, 485));
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jComboBox1_actionPerformed(ActionEvent e)
              int index = jComboBox1.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("Area Coimbatore Selected "); break;
                   case 1: System.out.println("Area Chennai selected"); break;
                   case 2: System.out.println("Mumbai being selected"); break;
                   case 3: System.out.println("New Delhi being selected"); break;
         private void jComboBox2_actionPerformed(ActionEvent e)
              int index = jComboBox2.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("North Zone Selcted "); break;
                   case 1: System.out.println("South Zone being selected"); break;
                   case 2: System.out.println("Central Zone being selected"); break;
                   case 3: System.out.println("Eastern Zone being selected"); break;
                   case 4: System.out.println("Western Zone being selected"); break;
         private void jComboBox3_actionPerformed(ActionEvent e)
              int index = jComboBox3.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("Microsoft Components being selected"); break;
                   case 1: System.out.println("Java Technologies being selected"); break;
                   case 2: System.out.println("ERP Tehnologies being selected"); break;
                   case 3: System.out.println("Other's selected"); break;
         private void jComboBox4_actionPerformed(ActionEvent e)
              int index = jComboBox4.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("One selected"); break;
                   case 1: System.out.println("Two selected"); break;
                   case 2: System.out.println("Three selected"); break;
                   case 3: System.out.println("Four selected"); break;
                   case 4: System.out.println("Five selected"); break;
         private void jComboBox5_actionPerformed(ActionEvent e)
              int index = jComboBox5.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("12/12/2004 being selected"); break;
                   case 1: System.out.println("13/12/2004 being selected"); break;
                   case 2: System.out.println("14/12/2004 being selected"); break;
         private void jComboBox6_actionPerformed(ActionEvent e)
              int index = jComboBox6.getSelectedIndex();
              switch(index)
                   case 0: System.out.println("12/11/2004 being selected"); break;
                   case 1: System.out.println("13/11/2004 being selected"); break;
                   case 2: System.out.println("14/11/2004 being selected"); break;
         public static void main(String[] args)
              newssa ssa=new newssa();
              //JFrame.setDefaultLookAndFeelDecorated(true);
              //JDialog.setDefaultLookAndFeelDecorated(true);
              //JFrame frame = new JFrame("SSA Service Scheduler");
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.setJMenuBar(ssa.menuBar);
    //frame.getContentPane( ).add(ssa.toolBar, BorderLayout.NORTH);
    //frame.getContentPane( ).add(ssa.pane, BorderLayout.CENTER);
    //frame.pack( );
    //frame.setVisible(true);
              try
                   //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
    But as a O/P ,I am getting menu in a seperate windos and the rest of the combobox and jtable in a seperate window.Kindly help me to solve the application.
    VERY URGENT PLEASE..
    Thanks in advance
    with kind regds
    Satheesh.K

    But did u mean this as the next problem,Which I will come across..Yes, the second setVisible(true) seemed to be producing a smaller frame behind the main frame.
    And your JMenuBar is declared twice, but not sure if this will affect the code - haven't read it all.

  • In Unix, main JFrame focus not regained after modal dialog exit.

    Hi all,
    I'm new to this forum so hopefully this is the right place to put this question.
    I have a relatively simple GUI application written in Java 6u20 that involves a main gui window (extends JFrame). Most of the file menu operations result in a modal dialog (either JFileChooser or JOptionPane) being presented to the user.
    The problem is that when running on Unix (HPUX), the process of changing focus to one of these modal dialogs occasionally results in a quick flash of the background terminal window (not necessarily that used to launch the Java), and the process of closing the modal dialogs (by any means, i.e. any dialog button or hitting esc) doesn't always return focus to the main extended JFrame object, sometimes it goes to the terminal window and sometimes just flashes the terminal window before returning to the main JFrame window.
    I think the problem is with the Unix window manager deciding that the main focus should be a terminal window, not my Java application, since the problem occurs in both directions (i.e. focus from main JFrame to modal dialog or vice versa).
    In most cases of JOptionPane, I DO specify that the main extended JFrame object is the parent.
    I've tried multiple things since the problem first occured, including multiple calls to a method which calls the following:
    .toFront();
    .requestFocus();
    .setAlwaysOnTop(true);
    .setVisible(true);
    ..on the main JFrame window (referred to as a public static object)...
    just before and after dialog display, and following selection of any button from the dialogs. This reduced the frequency of the problem, but it always tends to flash the terminal window if not return focus to it completely, and when it occurs (or starts to occur then gets worse) is apparently random! (which makes me think it's an OS issue)
    Any help appreciated thanks,
    Simon
    Self-contained compilable example below which has the same behaviour, but note that the problem DOESN'T occur running on Windows (XP) and that my actual program doesn't use auto-generated code generated by a guibuilder:
    * To change this template, choose Tools | Templates 
    * and open the template in the editor. 
    package example;  
    import javax.swing.JOptionPane;  
    * @author swg 
    public class Main {  
         * @param args the command line arguments 
        public static void main(String[] args) {  
            java.awt.EventQueue.invokeLater(new Runnable() {  
                public void run() {  
                    new NewJFrame().setVisible(true);  
    class NewJFrame extends javax.swing.JFrame {  
        /** Creates new form NewJFrame */ 
        public NewJFrame() {  
            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. 
        @SuppressWarnings("unchecked")  
        // <editor-fold defaultstate="collapsed" desc="Generated Code">  
        private void initComponents() {  
            jMenuBar1 = new javax.swing.JMenuBar();  
            jMenu1 = new javax.swing.JMenu();  
            jMenuItem1 = new javax.swing.JMenuItem();  
            jMenu2 = new javax.swing.JMenu();  
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
            jMenu1.setText("File");  
            jMenuItem1.setText("jMenuItem1");  
            jMenuItem1.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jMenuItem1ActionPerformed(evt);  
            jMenu1.add(jMenuItem1);  
            jMenuBar1.add(jMenu1);  
            jMenu2.setText("Edit");  
            jMenuBar1.add(jMenu2);  
            setJMenuBar(jMenuBar1);  
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());  
            getContentPane().setLayout(layout);  
            layout.setHorizontalGroup(  
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGap(0, 400, Short.MAX_VALUE)  
            layout.setVerticalGroup(  
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGap(0, 279, Short.MAX_VALUE)  
            pack();  
        }// </editor-fold>  
        private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {  
            int result = JOptionPane.showConfirmDialog(this, "hello");  
        // Variables declaration - do not modify  
        private javax.swing.JMenu jMenu1;  
        private javax.swing.JMenu jMenu2;  
        private javax.swing.JMenuBar jMenuBar1;  
        private javax.swing.JMenuItem jMenuItem1;  
        // End of variables declaration  
    }

    It won't comfort you much, but I had similar problems on Solaris 10, and at the time we traked them down to a known bug [6262392|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6262392]. The status of this latter is "Closed, will not fix", although it is not explained why...
    It's probably because the entry is itself related to another, more general, bug [6888200|http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=b6eea0fca217effffffffe82413c8a9fce16?bug_id=6888200], which is still open.
    So it is unclear whether this problem will be worked upon (I suspect that yes) and when (I suspect that... not too soon, as it's been dormant for several years!).
    None of our attempts (+toFront(...)+ etc...) solved the issue either, and they only moderately lowered the frequency of occurrence.
    I left the project since then, but I was said that the workaround mentioned in the first bug entry (see comments) doesn't work, whereas switching to Java Desktop instead of CDE reduced the frequency of the issues (without fixing them completely either) - I don't know whether it's an option on HPUX.
    Edited by: jduprez on Jul 9, 2010 11:29 AM

  • Simon game. buttons wont flash... help!

    This is a simple "Simon" memory game, produced in GUI...........
    The main(); invokes the FIRE(); which generates random numbers , which in turns invokes one of four COLOR methods, red(), green(), yellow(), blue(); .... These methods flash one of the four buttons and are assigned their own values. when they are invoked, they pass that value to Pattern();
    Pattern (); fills an array with the random values passed from the color methods, As well as compares users entry against the array and IF user entry is accurate then increase difficulty++
    (Pattern method has poor logic in it. I would like tips on this.)
    PROBLEM: it executes nearly perfect the first time the code cycles. After that the buttons no longer flash when the FIRE(); invokes COLOR(); methods.
    THANKS IN ADVANCE FOR YOUR HELP.
    import java.io.File;
       import java.io.IOException;
       import javax.sound.sampled.AudioFormat;
       import javax.sound.sampled.AudioInputStream;
       import javax.sound.sampled.AudioSystem;
       import javax.sound.sampled.DataLine;
       import javax.sound.sampled.LineUnavailableException;
       import javax.sound.sampled.SourceDataLine;
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
       import java.util.*;
        public class Simon extends JFrame implements MouseListener,ActionListener
          //static int pat=1;
          private static final int     EXTERNAL_BUFFER_SIZE = 128000;
          static JButton but1 = new JButton("Green");
          static JButton but2 = new JButton("Blue");
          static JButton but3 = new JButton("Orange");
          static JButton but4 = new JButton("Red");
          static JPanel pane1 = new JPanel();
          static JPanel pane2 = new JPanel();
          static JPanel pane3 = new JPanel();
          static JPanel pane4 = new JPanel();
          static JPanel pane5 = new JPanel();
          static JButton but5 = new JButton("Start");
          //static JLabel lab1 = new JLabel("Simon Says");
          Container con = getContentPane();
          static File soundFile = new File("hiho.wav");
          static File utopia = new File("utopia.wav");
          static File cowbell = new File("cowbell.wav");
          static File slap = new File("sound16.wav");
          static int G1=1,B2=2,Y3=3,R4=4;
          static int[] array = new int[256]; // maximum value
          static int difficulty = 3; //initial value
          static int count;
          static int x=0;
          static boolean click=false;
           public Simon()
             super("Simon Says");
             con.setLayout(new BorderLayout());
             con.add(pane5,BorderLayout.CENTER);
             con.add(pane4,BorderLayout.NORTH);
             con.add(pane3,BorderLayout.SOUTH);
             con.add(pane2,BorderLayout.EAST);
             con.add(pane1,BorderLayout.WEST);
             pane1.add(but1);
             pane2.add(but2);
             pane3.add(but3);
             pane4.add(but4);
             pane5.add(but5);
             but1.addMouseListener(this);
             but2.addMouseListener(this);
             but3.addMouseListener(this);
             but4.addMouseListener(this);
             but1.addActionListener(this);
             but2.addActionListener(this);
             but3.addActionListener(this);
             but4.addActionListener(this);
             but5.addActionListener(this);
           public static void main(String[]args)
             JFrame af = new Simon();
             af.setSize(275,135);
             Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
             af.setLocation( (screenSize.width - af.getWidth())/2,
                (screenSize.height - af.getHeight())/2 );
             af.setVisible(true);
             af.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             af.setResizable(false);
             but1.setContentAreaFilled(false);
             but1.setOpaque(true);//enabling button to changed with mouse events.
             but2.setContentAreaFilled(false);
             but2.setOpaque(true);
             but3.setContentAreaFilled(false);
             but3.setOpaque(true);
             but4.setContentAreaFilled(false);
             but4.setOpaque(true);
             but1.setBackground(Color.darkGray);
             but1.setForeground(Color.WHITE);
             but2.setBackground(Color.darkGray);
             but2.setForeground(Color.WHITE);
             but3.setBackground(Color.darkGray);
             but3.setForeground(Color.WHITE);
             but4.setBackground(Color.darkGray);
             but4.setForeground(Color.WHITE);
                // everytime the pattern fires a button it invokes a method which
                // recieves an int ... fills an array with digits. and before the int
                // is assigned a subscript a variable is incremented so the array continues
                // to cycle. 
                //store the last pattern in an array then, and do a check if they match generate new pattern.
             FIRE();
           public static void FIRE()
             for(x=0;x<difficulty;++x)
                double rnd = Math.random()*10;
                if (rnd<2.5)
                   play(soundFile);   
                   green();
                else if (rnd>=2.5&&rnd<=5.0)
                   play(utopia);
                   blue();
                else if (rnd>5.0&&rnd<=7.5)
                   play(cowbell);
                   yellow();
                else //if (rnd>7.5);
                   play(slap);
                   red();
             if(x==difficulty)
                count=0;
           public static void green()///////////////////////////////////////////////////////
             but1.setBackground(Color.GREEN);
             but1.setForeground(Color.WHITE);
             try
                Thread.sleep(200);
                 catch(InterruptedException e){}
             but1.setBackground(Color.darkGray);
             but1.setForeground(Color.WHITE);   
             try
                Thread.sleep(200);
                 catch(InterruptedException e){}
             Pattern(G1);
           public static void blue()////////////////////////////////////////////////////
             but2.setBackground(Color.BLUE);
             but2.setForeground(Color.WHITE);
             try
                Thread.sleep(200);
                 catch(InterruptedException e){}
             but2.setBackground(Color.darkGray);
             but2.setForeground(Color.WHITE);
             try
                Thread.sleep(200);
                 catch(InterruptedException e){}
             Pattern(B2); 
           public static void yellow()///////////////////////////////////////////////////////
             but3.setBackground(Color.ORANGE);
             but3.setForeground(Color.WHITE);
             try
                Thread.sleep(200);
                 catch(InterruptedException e){}
             but3.setBackground(Color.darkGray);
             but3.setForeground(Color.WHITE);
             try
                Thread.sleep(200);
                 catch(InterruptedException e){}
             Pattern(Y3); 
           public static void red()//////////////////////////////////////////////////////////
             but4.setBackground(Color.RED);
             but4.setForeground(Color.WHITE);
             try
                Thread.sleep(200);
                 catch(InterruptedException e){}
             but4.setBackground(Color.darkGray);
             but4.setForeground(Color.WHITE);
             try
                Thread.sleep(200);
                 catch(InterruptedException e){}
             Pattern(R4);
           public void mousePressed(MouseEvent e)////////////////////////////////////////////////////////////////
             //System.out.println(" Count Equals before Fire()"+count);
             Object source = e.getSource();
             if (source==but1)
                click = true;
                but1.setBackground(Color.GREEN);
                but1.setForeground(Color.WHITE);
                play(soundFile);
                Pattern(G1);
             if(source==but2)
                click = true;
                but2.setBackground(Color.BLUE);
                but2.setForeground(Color.WHITE);
                play(utopia);
                Pattern(B2);
             if (source==but3)
                click = true;
                but3.setBackground(Color.orange);
                but3.setForeground(Color.WHITE);
                play(cowbell);
                Pattern(Y3);
             if (source==but4)
                click = true;
                but4.setBackground(Color.RED);
                but4.setForeground(Color.WHITE);
                play(slap);
                Pattern(R4);
           public void mouseReleased(MouseEvent e)/////////////////////////////////////////////////////////////
             Object source = e.getSource();
             if(source==but1)
                but1.setBackground(Color.darkGray);
                but1.setForeground(Color.WHITE); 
             else if (source==but2)
                but2.setBackground(Color.darkGray);
                but2.setForeground(Color.WHITE);
             else if (source==but3)
                but3.setBackground(Color.darkGray);
                but3.setForeground(Color.WHITE);
             else if (source==but4)
                but4.setBackground(Color.darkGray);
                but4.setForeground(Color.WHITE);
           public static void Pattern(int A)/////////////////////////////////////////////////////////////
             if (x<difficulty)
                array[count]=A;
                System.out.println("Randomly generated array position "+count+"'s value is, "+A);
                ++count;
             if (x==difficulty)
                System.out.println(".....User entry at array position "+count+"'s value is, "+A);       
                if (array[count]==A&&count==difficulty-1) //if user entry is correct and the array has reached
                   NEXT();
                                                                     //array.length then invoke NEXT();    
                if (A!=array[count]/*&&count<difficulty*/&&count!=0)//poor logic: at anytime if array[count] is not equal to user entry, LOSE();        
                   LOSE();
                if (click==true)       
                   count++; 
             click =false;                
           public static void LOSE()
             System.out.println("YOU LOSE");
             System.exit(0);
           public static  void NEXT()
         //     String[] s = null;
             System.out.println("NEXT LEVEL");
             ++difficulty;
             count=0;
             x=0;
               // Simon.main((s = new String[] {"N"}));
             FIRE();
           public static void play(File soundFile)////////////////////////////////// AUDIO PLAYER
             AudioInputStream     audioInputStream = null;
             try
                audioInputStream = AudioSystem.getAudioInputStream(soundFile);
                 catch (Exception e)
                   e.printStackTrace();
                   System.exit(1);
             AudioFormat     audioFormat = audioInputStream.getFormat();
             SourceDataLine     line = null;
             DataLine.Info     info = new DataLine.Info(SourceDataLine.class,audioFormat);
             try
                line = (SourceDataLine) AudioSystem.getLine(info);
                line.open(audioFormat);
                 catch (LineUnavailableException e)
                   e.printStackTrace();
                   System.exit(1);
                 catch (Exception e)
                   e.printStackTrace();
                   System.exit(1);
             line.start();
             int     nBytesRead = 0;
             byte[]     abData = new byte[EXTERNAL_BUFFER_SIZE];
             while (nBytesRead != -1)
                try
                   nBytesRead = audioInputStream.read(abData, 0, abData.length);
                    catch (IOException e)
                      e.printStackTrace();
                if (nBytesRead >= 0)
                   int     nBytesWritten = line.write(abData, 0, nBytesRead);
          //       line.drain();
          //          line.close();
             //System.exit(0);
           private void printUsageAndExit()
             out("SimpleAudioPlayer: usage:");
             out("\tjava SimpleAudioPlayer <soundfile>");
             System.exit(1);
           private void out(String strMessage)
             System.out.println(strMessage);
           public void actionPerformed(ActionEvent e)//OVERRIDDEN INTERFACE METHODS
           public void mouseClicked(MouseEvent e)
           public void mouseEntered(MouseEvent e)
           public void mouseExited(MouseEvent e)
       }

    In the future, Swing related questions should be posted in the Swing forum.
    You don't use the Thread.sleep(...) method in the GUI Event Thread, it prevents the GUI from responding to events and repainting itself.
    Use a Swing Timer to schedule the frequency of whatever you are doing.

  • How to use Flash buttons/animation in a Swing/Applet?

    Hello,
    I want to use flash button as like as JButton that we use in Swing/ Applet. How can I do So?
    Please help me.
    Thanks-

    [http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html]
    Or maybe just...
    import java.awt.*;
    import java.net.*;
    import javax.swing.*;
    public class Blinky {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    URL url = null;
                    try {
                        url = new URL("http://www.gifanimations.com/GA/image/animations/bodyparts/eyes/eye-01.gif");
                    } catch (MalformedURLException e) {
                        throw new RuntimeException(e);
                    JFrame f = new JFrame("Blinky");
                    f.getContentPane().add(new JButton(new ImageIcon(url)));
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.pack();
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }

  • Long delay during first resize of visible JFrame (help!)

    I need to increase the size of a component in a visible JFrame (and with it the size of the frame itself). The way I did this using jdk 1.3.1 causes a problem in 1.4.0 and 1.4.1.
    When a component in a visible JFrame (such as a JPanel) is resized - using a setPreferredSize()-pack() sequence, there is a VERY long delay (~ 5 seconds) before the frame is fully redrawn. This only occurs the FIRST time the component is resized. Subsequent setPreferredSize()-pack() sequences take a reasonable amount of time.
    Here's a simple example:
    import java.awt.*;
    import javax.swing.*;
    public class PackDelayTest extends JFrame {
        JPanel pan;
        int width;
        static long tm;
        public static void main(String[] argv) {
                tm = System.currentTimeMillis();
            PackDelayTest2 test = new PackDelayTest();
                elapsed("in constructor");
            test.replace(); elapsed("repack 1");
            test.replace(); elapsed("repack 2");
            test.replace(); elapsed("repack 2");
            test.replace(); elapsed("repack 2");  
            System.exit(0);
        public PackDelayTest() {
            pan = new JPanel();
            pan.setLayout(new BoxLayout(pan,BoxLayout.Y_AXIS));
            getContentPane().add(pan);        
            JLabel label = new JLabel("Label 0");
            pan.add(label);  
            pack();
            setVisible(true);
            width = pan.getPreferredSize().width;
        public void replace() {            
           Dimension d = pan.getPreferredSize();
           pan.setPreferredSize(new Dimension(++width,d.height));     
           pack();
        static void elapsed(String mess) {
            long ct = System.currentTimeMillis();
            System.out.println("Elapsed milliseconds, " + mess + ": " +
                               (ct - tm));
            tm = ct;
    }Running this with Sun jdk 1.3.1 yields the timings:
    Elapsed milliseconds, in constructor: 2226
    Elapsed milliseconds, repack 1: 26
    Elapsed milliseconds, repack 2: 24
    Elapsed milliseconds, repack 2: 25
    Elapsed milliseconds, repack 2: 24Running the same code with jdk 1.4.1_0 yields
    Elapsed milliseconds, in constructor: 1773
    Elapsed milliseconds, repack 1: [bold]5747[/bold]
    Elapsed milliseconds, repack 2: 32
    Elapsed milliseconds, repack 2: 7
    Elapsed milliseconds, repack 2: 1Note the FIVE SECOND delay during the first setPreferredSize()- pack() sequence.
    This problem also occurs with 1.4.0, Blackdown 1.4.1 and IBM 1.4.0, so presumably it is something in Sun's 1.4 code.
    The only way I've found to avoid the initial delay is to set frame invisible
    before the setPreferredSize(), pack() sequence and visible afterwards. But of course this makes the window 'flash' and is very unplesant for users.
    I've looked at the source for pack() but it hasn't gotten me anywhere. If anyone has an idea about fixing this problem or working around it, I'd appreciate hearing about it.
    FYI I ran these tests under Linux, vanilla installations of SuSE 8.0 and 8.1
    Thanks,
    bw

    It turns out that this problem occurs under SuSE (8.0 and 8.1) but NOT under Redhat 8.0
    I do NOT understand how this is possible, but it is the case. Has anyone encountered any SuSE specific problems?
    fyi I've reproduced the problem on two rather different i386 machines (an AMD k7 and a Pentium III thinkpad), so it certainly doesn't have anything to do with hardware.
    bw

  • Gentoo doesn't run a Java (Flash) application but Ubuntu yes

    Hello everybody.
    I can't find a solution to a Java-Flash-Gentoo related problem.
    I would like to run a Java program, using an [external library|http://djproject.sourceforge.net/ns/] , to realize a Java FlashPlayer. This is the code of the player:
    package testplayer;
    import chrriis.dj.nativeswing.swtimpl.NativeInterface;
    import chrriis.dj.nativeswing.swtimpl.components.JFlashPlayer;
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Main implements Runnable {
        public static void main(String[] args) {
            NativeInterface.open();
            EventQueue.invokeLater(new Main());
            NativeInterface.runEventPump();
        public void run() {
            JFlashPlayer player = new JFlashPlayer();
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(player);
            JFrame window = new JFrame("Test");
            window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            window.add(panel);
            window.setSize(400, 400);
            window.setVisible(true);
            player.load("http://www.youtube.com/v/XyX-KJwUohw");
    }A window should be opened and the youtube video should play as well. Here's what I get on Gentoo Linux.
    [http://i.imgur.com/XyYdk.png]
    It doesn't find the flash plugin actually, even though it is installed and properly working.
    My Gentoo is x86_64 architecture and if I try to run the same application on Ubuntu (x86_64), it works like a charm.
    At the moment my www-plugins/adobe-flash USE flags are the following: 64bit -32bit.
    Why this piece of code runs on Ubuntu and on Gentoo not????
    Could it be something related to some environment variable?
    Thanks a lot!

    I asked to the mantainers yet actually, but they didn't solve me the problem at the moment.
    Perhaps some of you could have an idea of what I am missing on Gentoo.
    What I can tell you, is that I tried to run that application on a fresh Debian installation and I've got the same problem.
    So this happens because of something that is missing. But what?? :(

  • Cant dispose a JFrame

    hi
    i'm having a problem with jFrame disposion. i have a login JDialog, that launches JFrame. After logoff - the same JDialog appears. And when i call JFrame again - i get 2 flashing frames, that are disabling/enabling one another, and swithing from one to another. after some accurate clicks in taskbar - forms stop flicker, but i still have 2 of them.
    then you may try to logoff and login again from one of them - and guess what - i get 4 flikering frames. dammit.
    how to completely dispose Frame?
    tryed everything in forums with keyword "dispose". no luck.
    many many many thanx.

    I presume your are calling frame.dispose() from your Dialog window, and not trying to be clever by calling it in your finalizer? Additionally, you could setframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

  • JFrame background color

    I have a JFrame and I'm setting the background color in the constructor:
    frame.setBackground(Color.green);
    The frame opens up, and the background color flashes green for an instant, then it goes back to grey. What am I missing? Do I have to set the background color in the paint() method?
    TIA,
    Rich

    I found a post from back in April about setting the background color of the contentPane instead, and that works.
    Thanks anyway!
    Rich

  • Flashing Border in Java ...

    I've spent about three days looking for a way to make a flashing border in Java.
    I want to be able to play the game while this border flashes around the title.
    What is the best recommended method to do this .. and why .. and how? .. Swing timers ? background loop?
    Please help, I'm under the gun on an assignment!

    Yes I know about the Thread problems in swing ... but I'll let you fix up the code if you like - this will at least paint a Border and flash it:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class IsBorderOrNot {
      private JFrame jf;
      private JPanel jp;
      private EmptyBorder eb;
      private MatteBorder mb;
      public IsBorderOrNot() {
        jf = new JFrame("IsBorderOrNot");
        jp = new JPanel();
        eb = new EmptyBorder(5, 5, 5, 5);
        mb = new MatteBorder(5, 5, 5, 5, Color.BLUE);
        jp.add(new JTextArea(10,10));
        jf.getContentPane().add(jp);
        new Thread() {
          public void run() {
            boolean isRunning = true;
            while(isRunning) {
              try {
                jp.setBorder(eb);
                Thread.sleep(100);
                jp.setBorder(mb);
                Thread.sleep(100);
              } catch(InterruptedException ie) {
                System.out.println(ie);
        }.start();
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      public static void main(String[] argv) {
    //    new IsBorderOrNot();
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            new IsBorderOrNot();
    }

  • Why the painted content flash and disappear?

    I try to run a simple code example from java almanac site but the painted content just flash and disappear. Can any people help to find the reason? Thanks in advance.
    Below are the code:
    package font;
    import java.text.AttributedString;
    import java.awt.*;
    import java.awt.font.LineBreakMeasurer;
    import java.awt.font.TextLayout;
    import javax.swing.*;
    public class DrawParagraphDemo extends JPanel {
        public DrawParagraphDemo() {
            this.setPreferredSize(new Dimension(500,500));
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("Demo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            DrawParagraphDemo demo = new DrawParagraphDemo();
            frame.setContentPane(demo);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
            demo.drawParagraph((Graphics2D) demo.getGraphics(), "One line of test string", 400);
        public void drawParagraph(Graphics2D g, String paragraph, float width) {
            LineBreakMeasurer linebreaker = new LineBreakMeasurer(
                new AttributedString(paragraph).getIterator(), g.getFontRenderContext());
            float y = 0.0f;
            while (linebreaker.getPosition() < paragraph.length()) {
                TextLayout tl = linebreaker.nextLayout(width);
                System.out.println(tl);
                y += tl.getAscent();
                tl.draw(g, 0, y);
                y += tl.getDescent() + tl.getLeading();
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Hi i have similar problem and i have followed Camickr's suggestion but it looks like my image was still being painted over here's my code
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    * FileChooserDemo2.java is a 1.4 application that requires these files:
    *   ImageFileView.java
    *   ImageFilter.java
    *   ImagePreview.java
    *   Utils.java
    *   images/jpgIcon.gif (required by ImageFileView.java)
    *   images/gifIcon.gif (required by ImageFileView.java)
    *   images/tiffIcon.gif (required by ImageFileView.java)
    *   images/pngIcon.png (required by ImageFileView.java)
    public class Asst4 extends JPanel
                                  implements ActionListener {
        static private String newline = "\n";
        private JTextArea log;
        private JFileChooser fc;
         private JPanel display,button;
         JButton load,grey,color;
         private Image image;
         static JComponent newContentPane;
        public Asst4() {
            super(new BorderLayout());
            //Create the log first, because the action listener
            //needs to refer to it.
              display=new JPanel();
              display.setOpaque(true);
              button=new JPanel();
              load=new JButton("Load Image");
              grey=new JButton("Greyscale Image");
              color=new JButton("Color Image");
              load.addActionListener(this);
              //display.setBackground(Color.BLACK);
              //System.out.println("displayable: "+isDisplayable()+" visible: "+isVisible()+" valid: "+isValid());
              //System.out.println("displayable: "+display.isDisplayable()+" visible: "+display.isVisible()+" valid: "+display.isValid());
              display.setSize(500,500);
              button.add(load, BorderLayout.WEST);
              button.add(grey, BorderLayout.CENTER);
              button.add(color, BorderLayout.EAST);
              add(button,BorderLayout.NORTH);
              add(display,BorderLayout.CENTER);
              setVisible(true);
        public void actionPerformed(ActionEvent e) {
                   //Set up the file chooser.
                   if (fc == null) {
                        fc = new JFileChooser();
                        //Add a custom file filter and disable the default
                        //(Accept All) file filter.
                        fc.addChoosableFileFilter(new ImageFilter());
                        fc.setAcceptAllFileFilterUsed(false);
                        //Add custom icons for file types.
                        fc.setFileView(new ImageFileView());
                        //Add the preview pane.
                        fc.setAccessory(new ImagePreview(fc));
                        //Show it.
                   int returnVal = fc.showDialog(Asst4.this,"Load Image");
                   //Process the results.
                   if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        Toolkit toolkit = Toolkit.getDefaultToolkit();
                        image = toolkit.getImage(file.getAbsolutePath());
                        MediaTracker mediaTracker = new MediaTracker(this);
                        mediaTracker.addImage(image,0);
                        try {
                           mediaTracker.waitForID(0);
                        } catch (InterruptedException ie) {
                           System.err.println(ie);
                           System.exit(1);
                   } else {
                        System.out.println("Loading cancelled by user." );
                   fc.setSelectedFile(null);
        protected void paintComponent(Graphics g)
              super.paintComponent(g); // this paints the background
              if(image!=null)
              drawImage(image);
        private void drawImage(Image image){
              Graphics2D g=(Graphics2D)display.getGraphics();
              g.drawImage(image,0,0,null);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            JDialog.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("Compsci_375_Assignment_4");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            newContentPane = new Asst4();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.setBounds(50,50,500,500);
               //frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }Can anyone tell me what's going on and also why if i pack the frame my display panel is disappear?
    Thanks a lot

Maybe you are looking for