从外部更改和更新 JPanel 组件,从 JFrame 不工作,Swing

2022-01-24 00:00:00 java swing jpanel jframe

I was working with JPanel (Changing its component), but I want to change it from External JFrame.

Sorry, I make this code with Netbeans (I know it put some stuff not needed for this question) and try to clean editing it, because the real code it is more large

Here the code of the JPanel, with name 'MyPanel'.

    public class MyPanel extends javax.swing.JPanel {

      private javax.swing.JButton filling = new javax.swing.JButton();
      private javax.swing.JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
      private javax.swing.JTable myTable = new javax.swing.JTable();

      private final javax.swing.table.DefaultTableModel INITIAL_TABLE_MODEL = new javax.swing.table.DefaultTableModel(
          new Object[][]{},
          new String[]{"Text", "Integer"}
      );

      public MyPanel() {
        initComponents();
        //callFilling(); // INNER CALL!
      }

      private void initComponents() {
        filling.setText("filling");
        filling.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent evt) {
            fillingActionPerformed(evt);
          }
        });

        myTable.setModel(new javax.swing.table.DefaultTableModel(
          new Object [][] { },
          new String [] { "Text", "Integer" }
       ) {
          Class[] types = new Class [] {
            java.lang.String.class, java.lang.Integer.class
          };

          public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
          }
        });
        jScrollPane1.setViewportView(myTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
          layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(filling)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
          .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
          layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(filling)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
      }                   

      public void callFilling() {
        myTable.setModel(INITIAL_TABLE_MODEL);
        INITIAL_TABLE_MODEL.setRowCount(0);
        ((javax.swing.table.DefaultTableModel) myTable.getModel()).setRowCount(0);
        Integer numberRows = new java.util.Random().nextInt((10 - 2) + 1) + 2;
        for (int i = 0; i < numberRows; i++) {
          Integer number = new java.util.Random().nextInt();
          ((javax.swing.table.DefaultTableModel) myTable.getModel()).addRow(
              new Object[]{
                number.toString(), number
              });
        }
        this.revalidate();
        this.repaint();
      }

      private void fillingActionPerformed(java.awt.event.ActionEvent evt) {                                        
        callFilling();
      }
    }

The Frame!!!

public class MainFrame extends javax.swing.JFrame {

  private javax.swing.JTabbedPane myTabbed = new javax.swing.JTabbedPane();

  public MainFrame() {
    initComponents();
    MyPanel myPanel = addNewTab();
    myPanel.callFilling(); //OUTER CALL!
    myPanel.revalidate();
    myPanel.repaint();
    addNewTab();
  }

  private MyPanel addNewTab() {
    int idx = myTabbed.getTabCount();
    String title = "myTabbed: " + idx + " ";
    MyPanel myPanel = new MyPanel();
    myTabbed.insertTab(title, null, new MyPanel(), null, idx);
    return myPanel;
  }

  private void initComponents() {
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    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(myTabbed, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(myTabbed, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)
        .addContainerGap())
    );

    pack();
  }

  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(() -> {
      new MainFrame().setVisible(true);
    });
  }
}

When the callFilling(); is do it from JPanel (review INNER CALL) works!, but from JFrame (review //OUTER CALL) doesn't work!

Reviewing this question Update content of JPanel on a frame on button click in another frame The proposed revalidate(); repaint(); code I used, but is not working.

How solve this?

解决方案

MyPanel myPanel = addNewTab();
myPanel.callFilling(); //OUTER CALL!
myPanel.revalidate();
myPanel.repaint();
addNewTab();

Not sure what you are trying to do.

You create a MyPanel object and invoke callFilling() on it to set the values in the TableModel. But you never actually add the panel to the frame.

You only need to invoke revalidate() and repaint() when you add components to a visible panel.

Then you invoke addNewTab() which does:

MyPanel myPanel = new MyPanel();
myTabbed.insertTab(title, null, new MyPanel(), null, idx);
return myPanel;

Again, this doesn't make any sense you create 2 MyPanel objects. You add one object to a tabbed pane, but then you return the second MyPanel object.

So you have created 3 MyPanel objects.

I really am not sure what you are trying to do. I don't know if you are trying to add a panel to the frame, or a panel to the tabbed pane, so I can't really make a specific suggestion.

In any case you need to structure you code so that only on MyObject object is created and you need to add that panel to either the tabbed pane or the frame, but not both.

相关文章