Duvida com Eventos

Boa noite, estou com uma duvida simples…para criar um Listener tenho que criar uma classe, ok…mas eu queria saber se posso criar uma classe com o nome Eventos e dentro dela criar varios metodos que serao os listeners.

Por exemplo, tenho 5 botoes, cada um faz uma ação, entao soh preciso criar uma classe com metodos por exemplo pra fechar um Frame, pra fazer uma conta, pra minimizar, pra deixar fullscreen, pra limpar a tela…entenderam? entao, é possivel fazer isso ou tenho que criar uma classe pra cada ação?

Vc pode fazer algo assim:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Tela extends JFrame {

	JButton b1 = new JButton("B1");
	JButton b2 = new JButton("B2");
	JButton b3 = new JButton("B3");
	JButton b4 = new JButton("B4");
	
	public Tela(){
		this.ajustaTela();
		this.addElementos();
		this.addActionListeners();
	}
	
	private void addActionListeners() {
		b1.addActionListener(new ActionListener() {			
			@Override
			public void actionPerformed(ActionEvent e) {
				exibeMensagem("Você clicou no botão b1");
			}
		});
		
		b2.addActionListener(new ActionListener() {			
			@Override
			public void actionPerformed(ActionEvent e) {
				exibeMensagem("Você clicou no botão b2");
			}
		});
		
		b3.addActionListener(new ActionListener() {			
			@Override
			public void actionPerformed(ActionEvent e) {
				exibeMensagem("Você clicou no botão b3");
			}
		});
		
		b4.addActionListener(new ActionListener() {			
			@Override
			public void actionPerformed(ActionEvent e) {
				exibeMensagem("Saindo");
				dispose();
			}
		});
		
	}

	private void exibeMensagem(String texto){
		//Ao invés de vc chamar esse método no seu action listener, vc pode chamar
		//métodos de outras classes.
		JOptionPane.showMessageDialog(this, texto);
	}


	private void addElementos(){
		getContentPane().add(b1);
		getContentPane().add(b2);
		getContentPane().add(b3);
		getContentPane().add(b4);
	}
	
	private void ajustaTela(){
		setSize(200, 200);
		setLocationRelativeTo(null);
		setLayout(new GridLayout(2, 2));
		setResizable(false);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setVisible(true);
	}
	
	public static void main(String[] args) {
		new Tela();
	}
}

Eu sempre crio os actionlisteners na mesma classe em que está o meu botão, se precisar chamo um método dentro deles ou até mesmo um método que esteja em outra classe.

Foi isso que vc queria saber?

Parece bom deste jeito também, mas então não é possivel fazer isto em outra classe?

Para mim vai ficar mais bagunçado, pq vc terá de fazer essa classe implementar a interface ActionListener, criar um método e enchê-lo de if para testar qual botão seu foi clicado, exatamente o mesmo se sua tela implementasse o ActionListener.

Seu código vai ficar meio espagueti (cheio de if) e vc vai criar uma classe para ter, basicamente, um método.

Mas sim, se mesmo assim vc quiser fazer é possível embora “feio”. :lol:

Infelizmente, não possível escolher outro método além do actionPerformed para responder aos comandos que você criar.

Olá

veja se é isso que queres implementar, segue um exemplo que envolve tres classes:

====================================================
1 - Action Support

package javaapplication1;

import java.awt.event.*;
import java.util.*;

/**
 *
 * Author Information
 * @author Jailes M S Pantoja
 * @email jailes.pantoja@gmail.com
 * @locale Brazil - Para - Belem
 *
 */

public class ActionSupport implements ActionListener {
    
    //java.awt.Window
    private Class<?> window;
    
    /**
     * Creates a new instance of ActionSupport
     */
    public ActionSupport(Class<?> window)  {
        this.window = window;
    }

    private List<ActionListener> listeners = new ArrayList<ActionListener>();
    
    public void addActionListener(ActionListener listener) {
        listeners.add(listener);
    }
    
    public void removeActionListener(ActionListener listener) {
        listeners.remove(listener);
    }
    
    public void fireActionEvent(ActionEvent e) {
        Iterator<ActionListener> it = listeners.iterator();
        while (it.hasNext()) {
            ActionListener listener = it.next();
            listener.actionPerformed(new ActionEvent(window, ActionEvent.ACTION_PERFORMED, e.getActionCommand()));
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        fireActionEvent(e);
    }
    
}

=======================================================
2 - O Controle


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

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *
 * @author Jailes Pantoja
 * @mail jailes.pantoja@gmail.com
 * 
 */
public class ClasseControle implements ActionListener {

    private static JFrameView mainView = null;

    public ClasseControle() {
        mainView = new JFrameView();
        mainView.pack();
        mainView.setTitle("Teste de MVC");
        mainView.setVisible(true);
        mainView.addActionListener(this);
        mainView.setResizable(true);    
    }

    
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("cmdUm")){
            mainView.setTexto("Butao Um Acionado");
        }
        if(e.getActionCommand().equals("cmdDois")){
            mainView.setTexto("Butao Dois Acionado");                        
        }
        if(e.getActionCommand().equals("cmdTres")){
            mainView.setTexto("Butao Tres Acionado");            
        }
    }

    public static void main(String[] vars) {
        ClasseControle classeControle = new ClasseControle();
    }
}

=============================================================
3 - O View


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

/*
 * JFrameView.java
 *
 * Created on Mar 8, 2011, 8:44:40 PM
 */

package javaapplication1;

import java.awt.event.ActionListener;

/**
 *
 * @author Jailes Pantoja
 * @mail jailes.pantoja@gmail.com
 * 
 */
public class JFrameView extends javax.swing.JFrame {

    ActionSupport actionSupport = new ActionSupport(JFrameView.class);
    
    public void addActionListener(ActionListener listener){
        actionSupport.addActionListener(listener);
    }
    
    /** Creates new form JFrameView */
    public JFrameView() {
        initComponents();
        
        jButton1.setActionCommand("cmdUm");
        jButton1.addActionListener(actionSupport);
        
        jButton2.setActionCommand("cmdDois");
        jButton2.addActionListener(actionSupport);
        
        jButton3.setActionCommand("cmdTres");
        jButton3.addActionListener(actionSupport);
        
    }

    public void setTexto(String texto){
        jTextField1.setText(texto);
    }
    
    /** 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() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");

        jButton2.setText("jButton2");

        jButton3.setText("jButton3");

        jTextField1.setText("jTextField1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap())
        );

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

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration

}

Lembrando que é apenas um esboço.

Seliaj, o seu modo parece resolver meu problema, mas é muito avançado para o meu nível, kkkkk…

Axo que vou tentar fazer tudo na mesma classe msm, porem vou encontrar o problema de n poder criar um metodo pra cada Listener, pois devem ter o nome actionPerformed, estou pensando num jeito

Guilherme,

Tudo na mesma classe, com cada button acionado um metodo especifico:


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

/*
 * JFrameView.java
 *
 * Created on Mar 8, 2011, 8:44:40 PM
 */

package javaapplication1;

import java.awt.event.ActionListener;

/**
 *
 * @author Jailes Pantoja
 * @mail jailes.pantoja@gmail.com
 * 
 */
public class JFrameView extends javax.swing.JFrame {

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

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameView().setVisible(true);
            }
        });
    }
    
    
    /** 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() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

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

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

        jTextField1.setText("jTextField1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 169, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap())
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        jTextField1.setText("Button One Acionado - Metodo 1");
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        jTextField1.setText("Button One Acionado - Metodo 2");
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        jTextField1.setText("Button One Acionado - Metodo 3");
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration

}

Ats,

Jailes

Jailes obrigado, agora posso resolver meu problema, agradeço a todos que colaboraram!

Agora eu possuo um outro problema, eu fiz um evento que por sua vez acaba adicionando um outro botão na tela, e ao clicar nesse botao ele deve realizar um verificação(if/else) com uma variavel que esta dentro do primeiro evento, porem nao consigo realizar, quando cito a variavel dentro desse otro evento, o NetBeans me da um erro:

[color=red]local variable idade is accessed from within inner class; needs to be declared final[/color]

Desculpem-me, ja consegui resolver este erro anterior, más agora infelizmente tenho outro, eu estou pegando dados Strings de 4 JTextFields, e um botao tem que pegar esses dados e mostrar em algum campo, tentei mostar em um JTextField ampliado, mas fica tudo escrito na mesma linhas, msm usando o \n…alguem poderia me dizer qual o componente mais apropriado para realizar essa exposição dos dados?

JTextArea

Entao, tentei usar, e ta dando varios erros, eu executo, e da erro…da uma olhad anos erros:

[color=blue]run:[/color]
[color=red]Exception in thread “AWT-EventQueue-0” java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at SwingApp.Form$1.actionPerformed(Form.java:59)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6267)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6032)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)[/color]
[color=green]CONSTRUÍDO COM SUCESSO (tempo total: 7 segundos)[/color]

OBS: estou usando esse comando para transformar um valor String em Int, sera que é isso?

int idade=Integer.parseInt(campo[2].getText());

Percebi que se eu comento essa linha, tudo funciona normalmente…alias, esta linha esta dentro de um evento, onde faz algumas verificações, e acaba por pegar um valor String numa area de texto e converte-lo em numerico(onde uso esse comando).