简体   繁体   English

无法更改Java Swing CardLayout中的卡

[英]Not able to changes cards in Java Swing CardLayout

I have an class named AddAccounts 我有一个名为AddAccounts的类

class AddAccounts extends JPanel {

    JPanel panelCont; //Panel deck
    CardLayout cl;

    public AddAccounts() {

             panelCont=new JPanel();
             cl = new CardLayout();
             panelCont.setLayout(cl);//set Panel Layout to CardLayout
            setPreferredSize(new Dimension(1013, 513));//Set Default Size

    /* Add Panels to the main window or integrate the panels*/
            panelCont.add(new Panel1(), "1");
            panelCont.add(new Panel2(),"2");
            panelCont.add(new Panel3(),"3");
            cl.show(panelCont, "1");
            add(panelCont);    
        }

    public void goNext() {
       cl.show(panelCont, "2");
      // cl.nxet(panelCont);
        System.out.println("method called"); //for debugging purpose
         }

    public void showFirstPanel(){
        cl.show(panelCont, "1");
         }  
}

And two external(separate files) class named Panel1 and panel2() . 还有两个名为Panel1和panel2()的外部(独立文件)类。 and I wanna change the cards( from panel1 to panel2 ) when the button is being pressed in panel1 that's why i create above listed method called goNext(), but the problem is I'm not able to change the cards. 当我在panel1中按下按钮时,我想更改卡( 从panel1到panel2 ),这就是为什么我创建上面列出的名为goNext()的方法的原因,但是问题是我无法更改卡。 here how i try to call the goNext()method in Panel1 在这里,我如何试图调用在Panel1的的goNext()方法

@Override
public void actionPerformed(ActionEvent event) {
    if (event.getSource() == nextBtn) {
        setMainCategory((String)mainCat.getSelectedItem());
    }
}
public void setMainCategory(String mainCategory){
    this.mainCategory=mainCategory;
   new AddAccounts().goNext();
    //System.out.println("From set Method: "+this.mainCategory);
}

Everything works fine, the System.out.println("method called"); 一切正常, System.out.println(“ method named”); //for debugging purpose get executed and printed on console window but the panels(card)are not changed. //出于调试目的,执行并打印在控制台窗口上,但面板(卡)未更改。 please help.. how to make it work. 请帮助..如何使其工作。

@haraldK what you said is absolutely correct. @haraldK你说的是绝对正确的。 but it doesn't help me, concept i trying to implement is I have an JFrame named mainPanel and in mainPanel i have a JSplitPanel JSplitPane rootPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, userPanel, mainContentPane); 但这对我没有帮助,我要实现的概念是我有一个名为mainPanel的JFrame,在mainPanel中我有一个JSplitPanel JSplitPane rootPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, userPanel, mainContentPane); mainContentPane consists mainContentPane包含

JTabbedPane mainContentPane = new JTabbedPane(); mainContentPane.setPreferredSize(new Dimension(900, 550)); mainContentPane.setTabPlacement(JTabbedPane.TOP); mainContentPane.addTab("Your Database", new UserRecords()); mainContentPane.addTab("Add Accounts", new AddAccounts());//here is the AddAccounts JPanel mainContentPane.addTab("Update Existing Data", new EditRecords()); mainContentPane.setSelectedIndex(1);

i place buttons on Panel1,Panel2 rather than placing buttons on parent Frame AddAccounts. 我将按钮放在Panel1,Panel2上,而不是将按钮放在父框架AddAccounts上。 Here the method goNext is belong to AddAccounts and i want to access it to change the panel(from 1 to 2) when the button is pressed in Panel1. 这里的goNext方法属于AddAccounts,当我在Panel1中按下按钮时,我想访问它以更改面板(从1到2)。 i cannot call the goNext() method directly,since it is the method of AddAccounts class not Panel1. 我不能直接调用goNext()方法,因为它是AddAccounts类的方法而不是Panel1。 and new AddAccounts().goNext(); new AddAccounts().goNext(); doesn't help Directory Structure: mypackage -UserPanel(MainPanelFrame,userPanelJPanel, mainContentPaneTabbedPane) -AddAccounts (goNext()) -Panel1 (nextBtn) -Panel2 (nextBtn) 不能帮助目录结构:mypackage -UserPanel(MainPanelFrame,userPanelJPanel,mainContentPaneTabbedPane)-AddAccounts(goNext())-Panel1(nextBtn)-Panel2(nextBtn)

The problem is not the CardLayout code, rather it is in the setMainCategory method: 问题在于CardLayout代码,而在于setMainCategory方法中:

new AddAccounts().goNext();

Here you create a new instance of the AddAccounts every time the method is invoked. 在这里,每次调用该方法时,都会创建一个AddAccounts的新实例。 The panel is flipped on this instance (that is why you see the debug output), but the component is never added to a parent (like a JFrame or JPanel ) and thus never shown. 该面板在该实例上处于翻转状态(这就是为什么您看到调试输出的原因),但是该组件从未添加到父级(例如JFrameJPanel ),因此从不显示。 After the method exits, the resulting component is just thrown away. 方法退出后,将只丢弃结果组件。

Instead, you need to add one single AddAccounts to a parent component, and in the setMainCategory method, you just invoke goNext() on this instance. 相反,您需要将一个AddAccounts添加到父组件,并且在setMainCategory方法中,只需在此实例上调用goNext()

Here's a fully functional program that demonstrates everything I tried to explain above: 这是一个功能齐全的程序,演示了我在上面试图解释的所有内容:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class CardLayoutTest {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("CardLayoutTest");
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

                frame.getContentPane().add(new AddAccounts()); // Create single instance here
                frame.pack();
                frame.setLocationRelativeTo(null);

                frame.setVisible(true);
            }
        });
    }

    static class AddAccounts extends JPanel {

        JPanel panelCont; //Panel deck
        CardLayout cl;

        public AddAccounts() {
            panelCont = new JPanel();
            cl = new CardLayout();
            panelCont.setLayout(cl);//set Panel Layout to CardLayout

            /* Add Panels to the main window or integrate the panels*/
            panelCont.add(new ColorPanel(Color.ORANGE), "1");
            panelCont.add(new ColorPanel(Color.GRAY), "2");
            panelCont.add(new ColorPanel(Color.DARK_GRAY), "3");

            cl.show(panelCont, "1");

            add(panelCont);

            add(new JButton(new AbstractAction("First") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    showFirstPanel();
                }
            }));
            add(new JButton(new AbstractAction("Next") {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // This method is similar to your setMainCategory
                    goNext();
                }
            }));
        }

        public void goNext() {
//            cl.show(panelCont, "2");
            cl.next(panelCont); // Allows iterating through all panels
            System.out.println("method called"); //for debugging purpose
        }

        public void showFirstPanel() {
            cl.show(panelCont, "1");
        }

        /// Dummy class to show that page flipping works
        private class ColorPanel extends JPanel {
            public ColorPanel(Color background) {
                setOpaque(true);
                setBackground(background);
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 200);
            }
        }
    }
}

Just tried to create a functional example. 刚刚尝试创建一个功能示例。 Hope this will help you. 希望这会帮助你。

import java.awt.CardLayout;

/**
 *
 * @author user
 */
public class MyFrame extends javax.swing.JFrame {

    /**
     * Creates new form MyFrame
     */
    public MyFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        deck = new javax.swing.JPanel();
        firstCard = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        secondCard = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        deck.setLayout(new java.awt.CardLayout());

        firstCard.setLayout(new java.awt.BorderLayout());

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("First");
        firstCard.add(jLabel1, java.awt.BorderLayout.CENTER);

        deck.add(firstCard, "card2");

        secondCard.setLayout(new java.awt.BorderLayout());

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Second");
        secondCard.add(jLabel2, java.awt.BorderLayout.CENTER);

        deck.add(secondCard, "card3");

        getContentPane().add(deck, java.awt.BorderLayout.CENTER);

        jButton1.setLabel("Go Next");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, java.awt.BorderLayout.PAGE_START);

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        ((CardLayout)deck.getLayout()).next(deck);
    }                                        

    /**
     * @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(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

    // Variables declaration - do not modify                     
    private javax.swing.JPanel deck;
    private javax.swing.JPanel firstCard;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel secondCard;
    // End of variables declaration                   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM