import javax.swing.*; import java.awt.*; import java.awt.event.*;
public class JavaTeste extends JFrame {
private JLabel texto[]; public JTextField campo[]; private JButton testar[];
private int total = 5;
public JavaTeste() { super("Formulario"); this.setSize(350,170); this.setLocation(50, 100);
Container ct = this.getContentPane(); ct.setLayout(null);
texto = new JLabel[total+1]; campo = new JTextField[total+1]; testar = new JButton[total+1];
for(int i=0; i <=total; i++){ try { texto[i] = new JLabel(); texto[i].setText("campo "+i+": "); texto[i].setBounds(0,20*i,60,20); ct.add(texto[i]);
campo[i] = new JTextField(); campo[i].setText("teste "+i); campo[i].setBounds(61,20*i,150,20); ct.add(campo[i]);
testar[i] = new JButton(); testar[i].setText("testar"); testar[i].setBounds(212,20*i,100,20); ct.add(testar[i]); } catch (NullPointerException erro) {/* Erro desapareceu */} }
Image Icone = Toolkit.getDefaultToolkit().getImage("icon.gif"); setIconImage(Icone);
this.setVisible(true); for(int i=0; i <=total; i++){ try { testar[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JButton botaoPressionado = (JButton) e.getSource(); String item = ""; for(int i = 0; i <= total; i++){ if(botaoPressionado == testar[i]){ item = campo[i].getText(); } } JOptionPane.showMessageDialog(null, item);
}}); } catch (NullPointerException erro) {/* Erro desapareceu */} } this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); }});
} public static void main(String[] args) { new JavaTeste(); } } |