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

Why setting the panel content in a Jframe from another panel in other Jframe is not working?

我知道我在哪里以图形方式设计面板内容以及 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. 您没有对放入 CheckListePanel 变量的 JPanel 对象执行任何操作以允许显示它。
  2. 您需要将该 JPanel 对象 添加到 顶级 window 才能显示。
  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. 或者创建一个 class 来扩展 JPanel 并以此方式创建您的 JPanel 对象。

例如,这里有一个 class 创建一个 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());
        }
    }
}

这里是一个使用上述 class/JPanel 的 class,它将 PropertyChangeListener 添加到 class,以便在进行选择时,此 [=36= 中的另一个组件],一个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();
        });
    }
}