Replacing a JPanel

Hi
In one of the dialogs of my application, I have a JPanel that describes some properties of one of my objects.
The object's properties described by my JPanel can be "empty' (when I have no properties to describe, I put in the JPanel a JLabel saying "No properties inserted" and a JButton "insert properties) or a Box with the properties I want (A vertical Box filled with horizontal Box, the first horizontal Box are JLabels (name, value, limit...) and the second Box are "JTextField"s).
When I have no properties and I press the button "insert properties", I replace the JPanel with a new JPanel with the new Layout.
The problem is that, when I have the button pressed to replace the JPanel, my new JPanel is not painted correctly (everything seems to be painted in the same place, component over component). I've already tested only the new JPanel on a JFrame and it is fine, the problem happens only when I try to replace the panels.
So, can you help me solve my problem?
thanks in advance

If you don't use a card layout, you need to either remove the old panel or make it invisible. Card layout of should work fine. Are you sure you're making the switch in the Event Dispatch Thread?

Similar Messages

  • How do I replace one JPanel on a JFrame with another?

    I want to replace one JPanel on a JFrame with a different JPanel when the user clicks on a certain menu item. The menu item is working corrrectly but I cant seem to repaint / refresh the component.
    My code is as follows:
    c.add(knotPanel, BorderLayout.CENTER);
    c.add(stepPanel, BorderLayout.NORTH);
         if (stepChoice != 9) {
         c.remove(ownPanel);
         c.add(lessonPanel, BorderLayout.EAST);
         else {
         c.remove(lessonPanel);
         c.add(ownPanel, BorderLayout.EAST);
         c.invalidate();
         c.validate();
         c.update(c.getGraphics());
    Any ideas?

    I think you should use CardLayout manager.
    With CardLayout you can switch beetwen JPanels without removing or adding.

  • Swing - replace a JPanel

    Hello,
    I'm with a little problem here:
    When I try to change a JPanel, it only gets updated at the end of all the code.
    This is the code I have right now:
    private void okActionPerformed(java.awt.event.ActionEvent evt) {                                  
            JFrame mainFrame = DesktopApplication1.getApplication().getMainFrame();
            String temp1 = quelle.getText();
            String temp2 = ziel.getText();
            if(temp1.equalsIgnoreCase("") || temp2.equalsIgnoreCase("")) {
                if(temp1.equalsIgnoreCase("") && temp2.equalsIgnoreCase(""))
                    JOptionPane.showMessageDialog(mainFrame, "Sie durfen nicht das Quellenfeld und das Zielfeld leer lassen!", "Warnung!", JOptionPane.WARNING_MESSAGE);
                if(temp1.equalsIgnoreCase("") && !temp2.equalsIgnoreCase(""))
                    JOptionPane.showMessageDialog(mainFrame, "Sie durfen nicht das Quellenfeld leer lassen!", "Warnung!", JOptionPane.WARNING_MESSAGE);
                if(temp2.equalsIgnoreCase("") && !temp1.equalsIgnoreCase(""))
                    JOptionPane.showMessageDialog(mainFrame, "Sie durfen nicht das Zielfeld leer lassen!", "Warnung!", JOptionPane.WARNING_MESSAGE);
            } else {
                mainPanel.setVisible(false);
                mainFrame.remove(mainPanel);
                mainFrame.validate();
    }Does anyone know what I have to do?
    I've been an entire day trying to find the solution... :(
    Thanks in advance!
    Edited by: Freiheitpt on Jul 29, 2009 9:51 PM
    Edited by: Freiheitpt on Jul 29, 2009 9:53 PM

    ok then,
    I put here the entire code, but be warned: i'm using netbeans (a lot of auto-code xD)
    public class DesktopApplication1View extends FrameView {
        private File src;
        private File dst;
        public DesktopApplication1View(SingleFrameApplication app) {
            super(app);
            initComponents();
            this.getFrame().setResizable(true);
            this.getFrame().setSize(400, 500);
           (Code removed - auto code from NetBeans)
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            UIManager.put("FileChooser.readOnly", Boolean.TRUE);
            JFileChooser chooser = new JFileChooser();
              chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              chooser.setMultiSelectionEnabled(false);
              chooser.setDialogTitle("Quelle:");
              if(chooser.showOpenDialog(DesktopApplication1.getApplication().getMainFrame()) == JFileChooser.APPROVE_OPTION) {
                src = chooser.getSelectedFile();
                quelle.setText(src.toString());
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            UIManager.put("FileChooser.readOnly", Boolean.FALSE);
            JFileChooser chooser = new JFileChooser();
              chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              chooser.setMultiSelectionEnabled(false);
              chooser.setDialogTitle("Ziel:");
            if(chooser.showSaveDialog(DesktopApplication1.getApplication().getMainFrame()) == JFileChooser.APPROVE_OPTION) {
                dst = chooser.getSelectedFile();
                ziel.setText(dst.toString());
        private void okActionPerformed(java.awt.event.ActionEvent evt) {                                  
            JFrame mainFrame = DesktopApplication1.getApplication().getMainFrame();
            String temp1 = quelle.getText();
            String temp2 = ziel.getText();
            if(temp1.equalsIgnoreCase("") || temp2.equalsIgnoreCase("")) {
                if(temp1.equalsIgnoreCase("") && temp2.equalsIgnoreCase(""))
                    JOptionPane.showMessageDialog(mainFrame, "Sie durfen nicht das Quellenfeld und das Zielfeld leer lassen!", "Warnung!", JOptionPane.WARNING_MESSAGE);
                if(temp1.equalsIgnoreCase("") && !temp2.equalsIgnoreCase(""))
                    JOptionPane.showMessageDialog(mainFrame, "Sie durfen nicht das Quellenfeld leer lassen!", "Warnung!", JOptionPane.WARNING_MESSAGE);
                if(temp2.equalsIgnoreCase("") && !temp1.equalsIgnoreCase(""))
                    JOptionPane.showMessageDialog(mainFrame, "Sie durfen nicht das Zielfeld leer lassen!", "Warnung!", JOptionPane.WARNING_MESSAGE);
            } else {
                mainPanel.setVisible(false);
                mainFrame.remove(mainPanel);
                mainFrame.add(process);
                process.setVisible(true);
                mainFrame.repaint();
                mainFrame.pack();
                mainFrame.validate();
                folders.setText(quelle.getText() + "\n|\n\\/\n" + ziel.getText());
      //          String[] extensions = {"jpg", "jpeg"};
    //           FileListExtensionFilter filter = new FileListExtensionFilter(extensions, false);
    //            File[] selectedFiles = src.listFiles(filter);
                /*Config cfg = Config.getInstance();
                float rel = 1;
                for(int i = 0; i < selectedFiles.length; i++) {
                File current = selectedFiles;
    String filename = current.getName();
    String ext = filename.substring(filename.lastIndexOf('.') + 1);
    filename = filename.substring(0, filename.lastIndexOf('.'));*/
    // BufferedImage image = ImageUtils.loadImage(current);
    // rel = MyUtils.calcRelativeSize(image.getWidth(), image.getHeight(), 300, 300);
    // BufferedImage previewImage = ImageUtils.resize(image, rel);
    // imageName.setText(filename + "." + ext);*/
    // JOptionPane.showMessageDialog(mainFrame, imageName.getText(), "Test", JOptionPane.ERROR_MESSAGE);
    /*preview.removeAll();
    preview.add(new JImagePanel(previewImage, (int)((preview.getWidth()-previewImage.getWidth())/2), (int)((preview.getHeight()-previewImage.getHeight())/2)));
    rel = MyUtils.calcRelativeSize(image.getWidth(), image.getHeight(),
    (int) (cfg.getMaxW()*cfg.getSizeProportion()), (int) (cfg.getMaxH()*cfg.getSizeProportion()));
    if(rel == 1 && cfg.getWatermark() == null && cfg.getTextStamp() == null) {
    try {
    FileUtils.Copy(selectedFiles[i], new File(dst.toString() + "\\"+ filename + "-iRez." + ext));
    } catch (IOException e) {
    e.printStackTrace();
    } else {
    image = ImageUtils.resize(image, rel);
    BufferedImage watermark = ImageUtils.loadImage(cfg.getWatermark());
    rel = MyUtils.calcRelativeSize(watermark.getWidth(), watermark.getHeight(),
    (int) (watermark.getWidth()*cfg.getWatermarkProportion()),
    (int) (watermark.getHeight()*cfg.getWatermarkProportion()));
    watermark = ImageUtils.resize(watermark, 0.5f);
    image = ImageWatermark.markImage(image, watermark, cfg.getWatermarkAlpha(),
    cfg.getWatermarkLocation(), cfg.getTextOffsetX(), cfg.getTextOffsetY());
    if(cfg.getTextStamp() != null)
    image = ImageWatermark.markText(image, cfg.getTextStamp(), cfg.getTextStampFont(),
    cfg.getTextStampFontColor(), cfg.getTextOffsetX(), cfg.getTextOffsetY(), cfg.getTextStampAlpha());
    ImageUtils.saveImage(image, new File(dst.toString() + "\\"+ filename + "-iRez." + ext));
    some code is commented cause i was debugging.
    Edited by: Freiheitpt on Jul 29, 2009 11:23 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Refreshing a set of JPanels

    Hello there,
    I have an issue with refreshing and replacing my JPanel colors. As you can see, the format is GridLayout with the size of the grid changing based on what file they open. My issue is that when a second file is opened, it merely adds those JPanels to the end of the previously loaded set of JPanels. I've tried refresh() and repaint() but to no avail. Maybe I placed them in the wrong place, not sure. Thanks in advance.
              if (actionCommand.equals("Open..."))
                   JFileChooser fileChooser = new JFileChooser();
                   fileChooser.setDialogTitle("Choose a file");
                   this.getContentPane().add(fileChooser);
                   fileChooser.setVisible(true);
                   int result = fileChooser.showOpenDialog(this);
                   File file = fileChooser.getSelectedFile();
                   GridMap gm = new GridMap();
                   gm.read(file);
                   int row = gm.getRow();
                   int col = gm.getColumn();
                   setLayout(new GridLayout(row,col));
                   for (int i = 0; i < row; i++)
                        for (int j = 0; j < col; j++)
                             JLabel color = new JLabel();
                             color.setOpaque(true);
                             if (gm.getGrid(i,j) == 'O')
                                  color.setBackground(Color.GREEN);
                             else if (gm.getGrid(i,j) == 'F')
                                  color.setBackground(Color.RED);
                             else if (gm.getGrid(i,j) == 'H')
                                  color.setBackground(Color.BLACK);
                             add(color);
              }

    something along these lines
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.*;
    public class MainFrame2
      private static final String EXIT = "Exit";
      private static final String OPEN = "Open...";
      private static final String START = "Start";
      private JPanel mainPanel = new JPanel();
      private JPanel gridPanel = new JPanel();
      public MainFrame2()
        mainPanel.setPreferredSize(new Dimension(300, 300));
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(gridPanel, BorderLayout.CENTER);
      public JComponent getPanel()
        return mainPanel;
      public JMenuBar createMenu()
        JMenu sim = new JMenu("Simulator");
        MenuListener menuListener = new MenuListener();
        JMenuItem m = new JMenuItem(OPEN);
        m.addActionListener(menuListener);
        sim.add(m);
        m = new JMenuItem(START);
        m.addActionListener(menuListener);
        sim.add(m);
        sim.addSeparator();
        m = new JMenuItem(EXIT);
        m.addActionListener(menuListener);
        sim.add(m);
        JMenuBar mBar = new JMenuBar();
        mBar.add(sim);
        return mBar;
      private class MenuListener implements ActionListener
        public void actionPerformed(ActionEvent e)
          String actionCommand = e.getActionCommand();
          if (actionCommand.equals(OPEN))
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Choose a file");
            //mainPanel.add(fileChooser);
            fileChooser.setVisible(true);
            int result = fileChooser.showOpenDialog(mainPanel);
            if (result == JFileChooser.APPROVE_OPTION)
              File file = fileChooser.getSelectedFile();
              GridMap gm = new GridMap();
              gm.read(file);
              int row = gm.getRow();
              int col = gm.getColumn();
              gridPanel.setLayout(new GridLayout(row, col));
              gridPanel.removeAll();
              for (int i = 0; i < row; i++)
                for (int j = 0; j < col; j++)
                  JLabel color = new JLabel();
                  color.setOpaque(true);
                  if (gm.getGrid(i, j) == 'O')
                    color.setBackground(Color.GREEN);
                  else if (gm.getGrid(i, j) == 'F')
                    color.setBackground(Color.RED);
                  else if (gm.getGrid(i, j) == 'H')
                    color.setBackground(Color.BLACK);
                  gridPanel.add(color);
          else if (actionCommand.equals(START))
            // setVisible(true);
          else if (actionCommand.equals(EXIT))
            Window window = SwingUtilities.getWindowAncestor(mainPanel);
            window.dispose();
      private static void createAndShowGUI()
        MainFrame2 frame2 = new MainFrame2();
        JFrame frame = new JFrame("Fire Saving Simulator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(frame2.getPanel());
        frame.setJMenuBar(frame2.createMenu());
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        javax.swing.SwingUtilities.invokeLater(new Runnable()
          public void run()
            createAndShowGUI();
    }

  • Replacing existing panel with a new panel.

    I don't use swing much and I have ran into a small problem.
    What is the standard procedure for replacing a jpanel on a
    jframe with another jpanel in the exact same position?
    Say you had a form on the first panel, when the user clicks
    next it display a new panel with a confirmation of the results
    and disposes of the old one.
    I have tried add,remove, setcontenpane. setvisible etc but nothing
    works. Can someone explain?
    Here is a small app which demonstrates my problem:
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class FrameTest extends JFrame implements ActionListener{
         JPanel jp1;
         JPanel jp2;
         JButton jb1;
         JButton jb2;
         public FrameTest(String name) {
              super(name);
              init();
         public void init() {
              jp1 = new JPanel(new FlowLayout());
              jb1 = new JButton("One");
              jb1.addActionListener(this);
              jp1.add(jb1);
              setContentPane(jp1);
              setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              setBounds(0, 0, 200, 200);
              setVisible(true);
         public JPanel panelTwo() {
              jp2 = new JPanel(new FlowLayout());
              jb2 = new JButton("Two");
              jb2.addActionListener(this);
              jp2.add(jb2);
              return jp2;
         public static void main(String[] args) {
              FrameTest ft = new FrameTest("Test");
          * On click I wish to replace panel one
          * with panel two
         public void actionPerformed(ActionEvent e) {
                   //What can I add here?
    }Regards

    I just took a look on the Java Tutorial and it is exactly what I am after.
    Thank you.

  • Wait for resizing JPanel

    nice day,
    during rezize JFrame simultaneously changing the size of JFrame Childs, how to stop, pause or wait for that and resize JFrame Childs just one time
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.border.EmptyBorder;
    public class PaintPanels extends JFrame {
        private static final long serialVersionUID = 1L;
        private final JPanel fatherPanel = new JPanel();
        private SomePanel centerPanel;
        private SomePanel northPanel;
        private SomePanel southPanel;
        public void makeUI() {
            centerPanel = new SomePanel();
            northPanel = new SomePanel();
            southPanel = new SomePanel();
            centerPanel.setName("centerPanel");
            northPanel.setName("northPanel");
            southPanel.setName("southPanel");
            northPanel.setPreferredSize(new Dimension(1020, 170));
            centerPanel.setPreferredSize(new Dimension(1020, 300));
            southPanel.setPreferredSize(new Dimension(1020, 170));
            fatherPanel.setLayout(new BorderLayout(5, 5));
            fatherPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
            fatherPanel.add(northPanel, BorderLayout.NORTH);
            fatherPanel.add(centerPanel, BorderLayout.CENTER);
            fatherPanel.add(southPanel, BorderLayout.SOUTH);
            setLayout(new BorderLayout(5, 5));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            add(fatherPanel, BorderLayout.CENTER);
            pack();
            setVisible(true);
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new PaintPanels().makeUI();
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class SomePanel extends JPanel {
        private static final long serialVersionUID = 1L;
        private GradientPanel titlePanel;
        protected JLabel titleLabel;
        int borderOffset = 2;
        public SomePanel() {
            setLayout(new BorderLayout(5,5));
            setBorder(BorderFactory.createLineBorder(Color.gray, 1));
            addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    Component comp = e.getComponent();
                    String compName = comp.getName();
                    System.out.print("Mouse click from " + compName + "\n");
                @Override
                public void mousePressed(MouseEvent e) {
                @Override
                public void mouseReleased(MouseEvent e) {
                @Override
                public void mouseEntered(MouseEvent e) {
                @Override
                public void mouseExited(MouseEvent e) {
            titleLabel = new JLabel("  Welcome World  ", JLabel.LEADING);
            titleLabel.setForeground(Color.darkGray);
            titlePanel = new GradientPanel(Color.black);
            titlePanel.setLayout(new BorderLayout());
            titlePanel.add(titleLabel, BorderLayout.WEST);
            titlePanel.setBorder(BorderFactory.createEmptyBorder(borderOffset, 4, borderOffset, 1));
            titlePanel.setBorder(BorderFactory.createLineBorder(Color.lightGray));
            titlePanel.setMinimumSize(new Dimension(300, 25));
            titlePanel.setPreferredSize(new Dimension(800, 25));
            titlePanel.setMaximumSize(new Dimension(1200, 25));
            add(titlePanel, BorderLayout.NORTH);
    import java.awt.Color;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Paint;
    import javax.swing.JPanel;
    class GradientPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        public GradientPanel(Color background) {
            setBackground(background);
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (isOpaque()) {// Color controlColor = UIManager.getColor("control");
                //Color background = new Color(44, 61, 146);
                //Color controlColor = new Color(168, 204, 241);
                Color background = new Color(168, 210, 241);
                Color controlColor = new Color(230, 240, 230);
                int width = getWidth();
                int height = getHeight();
                Graphics2D g2 = (Graphics2D) g;
                Paint oldPaint = g2.getPaint();
                g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
                //g2.setPaint(new GradientPaint(0, 0, getBackground(), width, 0, controlColor));
                g2.fillRect(0, 0, width, height);
                g2.setPaint(oldPaint);
    }

    nice day,
    could you hepl me with some definitions, still I can't to define gap for first and last of JLabel (matrix), is there some hack for GridBagLayout,
    hmmm, interesting that if I replace South JPanel and put there JPanet that contains only JButtons, then that's/just only this one (JPanel) doesn't any problems with synchronizations for repaint with JFrame,
    result is: resize isn't smooth, Border jump, resize breaking,
    already at a fraction of JComponents that I would like to display,
    I certainly know that the reason is the LCD display, where its native resolution makes a huge problem with the edge of Border and FontSize, 'glass screen' doesn't suffering from similar diseases,
    so there my question is how to stop the refresh, resize JPanels with its parents, therefore wait until the resize event ends on JFrame
    import java.awt.*;
    import javax.swing.*;
    public class ChildPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        public ChildPanel() {
            JLabel hidelLabel;
            JLabel firstLabel;
            JTextField firstText;
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            for (int k = 0; k < 50; k++) {
                hidelLabel = new JLabel("     ");
                //hidelLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.weightx = 0.5;
                gbc.weighty = 0.5;
                gbc.gridx = k;
                gbc.gridy = 0;
                add(hidelLabel, gbc);
            for (int k = 0; k < 5; k++) {
                firstLabel = new JLabel("Testing Label : ", SwingConstants.RIGHT);
                firstLabel.setFont(new Font("Serif", Font.BOLD, 20));
                firstLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                //gbc.ipady = 0;       //reset to default
                //gbc.weighty = 1.0;   //request any extra vertical space
                //gbc.anchor = GridBagConstraints.PAGE_END; //bottom of space
                gbc.insets = new Insets(0, 0, 5, 0);  //top padding
                gbc.gridx = 0;       //aligned with JLabel 0
                gbc.gridwidth = 8;   //8 columns wide
                gbc.gridy = k + 1;
                add(firstLabel, gbc);
            for (int k = 0; k < 5; k++) {
                firstText = new JTextField("Testing TextField");
                firstText.setFont(new Font("Serif", Font.BOLD, 20));
                firstText.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.insets = new Insets(0, 0, 5, 0);
                gbc.gridx = 9;
                gbc.gridwidth = k + 8;
                gbc.gridy = k + 1;
                add(firstText, gbc);
            for (int k = 0; k < 5; k++) {
                firstLabel = new JLabel("Testing Label : ", SwingConstants.RIGHT);
                firstLabel.setFont(new Font("Serif", Font.BOLD, 20));
                firstLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.insets = new Insets(0, 0, 5, 0);
                gbc.gridx = 20 + k;
                gbc.gridwidth = 8;
                gbc.gridy = k + 1;
                add(firstLabel, gbc);
            for (int k = 0; k < 5; k++) {
                firstText = new JTextField("Testing TextField");
                firstText.setFont(new Font("Serif", Font.BOLD, 20));
                firstText.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.insets = new Insets(0, 0, 5, 0);
                gbc.gridx = 29 + k;
                gbc.gridwidth = 21 - k;
                gbc.gridy = k + 1;
                add(firstText, gbc);
    import java.awt.*;
    import javax.swing.JPanel;
    class GradientPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        public GradientPanel(Color background) {
            setBackground(background);
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (isOpaque()) {
                Color background = new Color(168, 210, 241);
                Color controlColor = new Color(230, 240, 230);
                int width = getWidth();
                int height = getHeight();
                Graphics2D g2 = (Graphics2D) g;
                Paint oldPaint = g2.getPaint();
                g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
                g2.fillRect(0, 0, width, height);
                g2.setPaint(oldPaint);
    }

  • 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.

  • Updating a JFrame with a new panel

    Hi,
    i want to switch a JPanel placed in my JFrame. But if i do so, i always have to maximize the window and then bring it back again, to see the changes work completely.
    I tried both repaint() and validate() but both do not work that I always have to maximize the window to see the changes.
    Can anybody help me to solve this?
    Thanks for answers in advance!

    I don't know exactly what you mean by switching a JPanel.
    You might want to read the CardLayout tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html
    If you replace a JPanel you need to call revalidate on the parent of the JPanel you are replacing.
    If you want further help post a Short, Self Contained, Compilable and Executable, Example Program ([url http://homepage1.nifty.com/algafield/sscce.html]SSCCE) that demonstrates the problem.
    And don't forget to use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting when posting code.

  • Custom Cell Renderer for JList

    I'm getting some strange behaviour from my custom cell renderer.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class TestRenderer implements ListCellRenderer {
      private JPanel jpCell = new JPanel();
      public Component getListCellRendererComponent
          (JList list, Object value, int index, boolean isSelected,
           boolean cellHasFocus) {
        jpCell.add(new JLabel("Render"));
        return jpCell;
    import javax.swing.*;
    import java.awt.*;
    public class TestPanel extends JFrame {
         public TestPanel() {
              JList jlst = new JList(new String[]{"Value", "Value2", "Value3"});
              jlst.setCellRenderer(new TestRenderer());
              JPanel panel = new JPanel();
              panel.add(jlst);
              add(panel);
         public static void main(String[] args) {
              TestPanel frame = new TestPanel();
              frame.setSize(300, 300);
              frame.setLocationRelativeTo(null);
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.setVisible(true);
    }As you will see the renderer displays the string several times in each cell depending on which layout manager I use. However, if I replace the JPanel with a JLabel and set the String as text on the label the String is only printed once per cell. I can't see to find the reason for this.
    Edited by: 811488 on 18-Nov-2010 09:44
    Edited by: 811488 on 18-Nov-2010 09:45
    Edited by: 811488 on 18-Nov-2010 09:45

    So getListCellRendererComponent returns a component whose paintComponent method is called with the Graphics object of the JList Yes, except that the paint(...) method is called. There is a difference. paintComponent() only paints the component. In the case of a JPanel you would get a boring gray colored component. paint() will paint the component and its children and the Border of the component as well. So you get a much more exiting component.
    Read the section from the Swng tutorial on [url http://download.oracle.com/javase/tutorial/uiswing/painting/index.html]Custom Painting for more information.
    So the state of the cell is not the state of the cell Renderer Component meaning the image rendered onto the cell only reflects the state of the Cell Renderer Component at the time the cell was rendered.Yes which is why this method should be efficient because repainting is consistently being done for all the cells. For example every time row selection changes multiple rows need to be repainted. Think of this same concept when you use a JTable which also contains multiple columns for each row.
    That is why you should not be adding/removing components in the rendering code.
    It makes sense except that if this was the case the first version of the Render that I posted should have been rendered first with one "Render" then two then three, shouldn't it?Yes, except that you can't control when or how often the rendering is done. Add the following to the renderer:
    System.out.println(index + " : " + jpCell.getComponentCount());You will see that rendering is done multiple times. The JList tries to determine its preferred width. To do this it loops through all the items in the list and invokes the renderer to get the width of the largest renderer. Well the largest width is the last renderer because 3 labels have been added to the panel. So that width becomes the preferred width of the list. Then the GUI is displayed and the list is painted. Every time the renderer is called an new label is added, but after the 3rd label there is no room to paint the label so it is truncated.
    Change your code to the following:
    //add(panel);
    add(jlst);Now change the width of the frame to see what happens.
    Given all the help you have received, I expect to see many "helpfull answers" selected as well as a "correct answer" (if you want help in the future that is).

  • Best Practises

    Hi all, I am trying to create an application. I am providing the user with a screen, they click a button, filechooser appears, file selected. User does not go back to previous screen. User is now moved on to a new screen. JComboBox selection required . . . and so on.
    What is the best method for:
    1) Developing a program with screen flows like this?
    a) JFrame after JFrame after JFrame
    b) JFrame with iFrames
    2) Storing user selected data as they move through the program?
    ---- sorry I have no insights into this one. I tried to create a class that would hold the variables, but when I moved from one frame to the next I kept getting a null value, so I think the instance of the class holding the variables must be ... ? I tried JFrame and iFrame idea, but realised that although the book I was reading has an example all in one file, they are in fact different classes from each other. I thought the classes were inside the extends JFrame class. I was hoping to use the JFrame to hold the variables aquired while the user made selections in each iFrame.
    Any suggestions, recommendations, pointers, advice, opinions, jokes, anything?

    Think about similar programs which do this. e.g. install programs, wizards
    What do you like/dislike about these programs?
    Try to do the things you liked and not do the things you dislikes.
    You can reuse a JFrame by putting a JPanel inside it can replacing the JPanel with each new screen, this keeps the window in the same place without the apprearance of opening multiple windows.

  • Next, next, and next

    I'm making a small (temporary Swing) Application that has a linear set of "back" / "next" steps that the user must complete to achieve the user's / program goal.
    This "back" / "next" is very similar to that of a Wizard or common installation procedure (but is not a wizard or installation procedure).
    Each Frame (window) will have a common header and common footer which contains the Back / next buttons.
    I want the centre (or body) of the window to change at each step of the process. Each step requires different user controls such as combo boxes, list box's, passcode fields and images and so on.
    Due to limited screen space all steps cannot be "dumped" onto one main window.
    I do not wish to use a new pop up dialog box's for each step!
    I also do not wish to use a tabbed window setup.
    I currently have the idea of constructing a new panel for each step, and "attaching" (and removing the original) the appropriated panel at each step.
    My question is: Is this the best method? Is this memory efficient? And more importantly, is there a better approach to take???
    How would others achieve the same result?
    Is it possible to embed a frame inside a frame, much like an IFRAME inside a webpage???
    Any method proposed must be both simple and memory efficient, since this application will be converted to work on a mobile device using the Symbian Operating system, which means using AWT instead of Swing (just remove the "J" from the data type).

    That's exactly what I would do.
    Each screen would be a differnt object that extends JPanel. You can have a common class to take care of the header and buttons and just replace the Jpanel each time.
    As for mobile devices, I've never written a piece of Swing that I was able to port to a mobile device just by removing the J. There are so many differences between what is availble in J2SE and J2ME that (IMO) you would be leaps ahead just coding two applications. The architecture would remain and I have never had memory problems. I've written applications like this with 30+ screens and has not been a problem.
    If memory is a great concern, you can use a classloader to load and unload the classes as needed to load a new panel at the expense of speed.
    Good Luck.

  • How to replace a component in the JPanel?

    Hi,
    I want to replace a component in the JPanel. My panel has GridBagLayout.
    Thanks in advance.

    because my application demands me to use GridBagLayout.No it doesn't, that a choice you made. You are never forced to use a specific layout manager. In fact most layout problems are solved by using combinations of layout managers. You two main choices are:
    a) use a GridbagLayout for the main panel and then a CardLayout for the two components you want to sway, although it may look strange if the components are a different size as the preferred size of the panel will be the size of the largest component
    b) Simulate a card layout using:
    panel.remove(...)
    panel.add(...);
    panel.revalidate(...)

  • First GUI help needed - replace JPanel?

    Hello guys,
    I'm trying to develop my first GUI and I'm using Netbeans to create the GUI
    here's an image of what I have: http://www.imagebullet.com/i/Sv3FrBmURS6V.gif
    the central part of the GUI is a JPanel (the big part that contains "welcome to ...")
    now I'd like to create a new JPanel with Netbeans to replace the current one when I click store new password from the tasks menu (see the image)
    how can I do it? is this the correct approach at developing a GUI? or is there something I'm completely missing?
    Edited by: Icecube on Mar 8, 2008 6:35 AM

    Icecube wrote:
    I'm trying to develop my first GUI and I'm using Netbeans to create the GUIThat may be your first mistake. The more you offload code creation to another program (the NetBeans GUI builder), the less you understand about the concepts. If you really want to learn about coding a GUI, learn to do it without code generation software by going through the Sun Swing tutorials.
    now I'd like to create a new JPanel with Netbeans to replace the current one when I click store new password from the tasks menu (see the image)
    how can I do it? is this the correct approach at developing a GUI? or is there something I'm completely missing?You could use a CardLayout as one way to solve this. Again, check out the tutorials for this (you can search the tutorial), and also check the API. Good luck.

  • Replacing JPanels in applet

    Hi,
    I've made an applet which gets its content pane and adds a panel (lets say panel1).
    So, the code is something like this:
    public class MyApplet extends JApplet
    public void init()
    content_pane = getContentPane();
    content_pane.add( panel1, "Center" );
    Now, what I want to do is when a button on panel1 is clicked, I want panel 1 to be replaced by panel2. The listener for the button would be this applet class. So, the code would be:
    public class MyApplet extends JApplet implements ActionListener
    Panel1 p1;
    Panel2 p2;
    public void init()
    content_pane = getContentPane();
    p1 = new Panel1();
    content_pane.add( p1, "Center" );
    public void actionPerformed( ActionEvent e )
    content_pane.remove( p1 );
    p2 = new Panel2();
    content_pane.add( p2, "Center" );
    The problem is, this does not work. Panel1 and Panel2 are two totally different looking panels. On the click of the button, Panel is supposed to disappear and be replaced with Panel2. However, nothing happens.
    Could someone please let me know how I can fix this problem.
    Thanks.

    By the way, how can I format my code on these forums?

  • Can a JPanel object replace an applet?

    I know that I can insert an applet in an HTML page, and JavaScript can communicate with the applet. However, is it possible to do the same whith a JPanel object?
    Excuse the basic question.

    A panel is a light weight component, meaning it needs a top level container to hold it. An applet or frame is a top level (heavy weight) component, meaning it is it's own container. An applet can be nothing more than a thin wrapper around a panel which holds all of the other components. That's actually a good way to design it, since it lets you switch from applet to frame relatively easily, etc.

Maybe you are looking for

  • Since the Mountain Lion OS update today I've had issues with internet connection and e-mail, has anyone else?

    Since the Mountain Lion OS update today I've had issues with internet connection and e-mail, has anyone else?

  • Advanced table in advanced table- Need custom Detail table data.

    hi, I have a advanced table in table. Now for the inner detail table I have a Language column. For each row in master table I have correspoding 3 detail table records for 3 different languages. This languages are related to another master table calle

  • Regarding TDS Utility..

    Dear All, I am going to upgrade the system from SAP 2007 to 8.8 but i have doubt about how my table structure is going to upgrade & what is pre-requasite before upgrade. As per my Knowledge SAP provided some query to transfer the TDS data 2007 to 8.8

  • Unblock contact request

    I wish to unblock a contact request that has also been reported as spam. How do this please. THe contact request was from "[e-mail removed for privacy and security]", because there was no photo I blocked and reported this person by mistake as she is

  • How to find columns that do not match

    I am working on search requirement. Requirement is to search for a person. Search criteria is first name, last name and birth date. In case, when no results (i.e. result count is zero) are found, error should indicate which field or fields didnt matc