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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

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.

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

  • How to make the swing drawings to appear in a specific jPanel?

    hi,
    I have a frame which I divided in two panels - one for the jComboBoxes/buttons and the other one for showing graphics. but the paint(Graphics g) overpaints it all =(
    how should my code look like if I want some rectangles (depending on the combo choices and on button click which means update) to appear in the second panel?
    the code's structure is like :
    import *;
    public class NewJFrame extends javax.swing.JFrame {
         private JPanel jPanel1;
    public static void main(String[] args) {
              NewJFrame inst = new NewJFrame();
              inst.setVisible(true);
         public NewJFrame() {
              super();
              initGUI();          
         public void paint(Graphics g) {
              g.fillRect (x, y, w, z)
         private void initGUI() {
              jPanel1 = new JPanel();
                   // combo boxes and buttons
                   // action listeners for them
              jPanel2 = new JPanel();
                   // the place where the rectangles should be shown
                   // and updated if combos are changed and button clicked
    }now, I wonder if anyone could possibly give me a hint how to make it correctly, because I'm really a total newb in Java and I can't find any good examples from www which I've search through for the solution.
    P.S. is there a plug-in for eclipse for visual programming of the graphics? =)
    thank You for the kindest help!
    J.M.

    You should not be mixing AWT and Swing component in
    a Swing application, so don't use a Canvas.
    If you need some custom painting then you should
    override the paintComponent() method of JComponent or
    JPanel and then add this component to the GUIwhat does mean the override the paintComponent() method of JComponent or JPanel?
    how can I add that component to the GUI?
    =)
    can you give a short code example, please! the code structure would be more than enough.
    J.

  • 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);
    }

  • Want to draw some rectangles inside a swing panel object

    HI,
    I want to draw some rectangles inside one JPanel object in swing. The JPanel object should also hold some buttons, labels, etc.. I can add simple buttons, label etc. easily to the panel object but how do I add graphics (like lines, rectangles) to it ??
    an immediate response would be highly appreciated!!

    I am not sure why you are talking about the rectangle.
    To repeat I fill in a bit of code (subject to compiler errors since I Do not have a machine where I can compile or test on at the moment):
      private class ColourCube extends JPanel 
         // The size of each rectangle with colour
         private static final int ROWS = 10;
         private static final int COLS = 10;
         // To store current selection
         private int selectedIndex[] = null;
         public ColourCube()
             addMouseListener( new MouseAdapter() {
                public void mouseReleased(MouseEvent me)
                   // Find the rectangle index by dividing
                   // x and y positions then set selectedIndex
                   // unless it is the same positions as previous
                   // then set it to be null
                   fireActionEvent();
         // needed listener methods for firing events
         public void addActionListener( ActionListener al)
            // add to list
         // remove etc....
         protected void fireActionEvent()
            // Construct action event
            // call actionPerformed( ae ) on all listeners
         public void paintComponent(Graphics g)
             // Depending on size and height of this component
             // calculate out colWidth and rowHeight
             // Loop and paint the rectangles in their different colours
             for(int i = 0; i < ROWS; i++)
                for(int j = 0; j < COLS; j++)
                   // set the colour to the graphics object here from the list of colours available
                   g.setColor( ... );
                   // Added a little bit extra to have some space between
                   // each rectangle
                   g.fillRect( i * rowHeight + 1, j * colWidth + 1, colWidth - 2, rowHeight - 2 );
             if( selectedIndex != null )
                // We have a selection, lets paint the selection
                g.setColor( Color.white ); // Selection colour
                // The index contains the row in index 0 and the col in index 1
                g.drawRect( selectedIndex[0] * rowHeight, selectedIndex[1] * colWidth, colWidth, rowHeight );
      }Lacking from the above component is lacking stuff like preferedSize.
    Now, all you do is instantiate the ColourChooser, add it to your applet iether by drag and drop if you have an WYSIWYG editor, or by hand if you are so inclined.
    Voila! A composite component appears, doing the stuff it needs to be doing.
    Regards,
    Peter Norell

  • Add JPanel on top of a JPanel?

    Hi,
    I just wonder if I can add a Jpanel on top of a Japnel since when i compile this
    it has ava.lang.NullPointerException: peer
         at sun.awt.windows.WCanvasPeer.create(Native Method)
         at sun.awt.windows.WComponentPeer.<init>(WComponentPeer.java:378)
         at sun.awt.windows.WCanvasPeer.<init>(WCanvasPeer.java:26)
    I appreciate if anyone can help
    thks
    public class MiningBox{
    public JInternalFrame newMineFrame(String name) {
    JInternalFrame internal = new JInternalFrame(name, true, true, true, true);
    internal.setSize(519, 370);
    Kmeans k_means= new Kmeans();
    internal.setContentPane(k_means);
    return internal;
    public class Kmeans extends JPanel {
    GraphCanvas graphcanvas = new GraphCanvas(this);
    Options options = new Options(this);
    Panel sbpanel = new Panel();
    Scrollbar sb = new Scrollbar(Scrollbar.HORIZONTAL, graphcanvas.n, 5, 2,
    graphcanvas.maxN);
    Scrollbar sc = new Scrollbar(Scrollbar.HORIZONTAL, graphcanvas.nbclass,
    3, 2, graphcanvas.maxC);
    Kmeans(){
    setLayout(new BorderLayout(10, 10));
    sbpanel.setLayout(new GridLayout(2, 1, 0, 5));
    sbpanel.add(sb);
    sbpanel.add(sc);
    add(BorderLayout.CENTER, graphcanvas);
    add(BorderLayout.EAST, options);
    add(BorderLayout.SOUTH, sbpanel);
    }

    Not sure exactly why you're getting this exception. You certainly can add a JPanel into another JPanel.
    However, it is generally better not to mix AWT components with Swing components. AWT components are considered 'heavy-weight' components (since they use a native peer to present themselves) while Swing components are 'light-weight' (as they paint themselves based on the look-and-feel). These two types don't usually play well together.
    If you can, I would recommend using a JScrollPane instead of the ScrollBar, and you would probably want to convert all of your other AWT components to Swing (ie. JPanel instead of Canvas, JPanel instead of Panel, etc.). Just doing that might clear up the problem.

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

  • Jcombobox Main  populating JcomboboxSub in JPanel form

    Hi,
    I have a problem and am hoping someone can help me out.
    My main problem is where I have a program that where the user
    Selects the Make of a Car
    "Choose Make", "Chevrolet", "Crysler", "Ford", "Lexus", "Toyota"
    Once a choice is made a 2nd jcombobox will populate pending on the choose of the 1st combobox choice.
    if Chevrolet "Choose Model", "Tahoe", "Suburban", "Cavalier", " Impala"
    if Crysler "Choose Model", "LaBaron", "PTCruiser", "Concord", "300"
    if Ford "Choose Model", "F150", "Bronco", "Taurus", "Explorer"
    if Lexus               "Choose Model", "L200", "L300", "L400", "L500"          
    if Toyota "Choose Model", "Camary", "Celica", "Tacoma", "4Runner"
    I am using NetBeans Swing GUI Forms, JPanel form and I am somewhat of a newbee.
    I have the 2 jcomboboxs on there with the item1,item2, item3, item4 as there strings.
    I know there is a connection button in design as to where the Combobox will have a relationship,
    but I am not sure of what to pick for my options or how to code it.
    I am thinking an actionPreformed but am not sure and I can't figure it out.
    Can someone tell me how to do this in the Design Mode?
    Thank you in advance,
    Shotgun

    This is not a NetBeans forum.
    Learn how to write your own code and don't depend on an IDE.
    You can search the forum for my "Combo Box Two" (without the spaces) example.

  • WebBrowser in JPanel or other components

    Hi,
    I need a totally free web browser like jdic. i want to integrate this browser into my swing cp0mponent like jpanel or other components.
    jdic have some problems. so if there is another web browser like jdic please give me the links.
    Thanks.
    Edited by: Ariful on Nov 11, 2007 9:20 PM

    Google it or create your own using JEditorPane but it only support HTML 3.2.

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

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

  • Advanced programmers, what is wrong with my JScrollPane?

    Hi,
    I wanted my JScrollPane to display what is drawn on my canvas (which may be large)by scrolling, but it says it doesn't need any vertical and horizontal scroll bars -- hence I can't view all of what I have drawn(a rectangle) by scrolling.Here is the code that has this effect
    import javax.swing.*;
    import java.awt.*;
    public class WhatsWrong extends JApplet{
    public void init(){
    Container appletCont = getContentPane();
    appletCont.setLayout(new BorderLayout());
    JPanel p = new JPanel();
    p.setLayout(new BorderLayout());
    p.add(new LargeCanvas(),BorderLayout.CENTER);
    int ver = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int hor = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JScrollPane jsp = new JScrollPane(p,ver,hor);
    appletCont.add(jsp,BorderLayout.CENTER);
    class LargeCanvas extends Canvas{
    public LargeCanvas(){
    super();
    setBackground(Color.white);
    public void paint(Graphics g){
    g.drawRect(50,50,700,700);
    and the html code:
    <html>
    <body>
    <applet code="WhatsWrong" width = 300 height = 250>
    </applet>
    </body>
    </html>
    What shall I do?
    Thanks in advance.

    I have just found the solution from another guy on the
    forum. It is just to use JPanel instead of Canvas and
    set the size of the panel as suggested by the first
    response.
    Thanks all for your fast response!It's also better to only use Swing components when its alread a Swing gui. JPanel is the replacement for Canvas. I remember once when I tried to use a Canvas and a JMenubar. That didn't look too good, because when I clicked on a menu, the menuitems was displayed under the canvas.

Maybe you are looking for

  • Tab Page Navigation Issue

    I've two tab page tab1 and tab2. tab2 contains three tab page tabA,tabB and tabC. In tab1 i've a commadButton. Now, if i click on this commandButton then i want to go into tabB which is inside of tab2. Please give any idea how can i navigate in tab2

  • Problem viewing data in Performance monitroing in RWB

    hi Forum, In RWB in "Performance Monitoring", When i try to display "Overview Aggregated/Overview individually/Detailed Data Aggregated/Detailed Data individually", i am unable to view data before 07-june-2010 (for information today's date is 22 June

  • Sd card not formatted after ovi maps update

    Hi. I have a problem with my N82 Series Nokia. I wanted to update my maps via Ovi Software. I do this and it worked fine. Afterwards I tried to check the new maps but only a green area appeared. I accessed the sd card in the phone and only get the me

  • 20 inch cinema display problem

    I have an anoying problem with my screen and i need a solution. There are no green colors at all so the screen has a pinkish color. It all started when i had a problem with my G4 freezing. I took it to a repair place and they totally screwed me over.

  • Asynchronous reserveFinally failed

    We have implemented an NWDI (NW2004s SP10) server, the problem we experience is caused due to an old test configuration in the begin of the project. The default trace is full of the following errors: asynchronous reserveFinally failed I know where th