为什么在Jframe中从其他Jframe中的另一个面板设置面板内容不起作用?

时间:2016-03-25 01:21:28

标签: java swing jpanel

我知道我在哪里以图形方式设计面板内容以及它在jframe中的所有可能方法然后我在另一个jframe中使用该面板,我需要做的就是创建另一帧的实例并获取它面板并将其影响到当前jframe中的面板。

这是我试过的代码 第一个包含我设计的面板模型的jframe:

  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                   
}

我的jframe,我调用第一帧,然后将面板设置为建模面板:

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

当我运行代码时,我可以看到另一个jframe包含设计的面板,但调用者jframe不做任何事情

我应该做什么?

1 个答案:

答案 0 :(得分:1)

  1. 您没有对要放入CheckListePanel变量的JPanel对象执行任何操作,以允许显示它。
  2. 您需要将JPanel对象添加到顶级窗口,以便显示。
  3. 此外,您知道,您只能将一个组件添加到一个容器中。它只能看一次。
  4. 如果您只使用它来创建JPanel,为什么要使用第一个代码创建JFrame?
  5. 你问,"is there a way to make a copy a the panel that i designed" - 当然。而不是像你一样创建它,而是在某种工厂方法中创建JPanel。例如,public JPanel createMyPanel() { /* creational code goes in here */ }
  6. 或者创建一个扩展JPanel并以这种方式创建JPanel对象的类。
  7. 例如,这是一个创建JPanel的类,它将一个字符串列表显示为一个JRadioButtons列,然后通知任何观察者选择:

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

    这是一个使用上面的类/ JPanel的类,它将一个PropertyChangeListener添加到类中,以便在进行选择时,此类中的另一个组件JList可以显示新的选择:

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