单击按钮/ Java后创建JPanel

时间:2014-11-15 15:07:49

标签: java jpanel

我的项目有问题。我想在点击按钮后在我的框架中创建新面板。这是代码的一部分:

private class ComponentListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(newGameItem)) 
        {
            System.out.println("dasda");
            gamePanel = new GamePanel();
            cont.add(gamePanel);

        }
        if (e.getSource().equals(stopItem)) {
            gamePanel.stopGame();
        }
    }
}

GamePanel gamePanel;

Container cont = this.getContentPane();

当我点击按钮时,我在控制台中看到了文字,当我正在使用此面板启动项目时,一切正常。 我想这个问题很简单,但我无法弄清楚发生了什么:(。


我看到“dasda”所以这意味着方法actionPerformed正常工作。 miniwolf我应该在哪里调用重绘?在actionPerformed?

2 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案。我应该在gamePanel.revalidate()中添加actionPerformed。谢谢你的帮助

答案 1 :(得分:0)

我必须刷新此主题,因为我在JFrame表单中更改JPanel时遇到问题。 当我点击按钮我想要更改面板但我看不到它,但是当我创建JFrame(java类)并自己编写代码时,一切都没问题。

这是我制作的JFrame(java类)的代码。

 public class main extends JFrame
{
    public main()
    {
        frameSettings();
        this.getContentPane().add(panel1);
        panel1.add(button);
        panel1.setBackground(Color.red);
        button.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e)
        {
            gamePanel = new GamePanel();
            container.add(gamePanel);
            gamePanel.startGame();
            gamePanel.revalidate();
            gamePanel.requestFocus();
        }
    });
}
private void frameSettings() {
    int szer = Toolkit.getDefaultToolkit().getScreenSize().width;
    int wys = Toolkit.getDefaultToolkit().getScreenSize().height;
    this.setTitle("Pong");
    this.setSize(700, 600);
    this.setResizable(false);
    int szerRamki = this.getSize().width;
    int wysRamki = this.getSize().height;
    this.setDefaultCloseOperation(3);
    this.setLocation((szer - szerRamki) / 2, (wys - wysRamki) / 2);

}
JPanel panel1 = new JPanel();
JButton button = new JButton();
GamePanel gamePanel;
Container container = this.getContentPane();
public static void main(String args[])
{

    java.awt.EventQueue.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            new main().setVisible(true);
        }
    });
}

}

这是来自JFrame表单的代码

public class MainFrame extends javax.swing.JFrame
{

/**
 * Creates new form MainFrame
 */
public MainFrame()
{

    initComponents();
    frameSettings();

}

private void frameSettings()
{
    int szer = Toolkit.getDefaultToolkit().getScreenSize().width;
    int wys = Toolkit.getDefaultToolkit().getScreenSize().height;
    this.setTitle("Pong");
    this.setSize(700, 600);
    this.setResizable(false);
    int szerRamki = this.getSize().width;
    int wysRamki = this.getSize().height;
    this.setDefaultCloseOperation(3);
    this.setLocation((szer - szerRamki) / 2, (wys - wysRamki) / 2);

}

/**
 * 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()
{

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    jMenuItem1 = new javax.swing.JMenuItem();
    jMenuItem2 = new javax.swing.JMenuItem();
    jMenuItem3 = new javax.swing.JMenuItem();
    jMenu2 = new javax.swing.JMenu();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setBackground(new java.awt.Color(0, 0, 0));

    jLabel1.setFont(new java.awt.Font("Monospaced", 3, 160)); // NOI18N
    jLabel1.setForeground(new java.awt.Color(51, 255, 255));
    jLabel1.setText("Pong");

    jLabel2.setFont(new java.awt.Font("Monospaced", 3, 48)); // NOI18N
    jLabel2.setForeground(new java.awt.Color(102, 255, 0));
    jLabel2.setText("Nowa Gra");

    jLabel3.setFont(new java.awt.Font("Monospaced", 3, 48)); // NOI18N
    jLabel3.setForeground(new java.awt.Color(102, 255, 0));
    jLabel3.setText("Ranking");

    jLabel4.setFont(new java.awt.Font("Monospaced", 3, 48)); // NOI18N
    jLabel4.setForeground(new java.awt.Color(102, 255, 0));
    jLabel4.setText("Wyjście");

    jLabel5.setFont(new java.awt.Font("Monospaced", 3, 18)); // NOI18N
    jLabel5.setForeground(new java.awt.Color(153, 255, 0));
    jLabel5.setText("Najlepszy gracz:");

    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener()
    {
        public void actionPerformed(java.awt.event.ActionEvent evt)
        {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(237, 237, 237)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel4)
                        .addComponent(jLabel3)))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(227, 227, 227)
                    .addComponent(jLabel2)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(148, 148, 148)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 131, Short.MAX_VALUE)
            .addComponent(jButton1)
            .addGap(102, 102, 102))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(57, 57, 57)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jLabel1)
                .addComponent(jButton1))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel2)
            .addGap(18, 18, 18)
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel4)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel5))
    );

    jMenu1.setText("File");

    jMenuItem1.setText("Nowa Gra");
    jMenu1.add(jMenuItem1);

    jMenuItem2.setText("jMenuItem2");
    jMenu1.add(jMenuItem2);

    jMenuItem3.setText("jMenuItem3");
    jMenu1.add(jMenuItem3);

    jMenuBar1.add(jMenu1);

    jMenu2.setText("Edit");
    jMenuBar1.add(jMenu2);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)                                         
{                                             
    System.out.println("askdalk");
            gamePanel = new GamePanel();
            container.add(gamePanel);
            gamePanel.startGame();
            gamePanel.revalidate();
            gamePanel.requestFocus();
}                                        

/**
 * @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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex)
    {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex)
    {
        java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex)
    {
        java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
        }
    });
}
private Container container = this.getContentPane();
// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JPanel jPanel1;
// End of variables declaration                   
private GamePanel gamePanel;

}