Como adiciono Evento no Botão

10 respostas
S

Criei um codigo q ao clicar no “botao1” ele ira chamar uma função q terá como parametro uma String???

public class Servidor extends JFrame{
	private JTextField enter;
	
	private JTextArea display;
	ObjectOutputStream output;
	ObjectInputStream input;
	
	public Servidor(){
		super("Servidor");

		enter= new JTextField();
		enter.setEnabled(false);
		
		
		c.add(enter, BorderLayout.SOUTH);
		
		display=new JTextArea();
		display.setToolTipText("Mostra Status e Chat");
		c.add(new JScrollPane(display), BorderLayout.CENTER);
		
		JButton botao1=new JButton("Enviar");
		c.add(botao1, BorderLayout.EAST);
		botao1.setToolTipText("Enviar a Menssagem");
		botao1.setMnemonic('E');
//o codigo não está completo...

não seicomo programarei o evento do Botao
alguem pode me ajudar?

10 Respostas

M

simples! :D

botao1.addActionListener(

   new ActionListener() {

      public void actionPerformed( ActionEvent e )
      {
         // é aqui q tu vai colocar o codigo q 
         // teu botao deve executar
      }
   }
);

...mais duvidas, post it!

M

ahhh! e importe o pacote java.awt.event.* !!

S
"matheus":
simples! :D
botao1.addActionListener(

   new ActionListener() {

      public void actionPerformed( ActionEvent e )
      {
         // é aqui q tu vai colocar o codigo q 
         // teu botao deve executar
      }
   }
);

...mais duvidas, post it!

e os import???????????

tem algum implemet?

é só isso?

Coloquei quero chamar a função
"SendData (String)"
que a mesma pega um campo de texto e envia...mas ta dando erro...
pensei q eu estavaprogramando o evento errado... mas usei o seu e deu a mesma coisa

M

qual é o erro q esta dando? :?:

F

SIm simples como falow o nosso amigo Mateus
vc apenas tenque no inicio da Classe fazer os imports

import javax.swing.<em>;//caso seja swing o botão

import java.awt.</em>;

import java.awt.event.*;

vc ja está implementando o botão e sua ação no actionListener como está acima, basta colocar o que ele vai fazer no espaço como está acima!!!

Opa tem um errinho ai faz assim:

meuBotao.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e){
					//ação aqui 

				}}
			);

Só um erro de sintaxe fechando o botão antes , o código acima deve funcionar

fala se funcionou

S

Valeu!!!
ficou numa boa!!!

S

Gostaria de saber como faço para pegar um texto através de um clique de um botão…

esse texo esta dentro de uma “JTextArea” darei um ckique no botão e ele pegara esse texto e passara de parametro para uma funçao

Um abraço para todos

M

use o método mouseClicked() ... bem, achei um ex com este evento, segue ai:

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

public class MouseDetails extends JFrame {

   private int x, y;

   public MouseDetails()
   {
      super( "Mouse clicks and buttons" );

      addMouseListener( new Handler() );

      setSize( 350, 150 );
      setVisible( true );
   }

   public void paint( Graphics g )
   {
      super.paint( g );

      g.drawString( "Clicked @ [" + x + ", " + y + "]", x, y );
   }

   public static void main( String args[] )
   {
      MouseDetails win = new MouseDetails();

      win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

   private class Handler extends MouseAdapter {

      public void mouseClicked( MouseEvent e )
      {
         x = e.getX();
         y = e.getY();

         String title = "Clicked " + e.getClickCount() + " time(s)";

         if ( e.isMetaDown() )
            title += " with right mouse button";

         else if ( e.isAltDown() )
            title += " with center mouse button";

         else title+= " with left mouse button ";

         setTitle( title );
         repaint();
      }

   }

}
R

Tenta usar o método getSelectedText() de JTextArea… retorna o texto selecionado.

M

opa, então vai outro exemplo (do livro dos Deitel), onde tu seleciona o texto, e clica num botão pra copiar este texto selecionado:

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

public class TextAreaDemo extends JFrame {

   private JTextArea area1, area2;
   private JButton botao;

   public TextAreaDemo()
   {
      super( "TextArea Demo" );

      Box box = Box.createHorizontalBox();

      String str = "Temptations - My Girl\n\n" +
                   "Ive got sunshine on a cloudy day.\n" +
                   "When its cold outside Ive got the month of May.\n" +
                   "I guess youd say\n" +
                   "What can make me feel this way?\n" +
                   "Talkin about my girl (my girl).\n" +
                   "\n\n" +
                   "Ive got so much honey the bees envy me.\n"+
                   "Ive got a sweeter song than the birds in the trees\n"+
                   "I guess youd say\n"+
                   "What can make me feel this way?\n"+
                   "My girl...\n"+
                   "Talkin about my girl (my girl).";

      area1 = new JTextArea( str, 10, 15 );
      box.add( new JScrollPane( area1 ) );

      botao = new JButton( "Copy >>" );
      botao.addActionListener(

         new ActionListener() {

            public void actionPerformed( ActionEvent e )
            {
               area2.setText( area1.getSelectedText() );
            }

         }

      );

      box.add( botao );

      area2 = new JTextArea( 10, 15 );
      area2.setEditable( false );
      box.add( new JScrollPane( area2 ) );

      Container container = getContentPane();
      container.add( box );
    

      setSize( 425, 200 );
      setVisible( true );

   }

   public static void main( String args[] )
   {
      TextAreaDemo win = new TextAreaDemo();

      win.setExtendedState(MAXIMIZED_BOTH);

      win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }

}
Criado 2 de maio de 2004
Ultima resposta 8 de mai. de 2004
Respostas 10
Participantes 4