Problem with JFrame, it goes blank

i
My problem is with JFrame, when it's carrying operation which takes a bit of time, if somethhing goes on
top of the frame the frame goes blank, all the components vanished and when the operation is completed the components bacome visible. I dont know why this is happening,. The code is below, since my code is very complicated I am sending some code whcih shows the problem I have, when you press the button it execute's a for loop, whcih takes some time. If you minimize the frame and maximize again, you'll see what I mean.
Please help!!!
Many Thanks
Lilylay
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Frame1 extends JFrame {
JPanel contentPane;
JButton jButton2 = new JButton();
/**Construct the frame*/
public Frame1() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
/**Component initialization*/
private void jbInit() throws Exception {
//setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(null);
this.setSize(new Dimension(407, 289));
this.setTitle("Frame Title");
contentPane.setBackground(SystemColor.text);
contentPane.setForeground(Color.lightGray);
jButton2.setText("Press me!");
jButton2.setBounds(new Rectangle(107, 111, 143, 48));
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(MouseEvent e) {
jButton2_mousePressed(e);
contentPane.add(jButton2, null);
/**Overridden so we can exit when window is closed*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
void jButton2_mousePressed(MouseEvent e) {
for(int i=0; i<256898; i++){
for(int j=0; j<5656585; j++){
System.out.println("hello");
public static void main(String [] args){
Frame1 frame=new Frame1();
frame.show();
}

The reason this is happening is because your loop is so intensive that your program doesn't have time to refresh its JFrame. There is no great way to get past this stumbling block without decreasing the efficiency of your code. One possible solution is to call repaint() from within your loop, but of course this slows down your loop.
Hope that helps

Similar Messages

  • Problem with JFrame's dispose();

    Hello everyone,
    I'm having a problem with JFrame's dispose() method. In my program I have 2 classes which go into full screen. On each screen there is a button to switch to the other screen. The first time I push the button on both of them the other screen closes, which is what I want. However, if I push the same button more than twice - like by going from Screen1 to Screen2 and Screen2 to Screen1 and then Screen1 to Screen2 - I get 2 screens. If I keep doing that I eventually get 10+ screens up, which is bad. How do I prevent that?

    There's a lot of code, so I'll just post up the part that does it.
    backButton.addActionListener(new ActionListener()
                  public void actionPerformed(ActionEvent e)
                      soundManagerM.close();
                        new MenuScreen().setVisible(true);
                        dispose();
             });I don't think it opens up 2 at once, because it would play multiple music right?

  • HT4199 Had problems with my broadband going down at weekend, since it came back on unable to join wifi BT say it is because my wifi settings are missing on my iPad can anyone tell me where to find seething details IP address etc

    Had problems with my broadband going down at weekend, since it came back on unable to join wifi BT say it is because my wifi settings are missing on my iPad can anyone tell me where to find seething details IP address etc

    Some things to try first:
    1. Turn Off your iPad. Then turn Off (disconnect power cord for 30 seconds or longer) the wireless router & then back On. Now boot your iPad. Hopefully it will see the WiFi.
    2. Go to Settings>Wi-Fi and turn Off. Then while at Settings>Wi-Fi, turn back On and chose a Network.
    3. Change the channel on your wireless router (Auto or Channel 6 is best). Instructions at http://macintoshhowto.com/advanced/how-to-get-a-good-range-on-your-wireless-netw ork.html
    4. Go into your router security settings and change from WEP to WPA with AES.
    5.  Renew IP Address: (especially if you are drooping internet connection)
        •    Launch Settings app
        •    Tap on Wi-Fi
        •    Tap on the blue arrow of the Wi-Fi network that you connect to from the list
        •    In the window that opens, tap on the Renew Lease button
    6. Potential Quick Fixes When Your iPad Won’t Connect to Your Wifi Network
    http://ipadinsight.com/ipad-tips-tricks/potential-quick-fixes-when-your-ipad-won t-connect-to-your-wifi-network/
    ~~~~~~~~~~~~~~~~~~~~~~~~~
    Fix WiFi Issue for iOS 7
    http://ipadnerds.com/fix-wifi-issue-ios-7/
    iOS 6 Wifi Problems/Fixes
    Wi-Fi Fix for iOS 6
    https://discussions.apple.com/thread/4823738?tstart=240
    How To: Workaround iPad Wi-Fi Issues
    http://www.theipadfan.com/workaround-ipad-wifi-issues/
    Another Fix For iOS 6 WiFi Problems
    http://tabletcrunch.com/2012/10/27/fix-ios-6-wifi-problems-ssid/
    Wifi Doesn't Connect After Waking From Sleep - Sometimes increasing screen brightness prevents the failure to reconnect after waking from sleep. According to Apple, “If brightness is at lowest level, increase it by moving the slider to the right and set auto brightness to off.”
    Fix For iOS 6 WiFi Problems?
    http://tabletcrunch.com/2012/09/27/fix-ios-6-wifi-problems/
    Did iOS 6 Screw Your Wi-Fi? Here’s How to Fix It
    http://gizmodo.com/5944761/does-ios-6-have-a-wi+fi-bug
    How To Fix Wi-Fi Connectivity Issue After Upgrading To iOS 6
    http://www.iphonehacks.com/2012/09/fix-wi-fi-connectivity-issue-after-upgrading- to-ios-6.html
    iOS 6 iPad 3 wi-fi "connection fix" for netgear router
    http://www.youtube.com/watch?v=XsWS4ha-dn0
    Apple's iOS 6 Wi-Fi problems
    http://www.zdnet.com/apples-ios-6-wi-fi-problems-linger-on-7000004799/
    ~~~~~~~~~~~~~~~~~~~~~~~
    iPad: Issues connecting to Wi-Fi networks
    http://support.apple.com/kb/ts3304
    How to Boost Your Wi-Fi Signal
    http://ipad.about.com/od/iPad_Troubleshooting/a/How-To-Boost-Your-Wi-Fi-Signal.h Mt
    Troubleshooting a Weak Wi-Fi Signal
    http://ipad.about.com/od/iPad_Troubleshooting/a/Troubleshooting-A-Weak-Wi-Fi-Sig nal.htm
    How to Fix a Poor Wi-Fi Signal on Your iPad
    http://ipad.about.com/od/iPad_Troubleshooting/a/How-To-Fix-A-Poor-Wi-Fi-Signal-O n-Your-iPad.htm
    iOS Troubleshooting Wi-Fi networks and connections  http://support.apple.com/kb/TS1398
    iPad: Issues connecting to Wi-Fi networks  http://support.apple.com/kb/ts3304
    WiFi Connecting/Troubleshooting http://www.apple.com/support/ipad/wifi/
    How to Fix: My iPad Won't Connect to WiFi
    http://ipad.about.com/od/iPad_Troubleshooting/ss/How-To-Fix-My-Ipad-Wont-Connect -To-Wi-Fi.htm
    iOS: Connecting to the Internet http://support.apple.com/kb/HT1695
    iOS: Recommended settings for Wi-Fi routers and access points  http://support.apple.com/kb/HT4199
    How to Quickly Fix iPad 3 Wi-Fi Reception Problems
    http://osxdaily.com/2012/03/21/fix-new-ipad-3-wi-fi-reception-problems/
    iPad Wi-Fi Problems: Comprehensive List of Fixes
    http://appletoolbox.com/2010/04/ipad-wi-fi-problems-comprehensive-list-of-fixes/
    Connect iPad to Wi-Fi (with troubleshooting info)
    http://thehowto.wikidot.com/wifi-connect-ipad
    10 Ways to Boost Your Wireless Signal
    http://www.pcmag.com/article2/0,2817,2372811,00.asp
    Fix iPad Wifi Connection and Signal Issues  http://www.youtube.com/watch?v=uwWtIG5jUxE
    Fix Slow WiFi Issue https://discussions.apple.com/thread/2398063?start=60&tstart=0
    How To Fix iPhone, iPad, iPod Touch Wi-Fi Connectivity Issue http://tinyurl.com/7nvxbmz
    Unable to Connect After iOS Update - saw this solution on another post.
    https://discussions.apple.com/thread/4010130
    Note - When troubleshooting wifi connection problems, don't hold your iPad by hand. There have been a few reports that holding the iPad by hand, seems to attenuate the wifi signal.
    Some Wi-Fi losses may stem from a problematic interaction between Wi-Fi and cellular data connections. Numerous users have found that turning off Cellular Data in Settings gets their Wi-Fi working again.
    You may have many apps open which can possibly cause the slowdown and possibly the loss of wifi. In iOS 4-6 double tap your Home button & at the bottom of the screen you will see the icons of all open apps. Close those you are not using by pressing on an icon until all icons wiggle - then tap the minus sign. For iOS 7 users, there’s an easy way to see which apps are open in order to close them. By double-tapping the home button on your iPhone or iPad, the new multitasking feature in iOS 7 shows full page previews of all your open apps. Simply scroll horizontally to see all your apps, and close the apps with a simple flick towards the top of the screen.
    Wi-Fi or Bluetooth settings grayed out or dim
    http://support.apple.com/kb/TS1559
    ~~~~~~~~~~~~~~~
    If any of the above solutions work, please post back what solved your problem. It will help others with the same problem.
     Cheers, Tom

  • I had a problem with imac screen going black. apple store diagnosed prob with video card which they replaced. Brought it home, turned it on (have done this 4 times) it starts up, wheel turns, there is a long bar at bottom which fills up, then it turns off

    I had a problem with imac screen going black. apple store diagnosed prob with video card which they replaced. Brought it home, turned it on (have done this 4 times) it starts up, wheel turns, there is a long bar at bottom which fills up, then it turns off

    Apple guarantees their work, take it back.

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Problem with JFrame resizing at runtime

    Hi All,
    I have a problem with resizing the JFrame at runtime. Even if i resize the JPanel. It is not affection on all the components over the frame. How can i solve that I am using AbsoluteLayout(jre1.6) and here i am going to provide you code snippet. My requirement is to resizt the form. If form is small in size then all the component should also be according tothe size of the form.
    public void initComponents(int size) {
    if(size >= 50) {
    x_co_or = 300;
    y_co_or = 300;
    } else if(size < 50) {
    x_co_or = 200;
    y_co_or = 200;
    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jButton1.setText("jButton1");
    jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, 110, 40));
    getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, x_co_or, y_co_or));
    pack();
    Can anybody suggest any idea/solution.
    Any idea/solution are most welcome.
    Regards,
    Pradeep Dubey

    How can i solve that I am using AbsoluteLayout(jre1.6)
    and here i am going to provide you code snippet.no need for the snippet, you're using absolute positioning, which means you're responsible for location and size on every single change.
    start coding now, take about a week, or you could use a layout manager, take maybe, 5 minutes

  • Problem with JFrame and busy/wait Cursor

    Hi -- I'm trying to set a JFrame's cursor to be the busy cursor,
    for the duration of some operation (usually just a few seconds).
    I can get it to work in some situations, but not others.
    Timing does seem to be an issue.
    There are thousands of posts on the BugParade, but
    in general Sun indicates this is not a bug. I just need
    a work-around.
    I've written a test program below to demonstrate the problem.
    I have the problem on Solaris, running with both J2SE 1.3 and 1.4.
    I have not tested on Windows yet.
    When you run the following code, three JFrames will be opened,
    each with the same 5 buttons. The first "F1" listens to its own
    buttons, and works fine. The other two (F2 and F3) listen
    to each other's buttons.
    The "BUSY" button simply sets the cursor on its listener
    to the busy cursor. The "DONE" button sets it to the
    default cursor. These work fine.
    The "SLEEP" button sets the cursor, sleeps for 3 seconds,
    and sets it back. This does not work.
    The "INVOKE LATER" button does the same thing,
    except is uses invokeLater to sleep and set the
    cursor back. This also does not work.
    The "DELAY" button sleeps for 3 seconds (giving you
    time to move the mouse into the other (listerner's)
    window, and then it behaves just like the "SLEEP"
    button. This works.
    Any ideas would be appreciated, thanks.
    -J
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class BusyFrameTest implements ActionListener
    private static Cursor busy = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
    private static Cursor done = Cursor.getDefaultCursor();
    JFrame frame;
    JButton[] buttons;
    public BusyFrameTest (String title)
    frame = new JFrame (title);
    buttons = new JButton[5];
    buttons[0] = new JButton ("BUSY");
    buttons[1] = new JButton ("DONE");
    buttons[2] = new JButton ("SLEEP");
    buttons[3] = new JButton ("INVOKE LATER");
    buttons[4] = new JButton ("DELAY");
    JPanel buttonPanel = new JPanel();
    for (int i = 0; i < buttons.length; i++)
    buttonPanel.add (buttons);
    frame.getContentPane().add (buttonPanel);
    frame.pack();
    frame.setVisible (true);
    public void addListeners (ActionListener listener)
    for (int i = 0; i < buttons.length; i++)
    buttons[i].addActionListener (listener);
    public void actionPerformed (ActionEvent e)
    System.out.print (frame.getTitle() + ": " + e.getActionCommand());
    if (e.getActionCommand().equals ("BUSY"))
    frame.setCursor (busy);
    else if (e.getActionCommand().equals ("DONE"))
    frame.setCursor (done);
    else if (e.getActionCommand().equals ("SLEEP"))
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    else if (e.getActionCommand().equals ("INVOKE LATER"))
    frame.setCursor (busy);
    SwingUtilities.invokeLater (thread);
    else if (e.getActionCommand().equals ("DELAY"))
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    System.out.println();
    Runnable thread = new Runnable()
    public void run()
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.println (" finished");
    public static void main (String[] args)
    BusyFrameTest f1 = new BusyFrameTest ("F1");
    f1.addListeners (f1);
    BusyFrameTest f2 = new BusyFrameTest ("F2");
    BusyFrameTest f3 = new BusyFrameTest ("F3");
    f2.addListeners (f3); // 2 listens to 3
    f3.addListeners (f2); // 3 listens to 2

    I've had the same problems with cursors and repaints in a swing application, and I was thinking of if I could use invokeLater, but I never got that far with it.
    I still believe you would need a thread for the time consuming task, and that invokeLater is something you only need to use in a thread different from the event thread.

  • Problem with JFrame class.

    To risolve my problem i need for few diferent frame
    ( for esample in one i put JTextFild that take the user input, in a nother one i need for program output ) . But, th problem is, all my frames using the same object.
    If i construct diferent JFrame window class i have problem that i don't acess in the same object from all the window. And if i dont use a object, i have static acess .
    I risolve the problem with 1 JFrame class with diferent constructors, but i wont a diferent way to risolve my problem, because there are few windows.
    Help me.....

    Make the class that extends JFrame an inner class of the the main class. You can then access all members of the outer class.

  • Problem with JFrame code

    Can anyone say the problem with the attached code. When I run the program, only, maximize, minimize and close options are viewable and nothing else.
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Graphics;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.border.LineBorder;
    * Created on Mar 24, 2008
    * @author Anand
    public class JBackGroundImageDemo extends JFrame
        Container con = null;
        JPanel panelBgImg;
        public JBackGroundImageDemo()
            setTitle("JBackGroundImageDemo");
            con = getContentPane();
            con.setLayout(null);
            ImageIcon imh = new ImageIcon("aditi.jpg");
            setSize(imh.getIconWidth(), imh.getIconHeight());
            panelBgImg = new JPanel()
                public void paintComponent(Graphics g)
                    Image img = new ImageIcon("aditi.jpg").getImage();
                    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                    setPreferredSize(size);
                    setMinimumSize(size);
                    setMaximumSize(size);
                    setSize(size);
                    setLayout(null);
                    g.drawImage(img, 0, 0, null);
            con.add(panelBgImg);
            panelBgImg.setBounds(0, 0, imh.getIconWidth(), imh.getIconHeight());
            GridBagLayout layout = new GridBagLayout();
            JPanel panelContent = new JPanel(layout);
            GridBagConstraints gc = new GridBagConstraints();
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 1;
            JLabel label = new JLabel("UserName: ", JLabel.LEFT);                       
            panelContent.add(label, gc);
            gc.gridx = 2;
            gc.gridy = 1;
            JTextField txtName = new JTextField(10);
            panelContent.add(txtName, gc);
            gc.insets = new Insets(3, 3, 3, 3);
            gc.gridx = 1;
            gc.gridy = 2;
            gc.gridwidth = 2;
            JButton btn = new JButton("Login");
            panelContent.add(btn, gc);
            panelContent.setBackground(Color.GRAY);
            panelContent.setBorder(new LineBorder(Color.WHITE));
            panelBgImg.add(panelContent);
            panelBgImg.setLayout(new FlowLayout(FlowLayout.CENTER, 150, 200));
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String[] args)
            new JBackGroundImageDemo().setVisible(true);
         Please help.
    Regards,
    Anees

    Here's you a little code example, it works, so take a look at it.
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Junk{
      public Junk(){
      public void makeFrame(){
        JFrame j = new JFrame("Junk");
        Toolkit t = Toolkit.getDefaultToolkit();
        MediaTracker mt = new MediaTracker(j);
        Image img = t.getImage("junk.jpg");
        mt.addImage(img, 0);
        try{
          mt.waitForID(0);
        }catch(InterruptedException e){
          System.out.println("Hey, we were too impatient!");
        myPanel p = new myPanel(img);
        p.setPreferredSize(new Dimension(img.getWidth(null), img.getHeight(null)));
        j.add(p);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        j.pack();
        j.setVisible(true);
      public static void main(String[] args){
        new Junk().makeFrame();
      class myPanel extends JPanel{
        Image img;
        myPanel(Image img){
          this.img = img;
        public void paintComponent(Graphics g){
          g.drawImage(img, 0, 0, this);
    }BTW: your image should be in your project folder.

  • Is there a problem with JFrame and window listeners?

    As the subject implies, i'm having a problem with my JFrame window and the window listeners. I believe i have implemented it properly (i copied it from another class that works). Anyway, none of the events are caught and i'm not sure why. Here's the code
    package gcas.gui.plan;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.util.Hashtable;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import gcas.plandata.TaskData;
    import gcas.util.GCASProperties;
    import gcas.gui.planlist.MainPanel;
    * MainFrame extends JPanel and is the main class for the plan details window
    public class MainFrame extends JFrame implements WindowListener
         * the container for this window
        private Container contentPane;
         * a string value containing the name of the plan being viewed
        private String labelText;
         * a string value containing the name of the window (GCAS - plan list)
        private static String title;
         * an instance of JDialog class
        private static MainFrame dialog;
         * hashTable that correlates the task name to its id as found in the
         * plan
        private Hashtable taskNameToId = new Hashtable();
         * an instance of taskSetPane.  This is the current instance of taskSetPane
         * being viewed
        private PlanTaskSet currentPane;
         * instance of TaskData class.  Each instance will hold information on
         * an individual task
        private TaskData taskData;
         * hashTable containing instances of the taskSetPane class
        private Hashtable taskSetPanes = new Hashtable();
         * an instance of the OuterPanel class
        OuterPanel mainPanel;
         * an instance of the ButtonPanel class
        ButtonPanel buttonsPanel;
         * an instance of the LeftPanel class
        LeftPanel leftPanel;
         * an instance of the the GCASProperties class
        GCASProperties gcasProps;
        private static MainFrame thisPlanMain = null;
        private MainPanel planListMain;
         * constructor for MainFrame
         * @param frame the parent frame calling this class
         * @param locationComp the location of the component that initiated the opening of the dialog
         * @param labelText the name of the plan that is being viewed
         * @param title title of window
        private MainFrame(JFrame frame, Component locationComp, String labelText,
                String title)
            super(title);
            gcasProps = GCASProperties.getInstance();
            mainPanel = new OuterPanel(labelText, currentPane,
                    taskNameToId, taskSetPanes);
            leftPanel = mainPanel.getLeftPanel();
            System.out.println("LABLE: " + labelText);
            leftPanel.setMainPanelContents();
            buttonsPanel = new ButtonPanel(labelText, taskSetPanes,
                    taskNameToId, leftPanel);
            contentPane = getContentPane();
            contentPane.add(mainPanel, BorderLayout.CENTER);
            contentPane.add(buttonsPanel, BorderLayout.PAGE_END);
            this.addWindowListener(this);
            this.labelText = labelText;
            pack();
            setLocationRelativeTo(locationComp);
            this.setVisible(true);
            planListMain = MainPanel.getInstance();
            planListMain.setVisible(false);
        public static MainFrame getInstance(JFrame frame, Component locationComp, String labelText,
                String title)
            if (thisPlanMain == null)
                thisPlanMain = new MainFrame(frame, locationComp, labelText,
                        title);
            return thisPlanMain;
        public static MainFrame getDialogObject()
        {   //from the location this is called (ButtonPanel), this will never
            //be null
            return thisPlanMain;
        public static void setABMDDialogNull()
            thisPlanMain = null;
         * returns an instance of MainFrame
         * @return MainFrame instance
        public static MainFrame getDialog()
            return dialog;
         * setter for MainFrame
         * @param aDialog a MainFrame instance
        public static void setDialog(MainFrame aDialog)
            dialog = aDialog;
         * window opened event
         * @param windowEvent the window event passed to this method
        public void windowOpened(WindowEvent windowEvent)
         * The window event when a window is closing
         * @param windowEvent the window event passed to this method
        public void windowClosing(WindowEvent windowEvent)
            gcasProps.storeProperties("PlanList");
            MainPanel abmd = MainPanel.getInstance();
    //        planMain = this.getDialogObject();
    //        if(planMain != null)
    //            planMain.setVisible(false);
    //            abmd.setVisible(true);
    //            planMain.setABMDDialogNull();
            if(this.getDialogObject()!= null)
                abmd.setVisible(true);
                setVisible(false);
                setABMDDialogNull(); 
         * Invoked when the Window is set to be the active Window
         * @param windowEvent the window event passed to this method
        public void windowActivated(WindowEvent windowEvent)
         * Invoked when a window has been closed as the result of calling dispose on the window
         * @param windowEvent the window event passed to this method
        public void windowClosed(WindowEvent windowEvent)
         * Invoked when a Window is no longer the active Window
         * @param windowEvent the window event passed to this method
        public void windowDeactivated(WindowEvent windowEvent)
            System.out.println("HI");
         * Invoked when a window is changed from a minimized to a normal state
         * @param windowEvent the window event passed to this method
        public  void windowDeiconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
           System.out.println("Invoked when a window is changed from a minimized to a normal state.");
         * Invoked when a window is changed from a normal to a minimized state
         * @param windowEvent the window event passed to this method
        public  void windowIconified(WindowEvent windowEvent)
            //we could have code here that changed the way alerts are done
    //        System.out.println("Invoked when a window is changed from a normal to a minimized state.");
    }anyone know whats wrong?

    It turned out that my ide was running the old jar and not updating it, so no matter what code i added, it wasn't being seen. Everything should be fine now.

  • Hi Guys 'n' Gals! I have a problem with my computer going into 'Display Sleep' mode and it actually goes into full sleep mode. anyone know how to keep my Mac running software and not go into full sleep after I have set it to 'Never go into computer sleep

    Hi Guys 'n' Gals!
    I have a problem with my computer not going into 'Display Sleep' mode but actually goes into full Computer Sleep mode. Anyone know how to keep my Mac running software and not go into full sleep after I have set it to 'Never' go into 'Computer Sleep' within the 'energy saving' section!
    Any ideas guys?
    Miffa!

    Reset SMC.     http://support.apple.com/kb/HT3964
    Choose the  appropriate method.

  • Problems with Blackmagic footage going to black

    Hello, I am experiencing a problem with my footage dropping out or going to black. It is random. Sometimes the same piece of footage works other times not. Sometimes restarting is enough, but not always. I've trashed the prefs and adjusted memory options, but the problem persists.
    I am on a 2x2.93 GHz Quad_Core Intel MacOS 10.6.4
    with 12GB 1066MHz DDR3 of Memory
    After Effects CS5 v10.0.1.19
    And I'm running off a server.
    Is anyone else having this problem?
    J

    Start up in safe boot:
    Safe Boot
    http://support.apple.com/kb/HT1455
    This forces a disk check called fsck -fy it is similar to repair disk on the disk utility. Once it has started up to your log in screen restart normally and see if that helps

  • IPhone 6, problems with volume, automatically goes to the max when listening to the music

    iPhone 6 iOS 8.1, sometimes when I'm trying to increase volume by 1 bar, it goes to the max and there is no way to decrease it without reboot. Had same problem before updating to iOS 8.1... I've never had that problem with my 5S, which is also on iOS 8.1. I'm using Beats Mixr headphones with remote. I've tried to restore the phone, didn't helped.
    Yesterday I was listening to the music on iPhone 6 for about 4 hours and this happened 5 times, today I listened music from iPhone 5S for almost 5 hours and it didn't happended even once... I was using the same headphones... Any ideas?
    THanks in advance

    My phone is not on mute, the volume is up to the max, there are no blue tooth connections, the phone will not ring only vibrate with the ringer on.  I cannot hear any music through the phone either.

  • Problem with JFrame updating

    I'm having trouble making this application remove the "Client 1: 127.0.0.1 [localhost]" (and Client 2: or how ever many are connected) from a Box inside of a JPanel inside of a JFrame...
    I searched around a bit, but nothing fixed my problem. (SwingUtilities.invokeLater(new Runnable() etc is from another post, but with or without it I can't get it to work...)
    Running Fedora Core 2, JDK 1.4.2_04.
    Thanks in advance.
    (Hrmm, I had to mess with some of the longer lines to get them to display correctly...)
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class PennyServer extends JFrame implements ActionListener
         private Boolean finished;
         private Border border;
         private Box clientBox;
         private BoxLayout boxlayout;
         private Container content;
         private Dimension size;
         private JButton button;
         private JPanel buttonList;
         private JPanel clientList;
         private LinkedList llClient, llInput, llOutput;
         PennyServer()
              setBounds(100, 100, 400, 400);
    //          setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              setTitle("Test Server - by Joshua");
              content = getContentPane();
              border = BorderFactory.createRaisedBevelBorder();
              boxlayout = new BoxLayout(content, BoxLayout.Y_AXIS);
              clientBox = Box.createVerticalBox();
              size = new Dimension(80, 20);
              clientList = new JPanel(new BorderLayout());
              buttonList = new JPanel();
              content.setLayout(boxlayout);
              clientList.setBorder(new TitledBorder(new EtchedBorder(), "Client List"));
              clientList.add(clientBox, BorderLayout.CENTER);
              buttonList.add(button = new JButton("Start"));
              button.setBorder(border);
              button.setPreferredSize(size);
              button.addActionListener(this);
              buttonList.add(button = new JButton("Quit"));
              button.setBorder(border);
              button.setPreferredSize(size);
              button.addActionListener(this);
              buttonList.setBorder(
                   new CompoundBorder(
                        BorderFactory.createLineBorder(Color.black, 1),
                        BorderFactory.createBevelBorder(BevelBorder.RAISED)
              content.add(clientList);
              content.add(buttonList);
              setVisible(true);
              finished = new Boolean(false);
              llClient = new LinkedList();
              llInput = new LinkedList();
              llOutput = new LinkedList();
         public void addClient(Socket s)
              try
                   s.setSoTimeout(0100);
                   s.setTcpNoDelay(true);
                   llClient.addLast(s);
                   llInput.addLast(
                        new BufferedReader(
                             new InputStreamReader(
                                  s.getInputStream()
                   llOutput.addLast(new PrintStream(s.getOutputStream()));
              catch (Exception e)
                   System.out.println ("<" + e + ">");
              SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        refreshClientList();
         public void refreshClientList()
              InetAddress addr;
              ListIterator iter = llClient.listIterator(0);
              clientBox.removeAll();
              clientBox.add(Box.createVerticalStrut(20));
              while(iter.hasNext())
                   addr = ((Socket) iter.next()).getInetAddress();
    System.out.println (
         "Debug:  refreshClientList():  adding client " +
         (iter.previousIndex() + 1)
                   // This is not going away on the display...
                   clientBox.add(
                        new JLabel(
                             "Client " + (iter.previousIndex() + 1) + ": " +
                             addr.getHostAddress() + " [" + addr.getHostName() + "]"
                   if (iter.hasNext())
                        clientBox.add(Box.createVerticalStrut(20));
              clientBox.revalidate();
         public void select()
              BufferedReader in;
              ListIterator iterClient = llClient.listIterator(0);
              ListIterator iterInput = llInput.listIterator(0);
              ListIterator iterOutput = llOutput.listIterator(0);
              PrintStream out;
              Socket s;
              String userInput;
              while(iterClient.hasNext() && iterInput.hasNext() && iterOutput.hasNext())
                   s = (Socket) iterClient.next();
                   in = (BufferedReader) iterInput.next();
                   out = (PrintStream) iterOutput.next();
                   try
                        userInput = in.readLine();
                        if (userInput == null)
                             System.out.println (
                                  "Client " + (iterClient.previousIndex() + 1) +
                                  " has disconnected from the server."
                             iterClient.remove();
                             iterInput.remove();
                             iterOutput.remove();
                             SwingUtilities.invokeLater(new Runnable()
                                  public void run()
                                       refreshClientList();
                             continue;
                        System.out.println (
                             "Client " + (iterClient.previousIndex() + 1) +
                             ": " + userInput
                   catch (SocketTimeoutException e)
                   {}  // Do nothing, 100 millisecond time expired
                   catch (Exception e)
                        System.out.println ("<" + e + ">");
                   userInput = null;
         public boolean alive()
              return (!(finished.booleanValue()));
         public static void main (String[] args)
              try
                   PennyServer penny = new PennyServer();
                   ServerSocket ss;
                   Socket client;
                   ss = new ServerSocket(1234);  // Start a listening socket on port 1234
                   ss.setReuseAddress(true);  // Reuse local address/port combonation
                   ss.setSoTimeout(0100);  // 100 milliseconds, to simulate nonblocking IO
                   while(penny.alive())
                        penny.select();  // Poll sockets for input
                        try
                             penny.addClient(client = ss.accept());
                        catch (SocketTimeoutException e)
                        {}  // Do nothing, 100 millisecond time expired
                   penny.dispose();
                   ss.close();
              catch (Exception e)
                   System.out.println ("<" + e + ">");
         public void actionPerformed(ActionEvent event)
              if (event.getActionCommand().equals("Start"))
              else if (event.getActionCommand().equals("Quit"))
                   finished = new Boolean(true);
    }Joshua

    Ahha! Thank you, sjl. It works perfectly now.
    I thought it would be something silly, but I couldn't for the life of me figure out what.
    Joshua

  • Problem with jframe has jtextfield and jpanel

    hi all
    i ve a jframe with some components on it
    of these components a jpanel that i repaint each time i want
    and a textfield for chatting between players
    the problem is as follows
    some times when i click the textfield after repaining the panel
    it can not be activated and the caret does not appear
    when i click any other component out or in the frame
    and return i get it active and in a good state
    i use single buffer for repapint
    thanks for reading
    i'm waiting for response

    Your best bet here is to show us your code. We don't want to see all of it, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
    [http://homepage1.nifty.com/algafield/sscce.html|http://homepage1.nifty.com/algafield/sscce.html]
    Again, if the code is compilable and runnable more people will be able to help you.
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. You may want to click on the Preview tab to make sure that your code is formatted correctly. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
      // note the differences between the tag at the top vs the bottom.
    &#91;/code]

Maybe you are looking for