Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- public class ComboBoxes {
- // ------------------------------ FIELDS ------------------------------
- private ActionListener automobilListener = new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- Automobil automobil = (Automobil) ((JComboBox) e.getSource()).getSelectedItem();
- if (automobil != null)
- comboBox2.setModel(new DefaultComboBoxModel<>(db.getModelos(automobil.id)));
- }
- };
- private ListCellRenderer automobilRenderer = new DefaultListCellRenderer() {
- @Override
- public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
- super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
- setText(((Automobil) value).nombre);
- return this;
- }
- };
- private JComboBox<Automobil> comboBox1;
- private JComboBox<String> comboBox2;
- private JPanel contentPane;
- private Db db;
- private JPanel init() {
- db = new Db();
- comboBox1.setModel(new DefaultComboBoxModel<>(db.getAutomobiles()));
- comboBox1.addActionListener(automobilListener);
- comboBox1.setRenderer(automobilRenderer);
- comboBox2.setModel(new DefaultComboBoxModel<>(db.getModelos(1)));
- return contentPane;
- }
- class Automobil {
- int id;
- String nombre;
- Automobil(int id, String nombre) {
- this.id = id;
- this.nombre = nombre;
- }
- }
- class Db {
- Automobil[] CARS = {
- new Automobil(1, "FORD"),
- new Automobil(2, "HONDA"),
- new Automobil(3, "TOYOTA")
- };
- Automobil[] getAutomobiles() {
- return CARS;
- }
- String[] getModelos(int autoId) {
- if (autoId == 1) {
- return new String[]{"TAURUS"};
- } else if (autoId == 2) {
- return new String[]{"ACCORD"};
- } else if (autoId == 3) {
- return new String[]{"PRIUS"};
- } else {
- return new String[0];
- }
- }
- }
- // --------------------------- main() method ---------------------------
- public static void main(String[] args) {
- JFrame frame = new JFrame("<class name>");
- frame.setContentPane(new ComboBoxes().init());
- frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- frame.setMinimumSize(new Dimension(400, 200));
- frame.pack();
- frame.setVisible(true);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement