peter55555
peter55555

Reputation: 1475

How to refresh JFrame

I know there were similar questions but I have some different problem...

I'd like to remove all elements of JFrame after clicking a button:

It works:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0)
    {
        frame.getContentPane().removeAll();
        frame.revalidate();
        frame.repaint();
    }
});

All elements disappeared. But after that I need to putelements on this JFrame... After these 3 lines above (below frame.repaint()) I call method initialize (method that I call when I create my window at the beginning):

private void initialize()
{
    frame = new JFrame();
    frame.setBounds(100, 100, 1454, 860);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnNewSubject = new JButton("New subject");
    btnNewSubject.setBounds(647, 788, 137, 23);
    frame.getContentPane().add(btnNewSubject);

    JButton btnRefresh = new JButton("Refresh");
    btnRefresh.setBounds(1339, 788, 89, 23);
    frame.getContentPane().add(btnRefresh);

    JLabel lblNewLabel = new JLabel("Subject");
    lblNewLabel.setBounds(235, 11, 75, 14);
    frame.getContentPane().add(lblNewLabel);

    JLabel lblOwner = new JLabel("Owner");
    lblOwner.setBounds(662, 11, 46, 14);
    frame.getContentPane().add(lblOwner);

    JLabel lblStatus = new JLabel("Status");
    lblStatus.setBounds(883, 11, 46, 14);
    frame.getContentPane().add(lblStatus);

    JLabel lblDateOfAdded = new JLabel("Date of added");
    lblDateOfAdded.setBounds(1104, 11, 116, 14);
    frame.getContentPane().add(lblDateOfAdded);
}

Nothing happens. :( JFrame is still empty. Even if I call revalidate and repaint().

What is wrong?

Upvotes: 1

Views: 3063

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You are creating a completely new JFrame in your method here

frame = new JFrame();

and you never display it, you never call setVisible(true) on it, and so it will remain invisible. It almost sounds as if you're creating two JFrames without realizing it, that you are adding components to the second non-displayed JFrame, but are leaving displaying just the first one, the one without new components.

More importantly, you will want to use a CardLayout to help you swap your JPanel views as this situation is exactly what it's built for. Also, Your program uses null layout and setBounds(...) something that results in a rigid GUI that may look good on one system but will usually look poor on any other system or screen resolution. Programs created this way are very hard to debug, maintain and upgrade. Instead use the layout managers as this is what they excel at: at creating complex flexible GUI's that can be enhanced and changed easily.

Note that your removeAll() call does not remove the root pane as Ludovic is stating because you're calling this on the contentPane not the JFrame, and the contentPane does not contain the root pane.


Edit
For example,

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class CardLayoutEg extends JPanel {
   private CardLayout cardlayout = new CardLayout();
   private TitlePanel titlePanel = new TitlePanel(this);
   private SubjectPanel subjectPanel = new SubjectPanel(this);

   public CardLayoutEg() {
      setLayout(cardlayout);
      add(titlePanel, titlePanel.getName());
      add(subjectPanel, subjectPanel.getName());
   }

   public void nextCard() {
      cardlayout.next(this);
   }

   public void showCard(String key) {
      cardlayout.show(this, key);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("CardLayout Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new CardLayoutEg());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

}

class TitlePanel extends JPanel {
   public static final String TITLE_PANEL = "title panel";
   private static final int PREF_W = 900;
   private static final int PREF_H = 750;
   private static final String TITLE = "My Application Title";
   private static final float POINTS = 46f;
   private CardLayoutEg cardLayoutEg;

   public TitlePanel(CardLayoutEg cardLayoutEg) {
      setName(TITLE_PANEL);
      this.cardLayoutEg = cardLayoutEg;

      JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
      titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, POINTS));

      JButton subjectButton = new JButton(new SubjectAction("Subjects"));
      JPanel buttonPanel = new JPanel();
      buttonPanel.add(subjectButton);

      setLayout(new BorderLayout());
      add(titleLabel, BorderLayout.CENTER);
      add(buttonPanel, BorderLayout.PAGE_END);
   }

   @Override
   public Dimension getPreferredSize() {
      if (isPreferredSizeSet()) {
         return super.getPreferredSize();
      }
      return new Dimension(PREF_W, PREF_H);
   }

   private class SubjectAction extends AbstractAction {
      public SubjectAction(String name) {
         super(name);
         int mnemonic = (int) name.charAt(0);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         cardLayoutEg.showCard(SubjectPanel.SUBJECT_PANEL);
      }
   }
}

class SubjectPanel extends JPanel {
   public static final String SUBJECT_PANEL = "subject panel";
   private static final String[] COLUMN_NAMES = {"Subject", "Owner", "Status", "Date Added"};
   DefaultTableModel tableModel = new DefaultTableModel(COLUMN_NAMES, 10);
   private JTable table = new JTable(tableModel);
   private CardLayoutEg cardLayoutEg;

   public SubjectPanel(CardLayoutEg cardLayoutEg) {
      setBorder(BorderFactory.createTitledBorder("Subject Panel"));
      setName(SUBJECT_PANEL);
      this.cardLayoutEg = cardLayoutEg;

      JPanel buttonPanel = new JPanel();
      buttonPanel.setLayout(new GridLayout(1, 0, 10, 0));
      buttonPanel.add(new JButton("New Subject"));
      buttonPanel.add(new JButton("Refresh"));
      buttonPanel.add(new JButton(new TitleAction("Title")));
      buttonPanel.add(new JButton(new ExitAction("Exit")));

      JPanel bottomPanel = new JPanel();
      bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
      bottomPanel.add(Box.createHorizontalGlue());
      bottomPanel.add(buttonPanel);

      setLayout(new BorderLayout());
      add(new JScrollPane(table), BorderLayout.CENTER);
      add(bottomPanel, BorderLayout.PAGE_END);
   }

   private class TitleAction extends AbstractAction {
      public TitleAction(String name) {
         super(name);
         int mnemonic = (int) name.charAt(0);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         cardLayoutEg.showCard(TitlePanel.TITLE_PANEL);
      }
   }

   private class ExitAction extends AbstractAction {
      public ExitAction(String name) {
         super(name);
         int mnemonic = KeyEvent.VK_X;
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         Component component = (Component) e.getSource();
         Window win = SwingUtilities.getWindowAncestor(component);
         win.dispose();
      }
   }
}

Upvotes: 5

Related Questions