Código que demonstra a criação de interface gráfica,mostra a utilização da classe DecimalFormat e exibe o tratamento de eventos:
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import java.awt.Color;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusListener;
import java.awt.event.FocusEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.DecimalFormat;
/**
*Classe que demonstra o uso de swings,converte um numero para decimal
*e demonstra a utilização de eventos em Java–Focus Lost e ActionPerformed
*/
public class AplicacaoFrame extends JFrame implements ActionListener {
private JLabel l1;
private JTextField t1;
private JButton b1,b2;
private DecimalFormat formatador = new DecimalFormat(“R$0.00”);
public AplicacaoFrame(){
//Configurando o JFrame
setTitle(“Formatador de Decimais”);
setLocation(180,210);
setSize(295,105);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setForeground(Color.green);
setDefaultLookAndFeelDecorated(true);
getContentPane().setLayout(null);
//Instanciando e Configurando a JLabel
l1 = new JLabel(“Valor”);
l1.setBounds(50,10,65,25);
//Instanciando e Configurando o JTextField
t1 = new JTextField();
t1.setBounds(115,10,65,25);
t1.addFocusListener(new FocusAdapter(){
public void focusLost(FocusEvent e){
try {
t1.setText(formatador.format(Integer.parseInt(t1.getText())));
}
catch(NumberFormatException numEx){
JOptionPane.showMessageDialog(null,""+numEx.getMessage(),“Erro”,JOptionPane.ERROR_MESSAGE);
t1.setText("");
t1.requestFocus();
}
}});
//Instanciando e Configurando o JButton
b1 = new JButton(“Botão”);
b1.setBounds(40,40,95,25);
b1.addActionListener(this);
b2=new JButton(“Limpar”);
b2.setBounds(135,40,95,25);
b2.addActionListener(this);
getContentPane().add(l1);
getContentPane().add(t1);
getContentPane().add(b1);
getContentPane().add(b2);
}
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(b1)){
if(t1.getText().equals("")){
JOptionPane.showMessageDialog(null,“Campo em Branco”,“ERRO”,JOptionPane.ERROR_MESSAGE);
t1.requestFocus();
}
else{
JOptionPane.showMessageDialog(null,“Valor Convertido para decimal”,“Informando”,JOptionPane.INFORMATION_MESSAGE);
}
}
if(e.getSource().equals(b2)){
t1.setText("");
}
}
public static void main(String args[]){
AplicacaoFrame aplicacaoFrame=new AplicacaoFrame();
aplicacaoFrame.setVisible(true);