Precedente Indice Successiva

Esempio con JLabel e JTextField

  • Scriveremo nel file MyFrameField.java il codice:
    package framefieldtest

    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.JLabel;
    import javax.swing.JTextField;

    public class MyFrameField extends JFrame implements ActionListener {

    private JButton closeButton;
    private JButton helloButton;
    private JTextField nameField;
    private JLabel replay;

    private static final long serialVersionUID = 1L;

    public MyFrameField () {
    setTitle("Finestra con form di prova");

    closeButton = new JButton("Ok");
    helloButton = new JButton ("Saluti...");
    nameField = new JTextField();
    replay = new JLabel("Attendo");

    closeButton.addActionListener(this);
    helloButton.addActionListener(this);

    setLayout(new GridLayout(5,1));
    add(new JLabel("Scrivi il tuo nome"));
    add(nameField);
    add(replay);
    add(helloButton);
    add(closeButton);
    pack();
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
    if (evt.getSource() == closeButton) {
    dispose();
    } else if (evt.getSource() == helloButton) {
    replay.setText("Ciao " + nameField.getText());
    }
    }

    }
  • Ancora una volta il main cambia solo nel nome della classe e quindi non lo riscrivo.
  • Proviamo questi due componenti. Scriviamo un programma che:
    • Presenti all'utente un campo per inserire il proprio nome, con una label che indichi cosa deve fare l'utnete
    • Presenti un bottone "OK" che Scrive "Ciao " seguito dal nome in un'altra label
    • Presenti un bottone per terminare
© Ing. Stefano Salvi - released under FDL licence

Valid XHTML 1.0! Valid CSS!