Reload JPanel

I have 2 class files. One contains a JPanel that uses JTabbedPane to add a tab for each of my categories. Then in my other class file, I add the JPanel to my JFrame. So now I have some JMenuItems, the JTabbedPane (from the other class file) and some other JLabels etc...
My question is, if I add a new Category, obvisouly I won't see the new tab until I close out, and reload program. I was wondering what is the best way to solve this problem? I don't believe there are myPanel.reload() or myPanel.refresh() methods. Any ideas?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ClassCommunication {
  public static void main(String[] args) {
    // Once I create an instance of TabbedComponent here
    TabbedComponent tc = new TabbedComponent();
    JPanel panel = new JPanel();
    panel.setBackground(Color.red);
    // I can call its methods with the instance variable tc
    tc.addNewTab("One", panel);
    JFrame f = new JFrame("Class Communication");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(tc);
    f.pack();
    f.setLocation(400,300);
    f.setVisible(true);
    // after gui is realized...
    panel = new JPanel();
    panel.setBackground(Color.yellow);
    tc.addNewTab("Two", panel);
    panel = new JPanel();
    panel.setBackground(Color.blue);
    tc.addNewTab("Three", panel);
    panel = new JPanel();
    panel.setBackground(Color.green);
    tc.addNewTab("Four", panel);
    System.out.println("tab[2] background color = " +
                        tc.getPane().getBackgroundAt(2) + "\n" +
                       "panel[3] background color = " +
                        tc.getPane().getComponentAt(3).getBackground() + "\n" +
                       "tab[1] title = " + tc.getPane().getTitleAt(1));
class TabbedComponent extends JComponent {
  private JTabbedPane tabbedPane;
  public TabbedComponent() {
    setPreferredSize(new Dimension(400,300));
    tabbedPane = new JTabbedPane();
    setLayout(new BorderLayout());
    add(tabbedPane);
  public void addNewTab(String title, JPanel panel) {
    tabbedPane.addTab(title, panel);
    tabbedPane.validate();               // "refresh", a Container method
  public JTabbedPane getPane() {
    return tabbedPane;
}

Similar Messages

  • Reloading JPanel in JPanel

    Hi,
    I have a three JPanel called MainPanel, AddUserPanel and ViewPanel, a JButton called btnAddUser and one called btnView.
    At first, there is nothing in the MainPanel. When I clicked on the btnAddUser, how do I make that the AddUserPanel will be inserted into the MainPanel.
    Likewise, when I clicked on the btnView, the ViewPanel will replace the AddUserPanel and display only the ViewPanel.
    Please adivse. Thanks in advance.

    I'm a bit rusty but I think you just add the component and then you should probably do a "repaint". So switching components, remove the old, add the new then repaint. I'm not sure if this will cause a nasty flicker...depends if you are using double buffering I supoose...
    For the button add an ActionListener and then do the above in the "actionPerformed" method.

  • Reloading the same image into a JPanel

    I have a multi user app.. one user can edit an image in one GUI and i want the other user to be able to refresh somehow a JPanel that they have in their GUI to reload the image file.
    any help, would be appreciated.
    thanks

    Send a signal from one user's frame to the other's to reload the image. Then just call setIcon as you did before.

  • Refresh/reload Swing components???

    Hi all,
    I am having a problem with using a Swing frame ... I am calling a command line program on the click of a button in the frame. But as soon as the button is clicked, the swing frame is paused .. the button stays pressed as long as the program ends. My requirement is ... all those messages which are printed on the console should be printed on a Swing component (like a JLabel or JList). I have no problem doing that... but everything is visible only after the program ends... till then the swing frame remains static. Is there any way out??? Can we reload or refresh the JFrame?
    thaanx in advance

    jif1=new JInternalFrame("JIF Title",false,false,false,false);
                        Container c=jif1.getContentPane();
              c.setLayout(new BorderLayout());
                        listModel = new DefaultListModel();
                        listModel.addElement("First entry");
                                  JPanel jp=new JPanel();
                                  index=0;
                                  list = new JList(listModel);
                                  list.setVisibleRowCount(9);
                                  Font displayFont = new Font("Arial",Font.PLAIN,11);
                             list.setFont(displayFont);
                                  JScrollPane listScrollPane = new JScrollPane(jp);
                                  listScrollPane.getViewport().setView(list);
                                  list.setVisible(true);
                                  c.add(jp, BorderLayout.PAGE_END);
                                  jif1.setVisible(true);
                             jif1.setOpaque(true);
                                  jdp.add(jif1);
                                  jp.add(listScrollPane);
                                  repaint();
                                  jp.setVisible(true);
                                  try
                                            jif1.setSelected(true);
                                       } catch (java.beans.PropertyVetoException e) {}
                                  Process proc = Runtime.getRuntime().exec(command);
                                  InputStream stderr = proc.getErrorStream();
                                  InputStreamReader isr = new InputStreamReader(stderr);
                                  BufferedReader br = new BufferedReader(isr);
                                  String line = null;
                                  System.out.println("<DETAILS>");
                             while((line = br.readLine())!=null)
                                       final String con=line;
                                       final int ind=index;
                                  System.out.println(con);
    listModel.addElement(con);
                                       list.ensureIndexIsVisible(ind);
                                       index++;
                                  repaint();
                                  invalidate();
                                  validate();
                                  repaint();
                                  System.out.println("</DETAILS>");
                                  int exitVal = proc.waitFor();
                                  System.out.println("Value = " + exitVal);
                                  if(fil.exists()) System.out.println("File Created");                                                       pb.setString("Creating output file ... ");
                                  pb.setIndeterminate(true);
    ..... this internal frame should be popped up on the click of a button. but.. as soon as the button is clicked, the JFrame is frozen (... paused..) and there is no motion,... even the clicked button remains in the "clicked" state.Its only after the whole process is completed... that the internal frame becomes visible. As you can watch from the code posted above, in the while loop... I'm trying to display the status message both on the concole as well as on the list box. the console messages are displayed correctly.... but as the JFrame is not refreshed.... I'm not able to see the Internal frame as well as the list box atteched to it. please help me out.
    thanx in advance.....

  • Canvas3D not visable on Jpanel created with NetBeans UI Builder

    Hi,
    I created an application with NetBeans UI Builder. It has a frame and two panels. On one panel
    I attached a few things with the UI builder and they get displayed correctly. On the other panel however,
    I tried to attach a Canvas3D object that I created in another class (the object contains an universe
    with 3D objects) with not success by using the following code:
    DCL3DFrame mainWindow = new DCL3DFrame(); // object created with UI builder
                    DCL3d scope3d = new DCL3d(); // object created manually in another class
                    Canvas3D canvasForScope3D = scope3d.getCanvas();
                    mainWindow.getPanelForCanvas().add(canvasForScope3D, java.awt.BorderLayout.CENTER);
                    mainWindow.setVisible(true);I'm not a java programmer, so I'm probably missing something perhaps stupid.
    Any help is appreciated.
    Thanks,
    Salvo

    Thank you, now it works. It does not work because when I modified preferred size in netbeans the jpanel size was not changed. The jPanel size has changed when I reloaded(reopened) the file. I thought that preffered size property is not suitable but it is. I was wrong.
    Here is my working code.
    Regards,
    Primoz
    InvoiceCriteriaPanel icp = new InvoiceCriteriaPanel();
    jPanelCriteria.add(icp);
    jPanelCriteria.setPreferredSize(
          new Dimension(icp.getPreferredSize().width,
                                 icp.getPreferredSize().height));
    icp.setSize(icp.getPreferredSize().width,
                     icp.getPreferredSize().height);
    icp.setVisible(true);

  • Update picture in JPanel

    i'm have a picture, i showed it in JPanel, but my picture is change at any time, how i can update new picture on JPanel when my picture is updated
    //add picture in JPanel
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JPanel;
    class ImagePanel extends JPanel {
        private Image img;
        public ImagePanel(Image img) {
            this.img = img;
            Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
            setPreferredSize(size);
            setMinimumSize(size);
            setMaximumSize(size);
            setSize(size);
            setLayout(null);
        public void paintComponent(Graphics g) {
            g.drawImage(img, 0, 0, null);
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.rmi.Naming;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    public class ShowClient extends JFrame implements MouseMotionListener{
        public ShowClient() {
            super("Control Client");
            UpdatePicture();
        //this method
        public void UpdatePicture(){
            ImagePanel panel =
                    new ImagePanel(new ImageIcon("screen.jpg").getImage());
            JScrollPane scrollPane = new JScrollPane(panel);
            this.setLayout(new BorderLayout());
            this.add(scrollPane, BorderLayout.CENTER);
            scrollPane.addMouseMotionListener(this);
              when mouser move will have a new picture.
        public void mouseMoved(MouseEvent e){
            int x = e.getX();
            int y = e.getY();
            EventServer event = null;
            try {
                event = (EventServer)Naming.lookup("//localhost/Client");
                event.MouseMove(x, y);
            catch (Exception exp){
                System.out.println("Err " + exp);
            UpdatePicture(); //why here my JPanel don't show new picture
        public void mouseDragged(MouseEvent e){
        public void Show(){
            this.setDefaultCloseOperation(HIDE_ON_CLOSE);
            Toolkit tool = Toolkit.getDefaultToolkit();
            Dimension size = tool.getScreenSize();
            this.setSize(size);
            this.setVisible(true);
    }Thank a lot of !!
    Edited by: bathong on May 23, 2009 10:39 AM

    >
    If you mean that the image file is updated, you will need to either reload the Image from the file using ImageIO#read(...) or flush() the Image.
    When you load the image using the ImageIcon constructor that takes a String parameter, it is cached by Toolkitand will not be reloaded even if the file content changes.
    Why create an ImageIcon just to retrieve its Image? Use ImageIO and just load an Image.
    db
    >
    I rewrite as :
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import javax.swing.JPanel;
    class ImagePanel extends JPanel {
        public BufferedImage img;
        public ImagePanel(BufferedImage img) {
            this.img = img;
            Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
            setPreferredSize(size);
            setMinimumSize(size);
            setMaximumSize(size);
            setSize(size);
            setLayout(null); 
        public void paintComponent(Graphics g) {
            g.drawImage( img, 0, 0, null);
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.rmi.Naming;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    public class ShowClient extends JFrame implements MouseMotionListener{  
        public ShowClient() {
            super("Control Client");
            UpdatePicture();
        public void UpdatePicture(){
            try { 
                File file = new File("screen.jpg");
                BufferedImage buff = ImageIO.read(file);
                ImagePanel panel = new ImagePanel(buff);
                JScrollPane scrollPane = new JScrollPane(panel);
                this.setLayout(new BorderLayout());
                this.add(scrollPane, BorderLayout.CENTER);
                scrollPane.addMouseMotionListener(this); 
            catch (Exception exp){
                System.out.println("Error here " + exp);
                exp.printStackTrace();
        public void mouseMoved(MouseEvent e){
            int x = e.getX();
            int y = e.getY();
            EventServer event = null;
            try {
                event = (EventServer)Naming.lookup("//localhost/Client");
                event.MouseMove(x, y);
            catch (Exception exp){
                System.out.println("Err " + exp);
            UpdatePicture();
        public void mouseDragged(MouseEvent e){
        public void Show(){
            this.setDefaultCloseOperation(HIDE_ON_CLOSE);
            Toolkit tool = Toolkit.getDefaultToolkit();
            Dimension size = tool.getScreenSize();
            this.setSize(size);
            this.setVisible(true);
    }but new picture also can't update!! please help me, thank !!!!

  • Not getting swing components when the applet reloads

    I am facing one problem that is related to reloading of swing components. I Have a JPanel inside JApplet which contains some swing components and a button to launch the same JPanel again in the JApplet. When I click on the button the JPanel should get added in the JApplet once again below the upper JPanel. But new JPanel is not getting displayed although the reference of the new JPanel is created.

    My guess is that you haven't added your swing components to the right place. Are you adding them to the contentpane?

  • Reload different panels

    Hello all,
    Like to reload different panels onto the same load panel.
    Code sample below on what I'am trying to achieve
    Each panel size would like to be 45% of window size.
    Have problems of reloading different panels to achieve the size and
    also when resizing the window
    Have 8 dukes to get rid of from:
    http://forum.java.sun.com/thread.jsp?forum=43&thread=431639
    Thanks
    Abraham Khalil
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    * Want to test reloading panels of very different text sizes inside it<br>
    * The goal is no matter want the label text size is, each label panel should only
    * show a maximum of 45% of the window size. <br>
    * <p>
    * Each button on the right will show a more uglier panel to load
    public class PanelChangeTest extends JFrame implements ActionListener {
       private static final int WIDTH = 640;
       private static final int HEIGHT = 400;
       private static final String BUTTON_PANEL_TEST1 = "Load Normal Panel";
       private static final String BUTTON_PANEL_TEST2 = "Load bit ugly Panel";
       private static final String BUTTON_PANEL_TEST3 = "Load very ugly Panel";
       private static final String[] BUTTON_COMMANDS = {
                                                         BUTTON_PANEL_TEST1,
                                                         BUTTON_PANEL_TEST2,
                                                         BUTTON_PANEL_TEST3
       private JPanel loadPanel = new JPanel();
       private PanelChange[] testPanels = null;
        * Model for each panel. <br>
        * Each panel contain email fields of from, to, subject and cc
       private class PanelFields {
          private String from = null;
          private String to = null;
          private String subject = null;
          private String cc = null;
          public PanelFields(String from, String to, String subject, String cc) {
             this.from = from;
             this.to = to;
             this.subject = subject;
             this.cc = cc;
          public String getFrom() {
             return from;
          public String getTo() {
             return to;
          public String getSubject() {
             return subject;
          public String getCC() {
             return cc;
       } // End PanelFields class
        * View panel class <br>
        * Each panel change class will contain four panels and they are from, to, cc and subject panel. <br>
        * Each of the from, to, cc and subject panel contain two labels, one for description and other for
        * its text value.
        * Want to set each panel size to 45% of window size so it looks even, and if label text is too long
        * to fit in 45% view, it should truncate it..
       private class PanelChange extends JPanel {
          private static final float PERCENT = 1 / 100.0f;
          private static final float EACH_PANEL_SIZE = 45 * PERCENT;
          private JPanel getPanel(String labelForText, String text) {
             JLabel labelLeft = new JLabel(labelForText, JLabel.LEFT);
             JLabel labelRight = new JLabel(text, JLabel.LEFT);
             setBold(labelLeft, true);
             JPanel panel = new JPanel();
             panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
             panel.add(labelLeft);
             panel.add(labelRight);
             panel.setBorder(BorderFactory.createLineBorder(Color.blue));
             return panel;
          public void recalculate(Dimension parentSize) {
             Dimension eachPanelSize = new Dimension((int) (parentSize.width * EACH_PANEL_SIZE), 12);
             System.out.println("Parent size = (" + parentSize.width + ", " + parentSize.height + ")\n" +
                                "Each panel size is recalculated as (" + eachPanelSize.width + ", " + eachPanelSize.height + ")\n");
             Component[] components = getComponents();       
             for (int eachPanel = 0 ; eachPanel < components.length ; eachPanel++) {
                JComponent panel = (JComponent) components[eachPanel];
                panel.setMaximumSize(eachPanelSize);
                panel.setMinimumSize(eachPanelSize);
                panel.setSize(eachPanelSize);
          public PanelChange(PanelFields panelFields) {
             JPanel fromPanel = getPanel("From: ", panelFields.getFrom());
             JPanel toPanel = getPanel("To: ", panelFields.getTo());        
             JPanel subjectPanel = getPanel("Subject: ", panelFields.getSubject());
             JPanel ccPanel = getPanel("CC: ", panelFields.getCC());
             setLayout(new BorderLayout());
             JPanel panel = new JPanel();
             // Test with panel of GridLayout instead of GridBagLayout to see the difference...     
             panel.setLayout(new GridLayout(2, 2, 5, 5));
             panel.add(fromPanel);
             panel.add(toPanel);
             panel.add(subjectPanel);
             panel.add(ccPanel);
             panel.setLayout(new GridBagLayout());
             constrain(panel, fromPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       0, 0, 1, 1, 1.0, 0.0);
             constrain(panel, toPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       1, 0, 1, 1, 1.0, 0.0);
             constrain(panel, subjectPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       0, 1, 1, 1, 1.0, 0.0);
             constrain(panel, ccPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       1, 1, 1, 1, 1.0, 0.0);
             add(panel, BorderLayout.CENTER);
          private int getFontStyle(Component component, boolean makeBold) {
             int style = 0;
             if (component != null) {
                Font f = component.getFont();
                if (f != null) {
                   if (f.isPlain()) style = style | Font.PLAIN;
                   if (f.isItalic()) style = style | Font.ITALIC;
                   if (makeBold) style = style | Font.BOLD;
             return style;
          private void setBold(Component component, boolean makeBold) {
             int style = getFontStyle(component, makeBold);
             Font styleFont = component.getFont().deriveFont(style);
             component.setFont(styleFont);
       } // End PanelChange class
       public void constrain( Container container, Component component, 
                              int fill, int anchor,
                              int gx, int gy, int gw, int gh, double wx, double wy ) {
          GridBagConstraints c = new GridBagConstraints();
          c.fill = fill;
          c.anchor = anchor;
          c.gridx = gx;
          c.gridy = gy;
          c.gridwidth = gw;
          c.gridheight = gh;
          c.weightx = wx;
          c.weighty = wy;
          ( (GridBagLayout) container.getLayout() ).setConstraints( component, c );
          container.add( component );
       public void constrain( Container container, Component component, 
                              int fill, int anchor,
                              int gx, int gy, int gw, int gh,
                              double wx, double wy, Insets inset ) {
          GridBagConstraints c = new GridBagConstraints();
          c.fill = fill;
          c.anchor = anchor;
          c.gridx = gx;
          c.gridy = gy;
          c.gridwidth = gw;
          c.gridheight = gh;
          c.weightx = wx;
          c.weighty = wy;
          c.insets = inset;
          ( (GridBagLayout) container.getLayout() ).setConstraints( component, c );
          container.add( component );
       private void initPanels() {
          PanelFields okPanel = new PanelFields("Simple from...",
                                                "[email protected]; [email protected]",
                                                "Simple subject...",
                                                "[email protected]; [email protected]");
          PanelFields bitUglyPanel = new PanelFields("A bit ugly from................",
                                                     "[email protected]; [email protected]; [email protected]; [email protected]",
                                                     "A bit ungle subject.....................",
                                                     "[email protected]; [email protected]; [email protected]; [email protected]");
          PanelFields veryUglyPanel = new PanelFields("A very very very very very " +
                                                      "very very ugly from................",
                                                      "[email protected]; [email protected]; [email protected]; [email protected], " +
                                                      "[email protected]; [email protected]; [email protected]; [email protected]",
                                                      "A very very very very very very " +
                                                      "very ungle subject.....................",
                                                      "[email protected]; [email protected]; [email protected]; [email protected]; " +
                                                      "[email protected]; [email protected]; [email protected]; [email protected]");
          testPanels = new PanelChange[] {
                                            new PanelChange(okPanel),
                                            new PanelChange(bitUglyPanel),
                                            new PanelChange(veryUglyPanel)
          Container container = getContentPane();
          container.setLayout(new BorderLayout());
          JPanel buttonPanel = new JPanel();
          buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
          JButton button1 = new JButton(BUTTON_PANEL_TEST1);
          button1.setActionCommand(BUTTON_PANEL_TEST1);
          button1.addActionListener(this);
          JButton button2 = new JButton(BUTTON_PANEL_TEST2);
          button2.setActionCommand(BUTTON_PANEL_TEST2);
          button2.addActionListener(this);
          JButton button3 = new JButton(BUTTON_PANEL_TEST3);
          button3.setActionCommand(BUTTON_PANEL_TEST3);
          button3.addActionListener(this);
          buttonPanel.add(button1);
          buttonPanel.add(Box.createHorizontalStrut(5));
          buttonPanel.add(button2);
          buttonPanel.add(Box.createHorizontalStrut(5));
          buttonPanel.add(button3);
          JPanel mainPanel = new JPanel();
          mainPanel.setLayout(new GridBagLayout());
          constrain(mainPanel, loadPanel,
                    GridBagConstraints.BOTH, GridBagConstraints.WEST,
                    0, 0, 1, 1, 1.0, 1.0, new Insets(5, 5, 5, 5));
          constrain(mainPanel, buttonPanel,
                    GridBagConstraints.NONE, GridBagConstraints.CENTER,
                    0, 1, 1, 1, 0.0, 0.0, new Insets(5, 5, 5, 5));
          container.add(mainPanel);
       private void setupLoadPanel(PanelChange panelToLoad) {
          loadPanel.removeAll();
          panelToLoad.recalculate(getSize());
          loadPanel.add(panelToLoad);
          loadPanel.revalidate();     
       public void actionPerformed(ActionEvent e) {
          String actionCommand = e.getActionCommand();
          for (int i = 0 ; i < BUTTON_COMMANDS.length ; i++) {
             if (actionCommand.equals(BUTTON_COMMANDS)) {
    setupLoadPanel(testPanels[i]);
    break;
    public PanelChangeTest() {
    super("Panel change test...");
    Dimension size = new Dimension(WIDTH, HEIGHT);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screenSize.width - size.width) / 2;
    int y = (screenSize.height - size.height) / 2;
    setBounds(x, y, WIDTH, HEIGHT);
    addWindowListener(new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    System.exit(0);
    FontUIResource standardFont = new FontUIResource("dialogPlain11", Font.PLAIN, 11);
    UIManager.put("Label.font", standardFont);
    UIManager.put("Button.font", standardFont);
    initPanels();
    public static void main(String args[]) {
    new PanelChangeTest().setVisible(true);

    Please use the following code below:
    Somehow it doesn't show the text if it can't fit inside the panel.
    When resize to full screen, it shows the text??
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    * Want to test reloading panels of very different text sizes inside it<br>
    * The goal is no matter want the label text size is, each label panel should only
    * show a maximum of 45% of the window size. <br>
    * <p>
    * Each button on the right will show a more uglier panel to load
    public class PanelChangeTest extends JFrame implements ActionListener {
       private static final int WIDTH = 640;
       private static final int HEIGHT = 400;
       private static final String BUTTON_PANEL_TEST1 = "Load Normal Panel";
       private static final String BUTTON_PANEL_TEST2 = "Load bit ugly Panel";
       private static final String BUTTON_PANEL_TEST3 = "Load very ugly Panel";
       private static final String[] BUTTON_COMMANDS = {
                                                         BUTTON_PANEL_TEST1,
                                                         BUTTON_PANEL_TEST2,
                                                         BUTTON_PANEL_TEST3
       private JPanel loadPanel = new JPanel();
       private PanelChange[] testPanels = null;
        * Model for each panel. <br>
        * Each panel contain email fields of from, to, subject and cc
       private class PanelFields {
          private String from = null;
          private String to = null;
          private String subject = null;
          private String cc = null;
          public PanelFields(String from, String to, String subject, String cc) {
             this.from = from;
             this.to = to;
             this.subject = subject;
             this.cc = cc;
          public String getFrom() {
             return from;
          public String getTo() {
             return to;
          public String getSubject() {
             return subject;
          public String getCC() {
             return cc;
       } // End PanelFields class
        * View panel class <br>
        * Each panel change class will contain four panels and they are from, to, cc and subject panel. <br>
        * Each of the from, to, cc and subject panel contain two labels, one for description and other for
        * its text value.
        * Want to set each panel size to 45% of window size so it looks even, and if label text is too long
        * to fit in 45% view, it should truncate it..
       private class PanelChange extends JPanel {
          private static final float PERCENT = 1 / 100.0f;
          private static final float EACH_PANEL_SIZE = 45 * PERCENT;
          public PanelChange(PanelFields panelFields) {
             JPanel fromPanel = getPanel("From: ", panelFields.getFrom());
             JPanel toPanel = getPanel("To: ", panelFields.getTo());        
             JPanel subjectPanel = getPanel("Subject: ", panelFields.getSubject());
             JPanel ccPanel = getPanel("CC: ", panelFields.getCC());
             setLayout(new BorderLayout());
             JPanel panel = new JPanel();
             // Test with panel of GridLayout instead of GridBagLayout to see the difference...     
             panel.setLayout(new GridLayout(2, 2, 5, 5));
             panel.add(fromPanel);
             panel.add(toPanel);
             panel.add(subjectPanel);
             panel.add(ccPanel);
             panel.setLayout(new GridBagLayout());
             constrain(panel, fromPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       0, 0, 1, 1, 1.0, 0.0);
             constrain(panel, toPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       1, 0, 1, 1, 1.0, 0.0);
             constrain(panel, subjectPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       0, 1, 1, 1, 1.0, 0.0);
             constrain(panel, ccPanel,
                       GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST,
                       1, 1, 1, 1, 1.0, 0.0);
             add(panel, BorderLayout.CENTER);
          public void recalculate(Dimension parentSize) {
             Dimension eachPanelSize = new Dimension((int) (parentSize.width * EACH_PANEL_SIZE), 20);
             System.out.println("Parent size = (" + parentSize.width + ", " + parentSize.height + ")\n" +
                                "Each panel size is recalculated as (" + eachPanelSize.width + ", " + eachPanelSize.height + ")\n");
             JPanel mainPanel = (JPanel) getComponent(0);
             Component[] components = mainPanel.getComponents();
             for (int eachPanel = 0 ; eachPanel < components.length ; eachPanel++) {
                JComponent panel = (JComponent) components[eachPanel];
                panel.setMaximumSize(eachPanelSize);
                panel.setMinimumSize(eachPanelSize);
                panel.setPreferredSize(eachPanelSize);
          private JPanel getPanel(String labelForText, String text) {
             JLabel labelLeft = new JLabel(labelForText, JLabel.LEFT);
             JLabel labelRight = new JLabel(text, JLabel.LEFT);
             setBold(labelLeft, true);
             JPanel panel = new JPanel();
             panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 0));
             panel.add(labelLeft);
             panel.add(labelRight);
             panel.setBorder(BorderFactory.createLineBorder(Color.blue));
             return panel;
          private int getFontStyle(Component component, boolean makeBold) {
             int style = 0;
             if (component != null) {
                Font f = component.getFont();
                if (f != null) {
                   if (f.isPlain()) style = style | Font.PLAIN;
                   if (f.isItalic()) style = style | Font.ITALIC;
                   if (makeBold) style = style | Font.BOLD;
             return style;
          private void setBold(Component component, boolean makeBold) {
             int style = getFontStyle(component, makeBold);
             Font styleFont = component.getFont().deriveFont(style);
             component.setFont(styleFont);
       } // End PanelChange class
       public void constrain( Container container, Component component, 
                              int fill, int anchor,
                              int gx, int gy, int gw, int gh, double wx, double wy ) {
          GridBagConstraints c = new GridBagConstraints();
          c.fill = fill;
          c.anchor = anchor;
          c.gridx = gx;
          c.gridy = gy;
          c.gridwidth = gw;
          c.gridheight = gh;
          c.weightx = wx;
          c.weighty = wy;
          ( (GridBagLayout) container.getLayout() ).setConstraints( component, c );
          container.add( component );
       public void constrain( Container container, Component component, 
                              int fill, int anchor,
                              int gx, int gy, int gw, int gh,
                              double wx, double wy, Insets inset ) {
          GridBagConstraints c = new GridBagConstraints();
          c.fill = fill;
          c.anchor = anchor;
          c.gridx = gx;
          c.gridy = gy;
          c.gridwidth = gw;
          c.gridheight = gh;
          c.weightx = wx;
          c.weighty = wy;
          c.insets = inset;
          ( (GridBagLayout) container.getLayout() ).setConstraints( component, c );
          container.add( component );
       private void initPanels() {
          PanelFields okPanel = new PanelFields("Simple from...",
                                                "[email protected]; [email protected]",
                                                "Simple subject...",
                                                "[email protected]; [email protected]");
          PanelFields bitUglyPanel = new PanelFields("A bit ugly from................",
                                                     "[email protected]; [email protected]; [email protected]; [email protected]",
                                                     "A bit ungle subject.....................",
                                                     "[email protected]; [email protected]; [email protected]; [email protected]");
          PanelFields veryUglyPanel = new PanelFields("A very very very very very " +
                                                      "very very ugly from................",
                                                      "[email protected]; [email protected]; [email protected]; [email protected], " +
                                                      "[email protected]; [email protected]; [email protected]; [email protected]",
                                                      "A very very very very very very " +
                                                      "very ungle subject.....................",
                                                      "[email protected]; [email protected]; [email protected]; [email protected]; " +
                                                      "[email protected]; [email protected]; [email protected]; [email protected]");
          testPanels = new PanelChange[] {
                                            new PanelChange(okPanel),
                                            new PanelChange(bitUglyPanel),
                                            new PanelChange(veryUglyPanel)
          Container container = getContentPane();
          container.setLayout(new BorderLayout());
          JPanel buttonPanel = new JPanel();
          buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
          JButton button1 = new JButton(BUTTON_PANEL_TEST1);
          button1.setActionCommand(BUTTON_PANEL_TEST1);
          button1.addActionListener(this);
          JButton button2 = new JButton(BUTTON_PANEL_TEST2);
          button2.setActionCommand(BUTTON_PANEL_TEST2);
          button2.addActionListener(this);
          JButton button3 = new JButton(BUTTON_PANEL_TEST3);
          button3.setActionCommand(BUTTON_PANEL_TEST3);
          button3.addActionListener(this);
          buttonPanel.add(button1);
          buttonPanel.add(Box.createHorizontalStrut(5));
          buttonPanel.add(button2);
          buttonPanel.add(Box.createHorizontalStrut(5));
          buttonPanel.add(button3);
          JPanel mainPanel = new JPanel();
          mainPanel.setLayout(new GridBagLayout());
          constrain(mainPanel, loadPanel,
                    GridBagConstraints.BOTH, GridBagConstraints.WEST,
                    0, 0, 1, 1, 1.0, 1.0, new Insets(5, 5, 5, 5));
          constrain(mainPanel, buttonPanel,
                    GridBagConstraints.NONE, GridBagConstraints.CENTER,
                    0, 1, 1, 1, 0.0, 0.0, new Insets(5, 5, 5, 5));
          container.add(mainPanel);
       private void setupLoadPanel(PanelChange panelToLoad) {
          loadPanel.removeAll();
          Dimension parentSize = getSize();
          panelToLoad.recalculate(parentSize);     
          loadPanel.add(panelToLoad);
          loadPanel.revalidate();
          loadPanel.repaint(); 
       public void actionPerformed(ActionEvent e) {
          String actionCommand = e.getActionCommand();
          for (int i = 0 ; i < BUTTON_COMMANDS.length ; i++) {
             if (actionCommand.equals(BUTTON_COMMANDS)) {
    setupLoadPanel(testPanels[i]);
    break;
    public PanelChangeTest() {
    super("Panel change test...");
    Dimension size = new Dimension(WIDTH, HEIGHT);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screenSize.width - size.width) / 2;
    int y = (screenSize.height - size.height) / 2;
    setBounds(x, y, WIDTH, HEIGHT);
    addWindowListener(new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    System.exit(0);
    FontUIResource standardFont = new FontUIResource("dialogPlain11", Font.PLAIN, 11);
    UIManager.put("Label.font", standardFont);
    UIManager.put("Button.font", standardFont);
    initPanels();
    public static void main(String args[]) {
    new PanelChangeTest().setVisible(true);

  • How to reset a the contents of a JPanel

    I was just wondering the different ways one could go about resetting a JPanel. That is to clear everything then reload it.
    AKA a game of chess where the pieces have already been moved...then on the click of a button the pieces go back to their original starting positions.
    I've checked the API and fiddled about with hide(), show(), dispose() and re-adding the contents but to no avail. Well one method sort've worked but my algorithms became un-workable.
    Just wondering what the best (most efficient perhaps?) way of going about this would be.
    Thank you in advance.

    There's an example of replacing a JPanel here...
    http://forum.java.sun.com/thread.jspa?forumID=54&threadID=5248903&start=14
    It's in there somewhere, trust me... somewhere in the bit that changes the screen size.

  • Applet - page reload problem

    Greetings 4all,
    I'm developing, a bit complicated applet with few threads, listeners, and not difficult but expanded GUI. You can see it under www.demo.twelvee.com.pl.
    The problem is that this applet doesn't behave correctly after page reload in the browser. I mean that there are no graphics with parameters drawn in the middle of the main internal frame. I don't know why. When I'm visiting page first time everything works fine. This bug occurs only after reloading the page. Threads are still working, also all listeners are catching events. After few small tests I've recognized that method paintComponent() in each JPanel isn't called. I suppose it might be connected with browser's cache.
    Have You got any ideas? Because I have none, any suggestions are welcome :)
    You can access source here: http://www.iem.pw.edu.pl/~opalam/12/source/

    If it is due to the browser's cache of the applet, the only way that most (all?) current browsers will reload the applet is to close ALL of the browser's windows and restart the browser. (You used to be able to CTRL-F5 but this no longer works, afaik.)

  • Border not rendering properly on JPanel

    This is just a general question to see if I'm the only one having this problem or whether it is just a bug.
    I've got a Jframe with a couple of Jpanels within it. I want a border round one of the panels but for some reason the border only shows fully around 3 edges and only partly along the edge adjacent to the other JPanel.
    I thought this might be a layering problem with the panel without the border being placed on top of the border itself but I've had a similar problem with some JTextField. I've got 3 JTextFields in a JPanel each having their own border but every now and again the border will disappear from around the bottom JTextField.
    I realise this may well be a problem specific to my system or OS (Win 2000) but I thought I'd just check.
    Thanks, Clarkie

    Thanks for replying so quickly. Here is a cut down version of my code. I appologise now for using NetBeans as I believe this is frowned upon by many users of these forums.
    * NewJFrame.java
    * Created on 14 August 2006, 15:17
    package ets;
    import java.awt.*;
    import javax.swing.*;
    * @author  administrator
    public class sscce extends javax.swing.JFrame
        /** Creates new form NewJFrame */
        public sscce()
            initComponents();
            this.setIconImage(new ImageIcon("images/redtick48x48.gif").getImage());
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents()
            java.awt.GridBagConstraints gridBagConstraints;
            panelCont = new javax.swing.JPanel();
            panelNav = new javax.swing.JPanel();
            panelBtnsAndImg = new javax.swing.JPanel();
            panelNavBtns = new javax.swing.JPanel();
            btnNav_client = new javax.swing.JButton();
            btnNav_job = new javax.swing.JButton();
            btnNav_inv = new javax.swing.JButton();
            btnNav_cert = new javax.swing.JButton();
            btnNav_admin = new javax.swing.JButton();
            panelLogout = new javax.swing.JPanel();
            panelMain = new javax.swing.JPanel();
            panelClientMenu = new javax.swing.JPanel();
            panelClientMent_title = new javax.swing.JPanel();
            labClientMent_title = new javax.swing.JLabel();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("ETS - Client Management System");
            setBackground(new java.awt.Color(255, 255, 255));
            setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
            setName("mainFrame");
            panelCont.setLayout(new java.awt.BorderLayout());
            panelCont.setBackground(new java.awt.Color(255, 255, 255));
            panelNav.setLayout(new java.awt.BorderLayout());
            panelNav.setBackground(new java.awt.Color(255, 255, 255));
            panelNav.setMaximumSize(new java.awt.Dimension(150, 150));
            panelNav.setPreferredSize(new java.awt.Dimension(150, 100));
            panelBtnsAndImg.setLayout(new java.awt.GridLayout(0, 1));
            panelBtnsAndImg.setBackground(new java.awt.Color(255, 255, 255));
            panelBtnsAndImg.setMaximumSize(new java.awt.Dimension(150, 32767));
            panelNavBtns.setLayout(new java.awt.GridLayout(0, 1));
            panelNavBtns.setBackground(new java.awt.Color(255, 255, 255));
            btnNav_client.setText("Clients");
            panelNavBtns.add(btnNav_client);
            btnNav_job.setText("Jobs");
            panelNavBtns.add(btnNav_job);
            btnNav_inv.setText("Invoices");
            panelNavBtns.add(btnNav_inv);
            btnNav_cert.setText("Certificates");
            panelNavBtns.add(btnNav_cert);
            btnNav_admin.setText("Admin");
            panelNavBtns.add(btnNav_admin);
            panelBtnsAndImg.add(panelNavBtns);
            panelNav.add(panelBtnsAndImg, java.awt.BorderLayout.NORTH);
            panelLogout.setLayout(new java.awt.BorderLayout());
            panelLogout.setBackground(new java.awt.Color(255, 255, 255));
            panelLogout.setMaximumSize(new java.awt.Dimension(150, 32767));
            panelNav.add(panelLogout, java.awt.BorderLayout.CENTER);
            panelCont.add(panelNav, java.awt.BorderLayout.WEST);
            panelMain.setLayout(new java.awt.CardLayout());
            panelMain.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
            panelClientMenu.setLayout(new java.awt.GridBagLayout());
            panelClientMenu.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
            panelClientMent_title.setLayout(new java.awt.BorderLayout());
            labClientMent_title.setFont(new java.awt.Font("Tahoma", 0, 36));
            labClientMent_title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            labClientMent_title.setText("Main Panel");
            panelClientMent_title.add(labClientMent_title, java.awt.BorderLayout.CENTER);
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.ipadx = 5;
            gridBagConstraints.ipady = 15;
            panelClientMenu.add(panelClientMent_title, gridBagConstraints);
            panelMain.add(panelClientMenu, "card2");
            panelCont.add(panelMain, java.awt.BorderLayout.CENTER);
            getContentPane().add(panelCont, java.awt.BorderLayout.CENTER);
            jMenu1.setText("Menu");
            jMenuBar1.add(jMenu1);
            setJMenuBar(jMenuBar1);
            pack();
        }// </editor-fold>
         * @param args the command line arguments
        public static void main(String args[])
            Toolkit tk = java.awt.Toolkit.getDefaultToolkit();
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    sscce s = new sscce();
                    s.setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH);
                    s.setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton btnNav_admin;
        private javax.swing.JButton btnNav_cert;
        private javax.swing.JButton btnNav_client;
        private javax.swing.JButton btnNav_inv;
        private javax.swing.JButton btnNav_job;
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JLabel labClientMent_title;
        private javax.swing.JPanel panelBtnsAndImg;
        private javax.swing.JPanel panelClientMent_title;
        private javax.swing.JPanel panelClientMenu;
        private javax.swing.JPanel panelCont;
        private javax.swing.JPanel panelLogout;
        private javax.swing.JPanel panelMain;
        private javax.swing.JPanel panelNav;
        private javax.swing.JPanel panelNavBtns;
        // End of variables declaration
    }Also, I sometimes get a diagonal line going from the top left corner of a container to the first element when the JFrame is resized or reloaded from the Taskbar.
    Thanks again, Clarkie

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • Problem with JPanel and/or Thread

    Hello all,
    I have the following problem.
    I have a JFrame containing to JPanels. The JPanels are placed
    via BorderLayout.
    JPanel #1 is for moving a little rectangle (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this button is painted in
    the top left corner of my frame. It changes if I press another button.
    Any help would be appreciated.
    Thanks.
    Ralf

    I have a JFrame containing to JPanels. The JPanels are
    placed
    via BorderLayout.The type of Layout does not seem to be relevant
    >
    JPanel #1 is for moving a little rectangle
    (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to
    do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect
    at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface
    Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this
    button is painted in
    the top left corner of my frame. It changes if I press
    another button.
    I noticed you solved this by painting the whole JFrame.
    Yeh Form time to time I get this problem too......
    Especially if the screen has gone blank - by going and having a cup of tea etc -
    Text from one Panel would be drawn in another.. annoying
    At first it was because I changed the state of some Swing Components
    not from the Event Thread.
    So make sure that your new Thread doesn't just blithely call repaint() or such like cos that leads to problems
    but rather something like
    SwingUtilities.invokeLater( new Runnable()
       public void run()
          MyComponent.repaint();
    });However I still get this problem using JScrollPanes, and was able to fix it by using the slower backing store method for the JScrollPane
    I could not see from my code how something on one JPanel can get drawn on another JPanel but it was happening.
    Anyone who could totally enlighten me on this?

  • How to give Common Background color for all JPanels in My Swing application

    Hi All,
    I am developing a swing application using The Swing Application Framework(SAF)(JSR 296). I this application i have multiple JPanel's embedded in a JTabbedPane. In this way i have three JTabbedPane embedded in a JFrame.
    Now is there any way to set a common background color for the all the JPanel's available in the application??
    I have tried using UIManager.put("Panel.background",new Color.PINK);. But it did not work.
    Also let me know if SAF has some inbuilt method or way to do this.
    Your inputs are valuable.
    Thanks in Advance,
    Nishanth.C

    It is not the fault of NetBeans' GUI builder, JPanels are opaque by default, I mean whether you use Netbeans or not.Thank you!
    I stand corrected (which is short for +"I jumped red-eyed on my feet and rushed to create an SSCCE to demonstrate that JPanels are... mmm... oh well, they are opaque by default... ;-[]"+)
    NetBeans's definitely innocent then, and indeed using it would be an advantage (ctrl-click all JPanels in a form and edit the common opaque property to false) over manually coding
    To handle this it would be better idea to make a subclass of JPanel and override isOpaque() to return false. Then use this 'Trasparent Panel' for all the panels where ever transparency is required.I beg to differ. From a design standpoint, I'd find it terrible (in the pejorative sense of the word) to design a subclass to inconsistently override a getter whereas the standard API already exposes the property (both get and set) for what it's meant: specify whether the panel is opaque.
    Leveraging this subclass would mean changing all lines where a would-be-transparent JPanel is currently instantiated, and instantiate the subclass instead.
    If you're editing all such lines anyway, you might as well change the explicit new JPanel() for a call to a factory method createTransparentJPanel(); this latter could, at the programmer's discretion, implement transparency whichever way makes the programmer's life easier (subclass if he pleases, although that makes me shudder, or simply call thePanel.setOpaque(false) before returning the panel). That way the "transparency" code is centralized in a single easy to maintain location.
    I had to read the code for that latter's UI classes to find out the keys to use (+Panel.background+, Label.foreground, etc.), as I happened to not find this info in an authoritative document - I see that you seem to know thoses keys, may I ask you where you got them from?
    One of best utilities I got from this forum, written by camickr makes getting these keys and their values very easy. You can get it from his blog [(->link)|http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/]
    Definitely. I bit a pair of knucles off when discovered it monthes after cumbersomely traversing the BasicL&F code...
    Still, it is a matter-of-fact approach (and this time I don't mean that to sound pejorative), that works if you can test the result for a given JDK version and L&F, but doesn't guarantee that these keys are there to stand - an observation, but not a specification.
    Thanks TBM for highlighting this blog entry, that's the best keys list device I have found so far, but the questions still holds as to what specifies the keys.
    Edited by: jduprez on Feb 15, 2010 10:07 AM

  • Problem with JPanel in JFrame

    hai ashrivastava..
    thank u for sending this one..now i got some more problems with that screen .. actually i am added one JPanel to JFrame with BorderLayout at south..the problem is when i am drawing diagram..the part of diagram bellow JPanel is now not visible...and one more problem is ,after adding 6 ro 7 buttons remaing buttons are not vissible..how to increase the size of that JPanel...to add that JPanel i used bellow code
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    f.getContentPane().add(BorderLayout.SOUTH, panel);

    Hi
    JFrame f = new JFrame();
    JPanel panel = new JPanel();
    // Add this line to ur code with ur requiredWidth and requiredHeight
    panel.setPreferredSize(new Dimension(requiredWidth,requiredHeight));
    f.getContentPane().add(BorderLayout.SOUTH, panel);
    This should solve ur problem
    Ashish

Maybe you are looking for

  • Reverse/ delete downpayment request through F-47

    Hi friends, Can any one please tell me , how do I delete/reverse downpayment request made using F-47. Please let me know Thanks

  • Deploying a webservice on Jigsaw on Unix

    Hi All. We were able to successfully build and deploy a webservice on tomcat running on Windows. What we want to do is run it on a remote UNIX server running Jigsaw. What we're not able to do is find out where to actually put the war files and deploy

  • Linux version for SAP ECC 6.0

    Dear all, Please help me in finding the suitable Linux version for SAP ECC 6.0 version. Thanks & Regards Tavargeri Ganesh

  • Yosemite 10.10 and After Effects CC - Opens, but only the render que.

    Downloaded the Yosemite beta 2 the other day, not thinking about how all programs would work or not. So, all adobe programs open just fine, except for After effects. I've heard others having problems opening it - my problem is bit different. After ef

  • IPhone lags when texting

    Anyone else have this problem. When I try to send an SMS, it takes my iPhone 3G about 3/4 of a second from the time I hit a letter to the time it actually types it in the message. Not only that, but the letter I touch stays in the bigger format (exte