0

I get an idea where i design panel contents graphically and all it's possible methods in a jframe then i use that panel in another jframe where all i need to do is to create instance of the other frame and get it panel and affect it to a panel in my current jframe.

here is the code that i tried the first jframe that contains my designed panel model :

  package chemsou;

  import java.util.Hashtable;
  import javax.swing.JCheckBox;
  import javax.swing.JPanel;

  public class CheckListe extends javax.swing.JFrame {

   /**
    * Creates new form NewJFrame
    */
   Hashtable<String, JCheckBox> model = new Hashtable<>();
   public JPanel getPanel(){
      return jPanel1;
   }

   public CheckListe(String[] list) {
      initComponents();
      jPanel1.setLayout(new java.awt.GridLayout(0, 1, 0, 4));
      for (String element : list) {

          model.put(element, new JCheckBox(element));
          jPanel1.add(model.get(element));
      }

   }

   public CheckListe() {

       initComponents();

   }
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

    jPanel1 = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setLayout(new java.awt.GridLayout(0, 1, 0, 4));

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 388, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 535, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
       //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
       /* If Nimbus (introduced in Java SE 6) is not available, stay with the  default look and feel.
      * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
       */
       try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
               if ("Nimbus".equals(info.getName())) {
                  javax.swing.UIManager.setLookAndFeel(info.getClassName());
                  break;
               }
           }
       } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CheckListe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
           java.util.logging.Logger.getLogger(CheckListe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       } catch (IllegalAccessException ex) {
           java.util.logging.Logger.getLogger(CheckListe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
          java.util.logging.Logger.getLogger(CheckListe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       }
       //</editor-fold>
       //</editor-fold>

       /* Create and display the form */
       java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
               new CheckListe().setVisible(true);
          }
       });
   }

   // Variables declaration - do not modify                     
   private javax.swing.JPanel jPanel1;
   // End of variables declaration                   
}

my jframe where i call the first frame and i set the panel to the modeled one :

private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // TODO add your handling code here:
    String[] list =new String[]{"e1","e2","e3"};
    CheckListe checkListe = new CheckListe(list);
   // CheckListePanel.setLayout(checkListe.getPanel().getLayout());
    CheckListePanel = checkListe.getPanel();

    checkListe.setVisible( true );
    CheckListePanel.setVisible(true);
    CheckListePanel.setSize(100, 500);
    CheckListePanel.revalidate();
    CheckListePanel.repaint();
    System.out.println("done");
}                                             

When I run the code I can see that the other jframe contains the designed panel but the caller jframe dont do anything

what I m supposed to do ?

  • 1
    Okay, I'm confused. Are you trying to set the properties of the first frame? Are you trying to re-use the panel in another frame? – MadProgrammer Mar 25 '16 at 01:32
  • See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Mar 25 '16 at 02:55
  • @HovercraftFullOfEels what i really want is let say like : you panel i want you to be like the panel that i designed in this frame. then the panel says : it s ok i will transforme my self and i will be like and act like the panel that you want . so in the end i see that my panel have what i designed graphically . how to do it? i m trying to find it . – Mohammed Housseyn Taleb Mar 25 '16 at 20:12

1 Answers1

1
  1. You're not doing anything with the JPanel object that you're putting into the CheckListePanel variable that will allow it to be displayed.
  2. You need to add that JPanel object to a top-level window for it to show.
  3. Also, you can add a component to only one container, you know. It can only be visible once.
  4. Why create a JFrame with the first code if you're only using it to create a JPanel??
  5. You ask, "is there a way to make a copy a the panel that i designed" -- Sure. Rather than create it as you're doing, create the JPanel in a factory method of some sort. e.g., public JPanel createMyPanel() { /* creational code goes in here */ }
  6. Or create a class that extends JPanel and create your JPanel object this way.

For example, here's a class that creates a JPanel that displays a List of Strings as a column of JRadioButtons, and then that notifies any observers of a selection:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.*;
import javax.swing.border.Border;

@SuppressWarnings("serial")
public class BunchARadios extends JPanel {
    private static final int GAP = 5;
    public static final String SELECTION = "selection";
    private ButtonGroup buttonGroup = new ButtonGroup();

    public BunchARadios(String title, List<String> radioLabels) {
        Border innerBorder = BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP);
        Border outerBorder = BorderFactory.createTitledBorder(title);
        Border border = BorderFactory.createCompoundBorder(outerBorder, innerBorder);
        setBorder(border);
        setLayout(new GridLayout(0, 1, GAP, GAP));

        RButtonListener rButtonListener = new RButtonListener();
        for (String radioLabel : radioLabels) {
            JRadioButton radioButton = new JRadioButton(radioLabel);
            radioButton.setActionCommand(radioLabel);
            add(radioButton);
            buttonGroup.add(radioButton);
            radioButton.addActionListener(rButtonListener);
        }        
    }

    public String getSelection() {
        ButtonModel model = buttonGroup.getSelection();
        if (model == null) {
            return null; // throw exception?
        } else {
            return model.getActionCommand();
        }
    }

    private class RButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            firePropertyChange(SELECTION, null, e.getActionCommand());
        }
    }
}

And here's a class that uses the above class/JPanel, that adds a PropertyChangeListener to the class so that when a selection is made, another component in this class, a JList, can display the new selection:

import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class TestBunchARadios extends JPanel {
    private static final int GAP = 5;
    private String title = "Weekdays";
    private List<String> labels = Arrays.asList(new String[] { "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday" });
    private BunchARadios bunchARadios = new BunchARadios(title, labels);
    private DefaultListModel<String> listModel = new DefaultListModel<>();
    private JList<String> selectionList = new JList<>(listModel);

    public TestBunchARadios() {
        selectionList.setPrototypeCellValue("xxxxxxxxxxxxxxxxx");
        selectionList.setVisibleRowCount(5);
        JScrollPane scrollPane = new JScrollPane(selectionList);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        setLayout(new BorderLayout(GAP, GAP));
        add(bunchARadios, BorderLayout.CENTER);
        add(scrollPane, BorderLayout.LINE_END);

        bunchARadios.addPropertyChangeListener(BunchARadios.SELECTION,
                new BunchARadiosChangeListener());
    }

    private class BunchARadiosChangeListener implements PropertyChangeListener {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            String selection = (String) evt.getNewValue();
            listModel.addElement(selection);
        }
    }

    private static void createAndShowGui() {
        TestBunchARadios mainPanel = new TestBunchARadios();

        JFrame frame = new JFrame("TestBunchARadios");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 3
    *"Why create a JFrame with the first code if you're only using it to create a JPanel??"* - Now, that's the question that needs to be answered :P – MadProgrammer Mar 25 '16 at 01:33
  • @Hovercraft Full Of Eels is there a way to make a copy a the panel that i designed – Mohammed Housseyn Taleb Mar 25 '16 at 01:36
  • @MadProgrammer as i mentioned is only an idea that crossed my mind before going to sleep at 2 am – Mohammed Housseyn Taleb Mar 25 '16 at 01:38
  • @MohammedHousseynTaleb: to be blunt, it seems to be a bad idea, and if I were you, I'd discard it. – Hovercraft Full Of Eels Mar 25 '16 at 01:38
  • 3
    @MohammedHousseynTaleb "is there a way to make a copy a the panel that i designed"* - Don't wrap it in a `JFrame`, simply extend straight from `JPanel` and place you design straight on top it, when needed, create an instance and add it to some container which is visible on the screen – MadProgrammer Mar 25 '16 at 01:40
  • @HovercraftFullOfEels what i really imagined is a frame full of panels designed graphically that i call . – Mohammed Housseyn Taleb Mar 25 '16 at 01:40
  • @MohammedHousseynTaleb: then do that. Create either factory methods or classes that extend JPanel and create these classes. I do this all the time. – Hovercraft Full Of Eels Mar 25 '16 at 01:44
  • @MohammedHousseynTaleb: please see edit to answer with example code that demonstrates exactly what MadProgrammer and I are discussing. Please ask if any questions. – Hovercraft Full Of Eels Mar 25 '16 at 02:16
  • @MadProgrammer Also Hovercraft thanks for your help , by reading the code i understand that i can reshape[recode] any swing object by extending it and reforming it by adding what I really needs : I have to care about styling (borders ...) , events or properties. – Mohammed Housseyn Taleb Mar 25 '16 at 19:59