Categories

JAVA DATEBASE
Technology Network Community
Oracle Database
Fusion Middleware
Development Tools
Java
Desktop
Server & Storage Systems
Enterprise Management
Berkeley DB Family
Cloud Computing
Big Data
Business Intelligence
Architecture
Migration and Modernization
E-Business Suite
Siebel
PeopleSoft Enterprise
JD Edwards World
Industries
JD Edwards EnterpriseOne
User Productivity Kit Pro (UPK) and Tutor
Governance, Risk & Compliance (GRC)
Master Data Management (MDM)
Oracle CRM On Demand
On Demand: SaaS and Managed Applications
AutoVue Enterprise Visualization
Primavera
ATG
Agile PLM
Endeca Experience Management
Fusion Applications
Archived Forums

 



Tags

Swing [Archive]


JPanel sometimes doesn't display correctly


I have this JFrame which contains a single JPanel as its content pane. I have the paintComponent() overriden so that the panel paints a background that creates the basis for the GUI. The problem is that sometimes when I run the program (I've tried it on different computers too) instead of the background showing up with the text field on top of it, the background turns grey and only the text field that recieves focus by defualt shows up. I can make the other stuff show up too by clicking on it. It's as if I hadn't set setVisible() to true and it only happens some of the time. Here is a watered down version of the program but it still has the problem.  import javax.swing.*; import java.awt.*; import java.awt.event.*; class problemFrame {     JFrame interfaceFrame;     JLabel wrongLogin;     JPanel logIn, repMain;     JTextField userNameField;     JPasswordField passField;     JButton exit;     ImageIcon loginImg, exitButton, exitButtonPressed;     problemFrame(GraphicsDevice graphicsDev)     {             interfaceFrame = new JFrame("Stupid, do what you will, Frame");         interfaceFrame.setSize(graphicsDev.getDisplayMode().getWidth(), graphicsDev.getDisplayMode().getHeight());         interfaceFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         interfaceFrame.setUndecorated(true);                  loginImg = new ImageIcon("loginScreen.jpg");         exitButton = new ImageIcon("exitButtonNorm.jpg");         exitButtonPressed = new ImageIcon("exitButtonPressed.jpg");                  logIn = new JPanel()         {             public void paintComponent(Graphics g)             {                 super.paintComponent(g);                 g.drawImage(loginImg.getImage(), 0, 0, null);             }         };         logIn.setLayout(null);         logIn.setBackground(null);         logIn.setOpaque(false);                  exit = new JButton(exitButton);         exit.setBorderPainted(false);         exit.setPressedIcon(exitButtonPressed);         exit.setFocusable(false);         exit.setSize(exitButton.getIconWidth(), exitButton.getIconHeight());         exit.setLocation(1000, 7);         logIn.add(exit);         exit.setVisible(true);                         userNameField = new JTextField(20);         userNameField.setLocation(500, 315);         userNameField.setSize(userNameField.getPreferredSize());         userNameField.setMaximumSize(userNameField.getPreferredSize());         logIn.add(userNameField);         userNameField.setVisible(true);                  passField = new JPasswordField(20);         passField.setLocation(500, 385);         passField.setSize(passField.getPreferredSize());         passField.setMaximumSize(passField.getPreferredSize());         logIn.add(passField);         passField.setVisible(true);                  wrongLogin = new JLabel("Incorrect User Name/Password");         wrongLogin.setForeground(Color.red);         wrongLogin.setFont(new Font("SansSerif", Font.BOLD, 24));         wrongLogin.setSize(wrongLogin.getPreferredSize());         wrongLogin.setLocation(330, 250);         logIn.add(wrongLogin);         wrongLogin.setVisible(false);                      }     public void showLoginScreen()     {         interfaceFrame.setContentPane(logIn);         interfaceFrame.setVisible(true);         interfaceFrame.requestFocus();         userNameField.requestFocus();     }     public static void main (String[] args)     {                  GraphicsDevice dev = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice ();          GraphicsConfiguration gc = dev.getDefaultConfiguration();          DisplayMode currentMode = dev.getDisplayMode();         problemFrame PF = new problemFrame(dev);         dev.setFullScreenWindow(PF.interfaceFrame);         PF.showLoginScreen();                    }//end of main }   You'll need to suplement some of your own images. loginImg- a background image (if you haven't figured it out already this is a login screen for a program). exitButton and exitButtonPressed- any old 'X' like image that pleases you!  Also, do I need to put a setVisible(true) for each component or will doing it for the frame alone be sufficient? Should I be using another format for the background image, ImageIcon seems less like an image and more like a Icon. Any other things that I have that are repetitive, missing, or just plain stupid?  Thanks in Advance Colin  P.S. The most helpful person will recieve 3 duke dollars! Good luck.

Also I forgot to ask, is there any easy way to make a point layout like mine resize itself if the aspect ratio is still the same. I thought that I could make it so the images would resize themselves and I could position all the components by multiplying the screen width and height by a certain decimal to get points that would be geometricly similar in position to any other screen size. While I'm pretty sure that would work, there has to be an easier way.  Thanks again, Colin

OK, I really need this help! So, to encourage, I've now raised the bar. I will now give 10 Duke Dollars to the person that responds with the most helpful comment! Please read, I need to fix this by Mon. the 29th!  Colin

Ok, I think I've found it. I accedentally applyed the setVisible(true) and requestFocus() methods to the JFrame instead of the JPanel. It seems to work every time now. So now I have all these Duke Dollars to give [hint] someone could answer some of my other questions or confirm that I really have solved the problem[/hint].  Colin

Ok, never mind, it's not working. It just did it again. So, uh, help!  Colin

Try this and see if it works the way you want... import javax.swing.*; import java.awt.*; import java.awt.event.*;   class ProblemFrame {     JFrame interfaceFrame;     JLabel wrongLogin;     JPanel logIn, repMain;     JTextField userNameField;     JPasswordField passField;     JButton exit;     ImageIcon loginImg, exitButton, exitButtonPressed;       ProblemFrame(GraphicsDevice graphicsDev)     {         interfaceFrame = new JFrame("Stupid, do what you will, Frame");         interfaceFrame.setSize(graphicsDev.getDisplayMode().getWidth(),                                graphicsDev.getDisplayMode().getHeight());         interfaceFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         interfaceFrame.setUndecorated(true);            loginImg = new ImageIcon("images/barnowl.jpg");         exitButton = new ImageIcon("images/bclynx.jpg");         exitButtonPressed = new ImageIcon("images/greathornedowl.jpg");            logIn = new JPanel()         {             public void paintComponent(Graphics g)             {                 super.paintComponent(g);  // tells Swing to paint the background                 int w = getWidth();                 int h = getHeight();                 int imageW = loginImg.getImage().getWidth(null);                 int imageH = loginImg.getImage().getHeight(null);                 int x = (w - imageW)/2;                 int y = (h - imageH)/2;                 g.drawImage(loginImg.getImage(), x, y, null);             }         };         logIn.setLayout(null);            // not the best but okay         logIn.setBackground(Color.blue);  // only if you want to change the color //        logIn.setOpaque(false);         // big no-no for content panes!            exit = new JButton(exitButton);         exit.addActionListener(new ActionListener()         {             public void actionPerformed(ActionEvent e)             {                 interfaceFrame.setExtendedState(Frame.ICONIFIED);             }         });         exit.setBorderPainted(false);         exit.setPressedIcon(exitButtonPressed);         exit.setFocusable(false);         exit.setSize(exitButton.getIconWidth(), exitButton.getIconHeight());         exit.setLocation(700, 7);         logIn.add(exit); //        exit.setVisible(true);     // the frame will show these components            userNameField = new JTextField(20);         userNameField.setLocation(500, 315);         userNameField.setSize(userNameField.getPreferredSize());         userNameField.setMaximumSize(userNameField.getPreferredSize());         logIn.add(userNameField); //        userNameField.setVisible(true);            passField = new JPasswordField(20);         passField.addActionListener(new ActionListener()         {             // toggle wrongLogin visible/not             public void actionPerformed(ActionEvent e)             {                 wrongLogin.setVisible(!wrongLogin.isVisible());             }         });         passField.setLocation(500, 385);         passField.setSize(passField.getPreferredSize());         passField.setMaximumSize(passField.getPreferredSize());         logIn.add(passField); //        passField.setVisible(true);            wrongLogin = new JLabel("Incorrect User Name/Password");         wrongLogin.setForeground(Color.red);         wrongLogin.setFont(new Font("SansSerif", Font.BOLD, 24));         wrongLogin.setSize(wrongLogin.getPreferredSize());         wrongLogin.setLocation(330, 250);         logIn.add(wrongLogin);         wrongLogin.setVisible(false);     }        public void showLoginScreen()     {         interfaceFrame.setContentPane(logIn);   // must be opaque(true)         interfaceFrame.setVisible(true);         interfaceFrame.requestFocusInWindow();  // this method preferred,         userNameField.requestFocusInWindow();   // see api for explanation     }        public static void main (String[] args)     {         GraphicsDevice dev =             GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();          GraphicsConfiguration gc = dev.getDefaultConfiguration();          DisplayMode currentMode = dev.getDisplayMode();         ProblemFrame pf = new ProblemFrame(dev);         dev.setFullScreenWindow(pf.interfaceFrame);         pf.showLoginScreen();     }//end of main } 

Answer to your reply 1: we're using a (GridBag) layout manager in this one. The layout manager takes care of locating components under varying conditions. The only tricksy thing in this layout is the cooperation of the two gbc.weighty constraints in determining the height of the three–component group (of the two textfields and the wrongLogin label). Using a lower number for the top constraint and a larger number for the bottom weighty will move the group higher on the screen. The opposite settings will lower the group. It really depends on the height of the exit button. Once you get the height of the group set where you want it (with the constraints) it should resize nicely in different monitors. import javax.swing.*; import java.awt.*; import java.awt.event.*;   class ProblemFrame {     JFrame interfaceFrame;     JLabel wrongLogin;     JPanel logIn, repMain;     JTextField userNameField;     JPasswordField passField;     JButton exit;     ImageIcon loginImg, exitButton, exitButtonPressed;       ProblemFrame(GraphicsDevice graphicsDev)     {         interfaceFrame = new JFrame("Things are gettin' better...");         interfaceFrame.setSize(graphicsDev.getDisplayMode().getWidth(),                                graphicsDev.getDisplayMode().getHeight());         interfaceFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         interfaceFrame.setUndecorated(true);            loginImg = new ImageIcon("images/barnowl.jpg");         exitButton = new ImageIcon("images/bclynx.jpg");         exitButtonPressed = new ImageIcon("images/greathornedowl.jpg");            logIn = new JPanel()         {             public void paintComponent(Graphics g)             {                 super.paintComponent(g);                 int w = getWidth();                 int h = getHeight();                 int imageW = loginImg.getImage().getWidth(null);                 int imageH = loginImg.getImage().getHeight(null);                 int x = (w - imageW)/2;                 int y = (h - imageH)/2;                 g.drawImage(loginImg.getImage(), x, y, null);             }         };         logIn.setLayout(new GridBagLayout());         GridBagConstraints gbc = new GridBagConstraints();         gbc.gridwidth = gbc.REMAINDER;         logIn.setBackground(new Color(200,220,220));            exit = new JButton(exitButton);         exit.addActionListener(new ActionListener()         {             public void actionPerformed(ActionEvent e)             {                 interfaceFrame.setExtendedState(Frame.ICONIFIED);             }         });         exit.setBorderPainted(false);         exit.setPressedIcon(exitButtonPressed);         exit.setFocusable(false);            // no keyboard tabbing with this         exit.setPreferredSize(new Dimension(exitButton.getIconWidth(),                                             exitButton.getIconHeight()));         gbc.insets = new Insets(10,0,0,10);  // [top, left, bottom, right]         gbc.weightx = 1.0;         gbc.weighty = 0.5;  // [0 - 1.0] controls height of textfields and label                             // less means higher placement, see below (****)         gbc.anchor = gbc.NORTHEAST;         logIn.add(exit, gbc);            userNameField = new JTextField(20);         userNameField.setMaximumSize(userNameField.getPreferredSize());         gbc.insets = new Insets(20,0,20,0);         gbc.weighty = 0;                 // insets determine spacing now         gbc.weightx = 0;         gbc.anchor = gbc.NORTH;         logIn.add(userNameField, gbc);            passField = new JPasswordField(20);         passField.addActionListener(new ActionListener()         {             String s = "";               public void actionPerformed(ActionEvent e)             {                 if(wrongLogin.getText().equals(""))                     s = "Incorrect User Name/Password";                 else                     s = "";                 wrongLogin.setText(s);             }         });         passField.setMaximumSize(passField.getPreferredSize());         gbc.insets = new Insets(20,0,5,0);         logIn.add(passField, gbc);            wrongLogin = new JLabel("", JLabel.CENTER);         // visual diagnostic trick, remove later         //wrongLogin.setBorder(BorderFactory.createEtchedBorder());         wrongLogin.setForeground(Color.red);         wrongLogin.setFont(new Font("SansSerif", Font.BOLD, 24));         // increase height so label doesn't move with setText calls         wrongLogin.setPreferredSize(                        new Dimension(wrongLogin.getPreferredSize().width, 40));         gbc.insets = new Insets(0,0,0,0);         // push textfields and label up with weighty constraint > 0         gbc.weighty = 1.0;  // [0 - 1.0] controls height of textfields and label                             // more means higher, see above (****), this is key         gbc.weightx = 1.0;          // expand width so label doesn't move          gbc.fill = gbc.HORIZONTAL;  // around on us with calls to setText         logIn.add(wrongLogin, gbc);     }        public void showLoginScreen()     {         interfaceFrame.setContentPane(logIn);   // must be opaque(true)         interfaceFrame.setVisible(true);         interfaceFrame.requestFocusInWindow();  // this method preferred,         userNameField.requestFocusInWindow();   // see api for explanation     }        public static void main (String[] args)     {         GraphicsDevice dev =             GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();          GraphicsConfiguration gc = dev.getDefaultConfiguration();          DisplayMode currentMode = dev.getDisplayMode();         ProblemFrame pf = new ProblemFrame(dev);         dev.setFullScreenWindow(pf.interfaceFrame);         pf.showLoginScreen();     } } 

Thanks a million Philip! My problem seemed to be that I invoked the setOpaque(false) method on my JPanels. Now they display correctly every single time. As for the GridBag layout, the code looks good (not that I know very much) and I can see that you really put a lot of time in doing it. I'd heard of the Grid Bay layout, but it seemed pretty confusing and so I avoided it. After I turn in this program I will try and switch it to a Grid Bag Layout (if I can figure it out :-p) but I'm kind of short on time right now. And as a small token of my gratitude, here are 10 duke dollars!  Colin


Related Links

HTMLEditorKit, Custom Tags and CSS???
Design Guidelines for Java Clients in Intranet/Extranet Applicationsns
com.sun.java.swing
problem with outoff enviroment
com.sun.java.swing
about JTable's celleditor
Expand/Resize JTextField as user types
Screen 1.4.0 repaint erases screen - severe flickering
Ending a sub frame
How Can One use XML data into our Java Program
Appropriate use of JProgressBar
Problem with JFormattedTextField
how to create plugins in swing??
focusGained in JFormattedTextField
enabling/disabling button depending on text field in swing
Problem with custom SplitPane