Como criar botões?!?!

8 respostas
M

Pow… to precisando criar botões em um programa, que edite uma frase.

É um programa simples… sem mta firula! O problema é q sou iniciante em JAVA, e nao manjo muito!!

Entao é isso… to precisando criar 4 botões, um para coloca a frase em Negrito, outro em Italico, outro com uma Cor qualquer… e o ultimo para Limpar opção escolhida!

Aguarda a respota o mais rapido possivel, pois o prazo de entrega está se esgotando essa semana!!

Vlwsss!!!

8 Respostas

V

Onde está sua dúvida?
O que você já fez?

F

Vc já viu algo sobre Swing?

F

Tenta Sequir este exemplo :

nele estão sendo criados dois botões:

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

public class classeJButton extends JFrame implements ActionListener
{
	JButton b1, b2 ;
	
	
	public classeJButton()
	{
		
		setTitle("Acrescentando botões");
		setBounds(200,150,400,300);
		
		
		b1 = new JButton();
		b1.setText("Sair");
		b1.setSize(100,25);
		b1.setLocation(50,200);
		b1.setBackground(Color.orange);
		b1.setForeground(Color.blue);
		b1.setFont(new Font("Sans Serif",Font.BOLD,14));
		b1.setBorder(BorderFactory.createBevelBorder(1,Color.white,Color.black));
		b1.setEnabled(true);
		b1.addActionListener(this);
		b1.setMnemonic(KeyEvent.VK_S);//igual a utilizar ALT+S
			
	    b2 = new JButton("Cadastrar");
		b2.setSize(100,25);
		b2.setLocation(200,200);
		b2.setFont(new Font("ScriptS",Font.ITALIC,12));
		b2.setBorder(BorderFactory.createLineBorder(Color.black,2));
		b2.setEnabled(true);
		b2.addActionListener(this);
		b2.setMnemonic(KeyEvent.VK_C);// igual a utilizar ALT+C
		
		getContentPane().setLayout(null);
		getContentPane().add(b1);
		getContentPane().add(b2);
    }	
	public void actionPerformed(ActionEvent e)//ações de cada Botão
  {  
   if(e.getSource()==b1) 
   {
      	System.exit(0);
   }	
   if(e.getSource()==b2) 
   {
      	JFrame Ex = new classeJPaswordListener();
      	Ex.show();   
   }	
  }	
	 
	public static void main (String arg[])
	{
		JFrame Ex = new classeJButton();
		Ex.setVisible(true);
	}
}

Espero que Ajude!

M

Pow ajudou sim… mais preciso fazer com q os botões tenham a função de editar uma frase qq q o usuario escreva!
Ai vai o q ja fiz do programa…

[b]
import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class Formata {

public static void main(String[] args) {
	JFormata janela = new JFormata();
	janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	janela.setVisible(true);

}

}
class JFormata extends JFrame implements ActionListener{

JLabel rotulo1, rotulo2;
	JTextField campo1, campoSai;
	JButton botBold, botItalic, botColor, botLimp;
	public char frase1, resultado;
	
public JFormata(){
	setTitle("Formate sua frase!!");
	setSize(400,200);
	
	Container container = getContentPane();
	GridLayout grid = new GridLayout(4,2,3,3);
	container.setLayout(grid);
	
	rotulo1 = new JLabel ("Entre com sua frase:");
	campo1 = new JTextField(4);
	
	rotulo2 = new JLabel ("Resultado da formatação");
	campoSai = new JTextField(6);
	campoSai.setEditable(false);
	
	botBold = new JButton ("NEGRITO");
	botItalic = new JButton ("ITALICO");
	botColor = new JButton ("COLORIDO");
	botLimp = new JButton ("LIMPA");
	
	
	container.add(rotulo1);
	container.add(campo1);
	container.add(rotulo2);
	container.add(campoSai);
	container.add(botBold);
	container.add(botItalic);
	container.add(botColor);
	container.add(botLimp);
	
	botBold.addActionListener(this);
	botItalic.addActionListener(this);
	botColor.addActionListener(this);
	botLimp.addActionListener(this);
		
}

public void actionPerformed(ActionEvent Evento) {
	frase1 = (char) Double.parseDouble(campo1.getText() );
	
	
	
	if(Evento.getSource() == botBold){
		botBold.setFont (new Font("Serif",Font.BOLD,14));
		campoSai.setText(Double.toString(resultado));
	}
	
	else if(Evento.getSource() == botItalic){
		botItalic.setFont(new Font ("Serif",Font.ITALIC,14));
		campoSai.setText(Double.toString(resultado));
		
	}
	
	else if(Evento.getSource() == botColor){
		botColor.setBackground(Color.red);
		campoSai.setText(Double.toString(resultado));
	}
	
	else if(Evento.getSource() == botLimp){
			campo1.setText("");
			campoSai.setText("");
	}
	
	
}

}[/b]

M

Eu to precisando atribuir aos botões funções!!!

Tipo…

botBold … tenho q atribuir a função de deixar a frase em Negrito.
botItalic … a função de deixar a frase em Italico.

tenderam?!!

Ja criei os botões… e tals, so nao consigo fazer os botões funcionarem!!!

O programa inteiro está ai em cima… quem quiser ter uma noção maior!!!

G

Olha esse exemplo do livro do Sérgio Furgeri:

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

class Exemplo0904 extends JFrame implements ActionListener, TextListener
{
        JLabel L1,L2,L3;
        JButton B1, B2, B3, B4, B5;
        JTextField T1,T2,T3;   

   public static void main(String args[])
        {
        JFrame Janela=new Exemplo0904();
        Janela.show();
        //para fechar a janela
        WindowListener x = new WindowAdapter()
         {
         public void windowClosing(WindowEvent e)
          {
           System.exit(0);
          }
         };
        Janela.addWindowListener(x);
       }

   Exemplo0904()
        {
        setTitle("Calculadora");
        setSize(350,90);
        setLocation(50,50);
        getContentPane().setBackground(new Color(150,150,150));
        getContentPane().setLayout(new GridLayout(3,4));
        L1 = new JLabel("Num.1");
        L1.setForeground(Color.black);
        L1.setFont(new Font("",Font.BOLD,14));
        L2 = new JLabel("Num.2");
        L2.setForeground(Color.black);
        L2.setFont(new Font("",Font.BOLD,14));
        L3 = new JLabel("Total");
        L3.setFont(new Font("",Font.BOLD,14));
        B1 = new JButton ("+");      B1.addActionListener(this);
        B2 = new JButton ("-");      B2.addActionListener(this);
        B3 = new JButton ("x");      B3.addActionListener(this);
        B4 = new JButton ("/");      B4.addActionListener(this);
        B5 = new JButton ("Limpar"); B5.addActionListener(this);
        B5.setBackground(Color.black);
        B5.setForeground(Color.white);
        T1 = new JTextField();
        T2 = new JTextField();
        T3 = new JTextField();
 //       T1.addTextListener(this);
        T3.setEditable(false);  //define que o textField como somente leitura
        getContentPane().add(L1);
        getContentPane().add(T1);
        getContentPane().add(B1);
        getContentPane().add(B2);
        getContentPane().add(L2);
        getContentPane().add(T2);
        getContentPane().add(B3);
        getContentPane().add(B4);
        getContentPane().add(L3);
        getContentPane().add(T3);
        getContentPane().add(B5);
        }

public void actionPerformed(ActionEvent e)
        {
        if (e.getSource()==B5)
          {
          T1.setText("");  T2.setText("");  T3.setText("");
          return;
          }
        float N1=0,N2=0,result=0;
        try
        {
         N1 = Float.parseFloat(T1.getText());
         N2 = Float.parseFloat(T2.getText());
        }
        catch (NumberFormatException erro)
           {
           T3.setText("Erro");
           return;
           }
        if (e.getSource()==B1)
                {  result = N1 + N2;  }
        if (e.getSource()==B2)
                {  result = N1 - N2;  }
        if (e.getSource()==B3)
                {  result = N1 * N2;  }
        if (e.getSource()==B4)
                {  result = N1 / N2;  }
        T3.setText(""+result);
        }
public void textValueChanged(TextEvent e)
{T3.setText("Ola");
	}
}
M

Pow… vlws pela intenção mais esse exemplo matemático eu ja tenho aki
E nao ta me ajudando mto, pois minha dúvida é justamente onde vc declara q o B1 é para o botão de SOMA… ai vc coloca o N1 + N2 … no lugar disso eu preciso colocar a formatação de uma frase, digitada pelo usuario.

public void actionPerformed(ActionEvent e) { if (e.getSource()==B5) { T1.setText(""); T2.setText(""); T3.setText(""); return; } float N1=0,N2=0,result=0; try { N1 = Float.parseFloat(T1.getText()); N2 = Float.parseFloat(T2.getText()); } catch (NumberFormatException erro) { T3.setText("Erro"); return; } if (e.getSource()==B1) [b] { B1.setFont = (new Font("", Font.BOLD,14)); } [/b] if (e.getSource()==B2) { result = N1 - N2; } if (e.getSource()==B3) { result = N1 * N2; } if (e.getSource()==B4) { result = N1 / N2; } T3.setText(""+result); } public void textValueChanged(TextEvent e) {T3.setText("Ola"); } }

S

Saudações!
Bom, eu sei que este tópico é de muito tempo atrás, mas vou postar uma solução aqui, para caso de alguém que precise passar por aqui... :D

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Formata {

	public static void main(String[] args) {
		JFormata janela = new JFormata();
		janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		janela.setVisible(true);
	}
}

class JFormata extends JFrame implements ActionListener{
	JLabel rotulo1, rotulo2;
	JTextField campo1, campoSai;
	JButton botBold, botItalic, botColor, botLimp;
	public char frase1, resultado;

	public JFormata(){
		setTitle("Formate sua frase!!");
		setSize(400,200);
		Container container = getContentPane();
		GridLayout grid = new GridLayout(4,2,3,3);
		container.setLayout(grid);
		rotulo1 = new JLabel ("Entre com sua frase:");
		campo1 = new JTextField(4);
		rotulo2 = new JLabel ("Resultado da formatação");
		campoSai = new JTextField(6);
		campoSai.setEditable(false);
		botBold = new JButton ("NEGRITO");
		botItalic = new JButton ("ITALICO");
		botColor = new JButton ("COLORIDO");
		botLimp = new JButton ("LIMPA");
		container.add(rotulo1);
		container.add(campo1);
		container.add(rotulo2);
		container.add(campoSai);
		container.add(botBold);
		container.add(botItalic);
		container.add(botColor);
		container.add(botLimp);
		botBold.addActionListener(this);
		botItalic.addActionListener(this);
		botColor.addActionListener(this);
		botLimp.addActionListener(this);
	}

	public void actionPerformed(ActionEvent Evento) {
		String texto;
		texto = campo1.getText();
		if(Evento.getSource() == botBold){
			campoSai.setText(texto);
			campoSai.setFont(new Font("Serif", Font.BOLD, 14));
		}
		if(Evento.getSource() == botItalic){
			campoSai.setText(texto);
			campoSai.setFont(new Font("Serif", Font. ITALIC, 14));
		}
		if(Evento.getSource() == botColor){
			campoSai.setText(texto);
			campoSai.setBackground(Color.red);
		}
		if(Evento.getSource() == botLimp){
			campo1.setText("");
			campoSai.setText("");
			campoSai.setBackground(Color.white);
		}
	}
}

[ ]'s.

Criado 10 de setembro de 2007
Ultima resposta 15 de jan. de 2011
Respostas 8
Participantes 6