[GELÖST] Problem mit ActionListener

Allgemeine Themen rund um Java

Moderator: wegus

Antworten
themader
Beiträge: 3
Registriert: 20.02.2013, 10:26

[GELÖST] Problem mit ActionListener

Beitrag von themader » 20.02.2013, 10:39

Hallo,

ich hoffe ich bin hier im richtigen Bereich.

Nun zu meinem Problem. Ich habe eine Klasse names Control und ein jFrame MainWindow. Auf dem MainWindow befindet sich ein jButton "btn", den Listener will ich aber im Control haben.

Daher habe ich einen Listener definiert:

Code: Alles auswählen

        class BtnListener implements ActionListener {
		public void actionPerformed(java.awt.event.ActionEvent e) {
			_MainWindow.createPage();
		}
	}
Und rufe im Konstruktor des Control die Methode:

Code: Alles auswählen

        public void addDefaultListener() {
            _MainWindow.setBtnListener(new BtnListener());
        }
auf.

Die Methode sieht im MainWindow so aus:

Code: Alles auswählen

    public void setBtnListener(ActionListener al) {
        this.btn.addActionListener(al);
    }
Das funktioniert aber nicht, wenn ich den btn drücke passiert nichts. Habe im Control auch schon per getBtn() versucht direkt den Listener zu übergeben, aber funktioniert ebenfalls nicht.

Wo liegt mein Denkfehler, ich komme gerade einfach nicht weiter. :(

MfG
Mader
Zuletzt geändert von themader am 20.02.2013, 12:40, insgesamt 1-mal geändert.

Benutzeravatar
Olek77
Beiträge: 669
Registriert: 21.03.2009, 13:09

Re: Problem mit ActionListener

Beitrag von Olek77 » 20.02.2013, 10:58

Hallo,

Poste doch mal den ganzen Code.

Hast du eine Instanz von MainFrame in deinem Control?
Zum Debuggen hilft mir oft als erstes Ausgaben auf die Konsole mit

Code: Alles auswählen

System.out.println("");
So siehst du ob deine actionPerformed Methode überhaupt aufgerufen wird.
Professioneller geht das natürlich wenn du mit dem Debugger arbeitest ( der Knopf neben dem normalen Run-Knopf ).

Viele Grüße,

Olek
- Netbeans Certified Associate -

themader
Beiträge: 3
Registriert: 20.02.2013, 10:26

Re: Problem mit ActionListener

Beitrag von themader » 20.02.2013, 11:36

Also hier der ganze Code von Control:

Code: Alles auswählen

package composer;

import java.awt.event.ActionListener;

/**
 *
 * @author Madaa
 */
public class control {

    // Variables declaration
	private view _view;
	private model _model;
        private mainW _mainW;
    // End of variables declaration
	
    //Konstruktor
	public control() {
		this._view = new view();
		this._model = new model();
                this._mainW = new mainW();
                this.addDefaultListener();
	}//END_Konstruktor
   
    //initListener	
        public void addDefaultListener() {
            _mainW.setBtnListener(new BtnListener());
        }//END_addDefaultListener
    //end of initListener     

    //functions
        public void showMainWindow() {
		this._view.showMainWindow(_mainW);
	}//END_showMainWindow
    //end of functions
        
    //Listener
        class BtnListener implements ActionListener {
            @Override
		public void actionPerformed(java.awt.event.ActionEvent e) {
                        System.out.println("BtnListener wird aufgerufen");
			_mainW.createPage();
		}
	}//END_BtnListener
    //End of Listener
        
}//END_control

Und hier mainW, hatte es im startpost MainWindow genannt zum besseren Verständnis.

Code: Alles auswählen

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package composer;


import java.awt.event.ActionListener;
import java.util.ArrayList;
/**
 *
 * @author Madaa
 */
public class mainW extends javax.swing.JFrame {
    /**
     * Creates new form mainW
     */
    
    public mainW() {
        initComponents();
        setLocationRelativeTo(null);
        createPage();
    }
    
    /**
     * 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() {

        backgroundPanel = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        interactionPanel = new javax.swing.JPanel();
        newPagebtn = new javax.swing.JButton();
        delPageBtn = new javax.swing.JButton();
        creatModulBtn = new javax.swing.JButton();
        btn = new javax.swing.JButton();
        jPanel8 = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        pagePanel = new javax.swing.JPanel();
        btnPanel = new javax.swing.JPanel();
        dynNewPageBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setMinimumSize(new java.awt.Dimension(1109, 635));
        setPreferredSize(new java.awt.Dimension(1109, 635));

        backgroundPanel.setBackground(new java.awt.Color(255, 255, 255));

        jTabbedPane1.setBackground(new java.awt.Color(255, 255, 255));
        jTabbedPane1.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
        jTabbedPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTabbedPane1.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        jTabbedPane1.setFocusable(false);

        interactionPanel.setBackground(new java.awt.Color(255, 255, 255));
        interactionPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
        interactionPanel.setFocusable(false);

        newPagebtn.setBackground(new java.awt.Color(255, 255, 255));
        newPagebtn.setText("new page");
        newPagebtn.setBorderPainted(false);
        newPagebtn.setContentAreaFilled(false);
        newPagebtn.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        newPagebtn.setRequestFocusEnabled(false);
        newPagebtn.setRolloverEnabled(false);
        newPagebtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newPagebtnActionPerformed(evt);
            }
        });

        delPageBtn.setBackground(new java.awt.Color(255, 255, 255));
        delPageBtn.setText("delete page");
        delPageBtn.setBorderPainted(false);
        delPageBtn.setContentAreaFilled(false);
        delPageBtn.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        delPageBtn.setFocusable(false);
        delPageBtn.setRequestFocusEnabled(false);
        delPageBtn.setRolloverEnabled(false);
        delPageBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delPageBtnActionPerformed(evt);
            }
        });

        creatModulBtn.setBackground(new java.awt.Color(255, 255, 255));
        creatModulBtn.setText("dummy modul");
        creatModulBtn.setBorderPainted(false);
        creatModulBtn.setContentAreaFilled(false);
        creatModulBtn.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        creatModulBtn.setFocusable(false);
        creatModulBtn.setRequestFocusEnabled(false);
        creatModulBtn.setRolloverEnabled(false);
        creatModulBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                creatModulBtnActionPerformed(evt);
            }
        });

        btn.setText("testbtn");

        javax.swing.GroupLayout interactionPanelLayout = new javax.swing.GroupLayout(interactionPanel);
        interactionPanel.setLayout(interactionPanelLayout);
        interactionPanelLayout.setHorizontalGroup(
            interactionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(interactionPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(interactionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(newPagebtn)
                    .addComponent(delPageBtn))
                .addGap(43, 43, 43)
                .addComponent(creatModulBtn)
                .addGap(169, 169, 169)
                .addComponent(btn)
                .addContainerGap(605, Short.MAX_VALUE))
        );
        interactionPanelLayout.setVerticalGroup(
            interactionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(interactionPanelLayout.createSequentialGroup()
                .addGroup(interactionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(interactionPanelLayout.createSequentialGroup()
                        .addGroup(interactionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(newPagebtn)
                            .addComponent(creatModulBtn))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(delPageBtn))
                    .addGroup(interactionPanelLayout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(btn)))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("interaction", interactionPanel);

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1084, Short.MAX_VALUE)
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 69, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("media modules", jPanel8);

        jPanel9.setAlignmentX(0.0F);
        jPanel9.setAlignmentY(0.0F);

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1084, Short.MAX_VALUE)
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 69, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("structure models", jPanel9);

        jPanel6.setAlignmentX(0.0F);
        jPanel6.setAlignmentY(0.0F);
        jPanel6.setPreferredSize(new java.awt.Dimension(938, 70));

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1084, Short.MAX_VALUE)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 69, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("component", null, jPanel6, "");

        pagePanel.setBackground(new java.awt.Color(255, 255, 255));
        pagePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
        pagePanel.setToolTipText("");
        pagePanel.setAutoscrolls(true);
        pagePanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        pagePanel.setMaximumSize(new java.awt.Dimension(720, 250));
        pagePanel.setName(""); // NOI18N
        pagePanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 10, 10));

        btnPanel.setBackground(new java.awt.Color(255, 255, 255));
        btnPanel.setMinimumSize(new java.awt.Dimension(50, 355));
        btnPanel.setPreferredSize(new java.awt.Dimension(50, 355));

        dynNewPageBtn.setText("+");
        dynNewPageBtn.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        dynNewPageBtn.setContentAreaFilled(false);
        dynNewPageBtn.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        dynNewPageBtn.setMaximumSize(new java.awt.Dimension(20, 20));
        dynNewPageBtn.setMinimumSize(new java.awt.Dimension(15, 15));
        dynNewPageBtn.setPreferredSize(new java.awt.Dimension(17, 17));
        dynNewPageBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dynNewPageBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout btnPanelLayout = new javax.swing.GroupLayout(btnPanel);
        btnPanel.setLayout(btnPanelLayout);
        btnPanelLayout.setHorizontalGroup(
            btnPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(btnPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(dynNewPageBtn, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                .addContainerGap())
        );
        btnPanelLayout.setVerticalGroup(
            btnPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(btnPanelLayout.createSequentialGroup()
                .addGap(155, 155, 155)
                .addComponent(dynNewPageBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(170, Short.MAX_VALUE))
        );

        pagePanel.add(btnPanel);

        jScrollPane1.setViewportView(pagePanel);
        pagePanel.getAccessibleContext().setAccessibleName("");

        javax.swing.GroupLayout backgroundPanelLayout = new javax.swing.GroupLayout(backgroundPanel);
        backgroundPanel.setLayout(backgroundPanelLayout);
        backgroundPanelLayout.setHorizontalGroup(
            backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(backgroundPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTabbedPane1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        backgroundPanelLayout.setVerticalGroup(
            backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(backgroundPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
                .addContainerGap())
        );

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

        pack();
    }// </editor-fold>
    
    //ActionPerformed
    private void creatModulBtnActionPerformed(java.awt.event.ActionEvent evt) {                                              
        Modul _modulPanel = new Modul();        
        findCurPage().addModul(_modulPanel);
    }                                             

    private void delPageBtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
        pagePanel.remove(findCurPage());
        pagePanel.revalidate();
        pagePanel.repaint();
    }                                          

    private void newPagebtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
        createPage();
    }                                          

    private void dynNewPageBtnActionPerformed(java.awt.event.ActionEvent evt) {                                              
        createPage();
    }                                             
    //End of ActionPerformed    
    
    /**
     * @param args the command line arguments
     */
    public static void main() {
        /* 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(mainW.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(mainW.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(mainW.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(mainW.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

    // Variables declaration - do not modify
    private javax.swing.JPanel backgroundPanel;
    private javax.swing.JButton btn;
    private javax.swing.JPanel btnPanel;
    private javax.swing.JButton creatModulBtn;
    private javax.swing.JButton delPageBtn;
    private javax.swing.JButton dynNewPageBtn;
    private javax.swing.JPanel interactionPanel;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JButton newPagebtn;
    private javax.swing.JPanel pagePanel;
    // End of variables declaration
    //own variables dec
    public int njpID=0; 
    public ArrayList<Page> nJPlist = new ArrayList<>();
    // End of own variables dec
    
    //Functions
    public final void createPage() {
        pagePanel.remove(btnPanel);
        Page newpanel = new Page(njpID);
        njpID++;
        nJPlist.add(newpanel);
        pagePanel.add(newpanel);
        pagePanel.add(btnPanel);
        pagePanel.revalidate();
    }//END_createPage
    
    Page findCurPage() {
        int i=0;
        while(nJPlist.get(i).hasFocus()==false) {
            i++;
        } 
        return nJPlist.get(i);
    }//END_findCurPage
    
    public javax.swing.JButton getButton()  {
        return btn;
    }//END_getButton  
    //End of functions
    
    //setListener
    public void setBtnListener(ActionListener al) {
        this.btn.addActionListener(al);
    }//END_setBtnListener
    //End of setListener
}

Ich hatte auch schon nen Systemout Anfangs drin gehabt, aber der Listener reagiert scheinbar nicht auf Klicks. :/

themader
Beiträge: 3
Registriert: 20.02.2013, 10:26

Re: Problem mit ActionListener

Beitrag von themader » 20.02.2013, 12:39

Konnte das Problem lösen, im Main von mainW wird ein neues mainW erzeugt und auch nur dieses wird angezeigt. Man muss das main ersetzten durch eine einefache Funktion die setVisible(true) macht.

In meinem Fall habe ich den Code vom Main verwendet beim erzeugen des mainW im Control, keine Ahnung ob das Notwendig ist!

Antworten