Precedente Indice Successiva

Un esempio con liste e box di spunta - il codice

  • Nel file MyFrameCheckAndList.java inseriremo il codice:
    package framecheckandlisttest;

    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;

    public class MyFrameCheckAndList extends JFrame implements ActionListener {

    private JButton closeButton;
    private JButton helloButton;
    private JTextField nameField;
    private JLabel replay;
    private JCheckBox confidenziale;
    private JComboBox sesso;

    private static final long serialVersionUID = 1L;

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

    closeButton = new JButton("Ok");
    helloButton = new JButton ("Saluti...");
    nameField = new JTextField();
    nameField.setColumns(10);
    replay = new JLabel("Attendo");
    confidenziale = new JCheckBox();
    sesso = new JComboBox();
    sesso.addItem("Maschio");
    sesso.addItem("Femmina");

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

    setLayout(new BorderLayout());
    JPanel p = new JPanel();
    p.setLayout(new FlowLayout());
    p.add(new JLabel("Scrivi il tuo nome"));
    p.add(nameField);
    add(p, BorderLayout.NORTH);

    add(replay, BorderLayout.CENTER);

    JPanel pannelloInferiore = new JPanel();
    pannelloInferiore.setLayout(new GridLayout(3,1));
    p = new JPanel();
    p.setLayout(new FlowLayout());
    p.add(confidenziale);
    p.add(new JLabel("Tono confidenziale"));
    pannelloInferiore.add(p, BorderLayout.NORTH);
    pannelloInferiore.add(sesso);
    p = new JPanel();
    p.setLayout(new FlowLayout());
    p.add(helloButton);
    p.add(closeButton);
    pannelloInferiore.add(p);
    add(pannelloInferiore, BorderLayout.SOUTH);
    pack();
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
    if (evt.getSource() == closeButton) {
    dispose();
    } else if (evt.getSource() == helloButton) {
    String saluto="";
    switch (sesso.getSelectedIndex()) {
    case 0: // Maschio
    if (confidenziale.isSelected()) {
    saluto="Ciao caro ";
    } else {
    saluto = "Buon giorno Signor ";
    }
    break;
    default:
    if (confidenziale.isSelected()) {
    saluto="Ciao cara ";
    } else {
    saluto = "Buon giorno Signora ";
    }
    break;
    }
    replay.setText(saluto + nameField.getText());
    }
    }
    }
  • Come al solito nel main va solo cambiato il nome della classe, quindi non lo riporto.
© Ing. Stefano Salvi - released under FDL licence

Valid XHTML 1.0! Valid CSS!