How popular is Jcombobox with an array of strings?

Asked

Viewed 106 times

0

I have a class that inherits from JFrame and has a JComboBox comboBoxPorta = new JComboBox();.

I would like to popular this combo with the serial ports. I have a function in another class to print this procedure.

 public void popularComboPorta() {
     String[] portNames = SerialPortList.getPortNames();
     for (String portName : portNames) {
         //System.out.println(portName);
         JOptionPane.showMessageDialog(null, "Inicio Impressao" + portName);

    }

Using existing examples, you have to create a function in the form class by returning to JComboBox, but of error saying that the class is not solved. It seems so simple but I’m standing by it.

1 answer

0

Can use:

comboBoxPorta.setModel(new DefaultComboBoxModel(SerialPortList.getPortNames()));

Example:

import java.awt.BorderLayout;
import javax.swing.*;

public class Panel extends JFrame {

    String []ports;

    public Panel(String []ports){
        initializeComponents();
        this.ports = ports;
    }

    private void initializeComponents(){
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);

        JComboBox combobox = new JComboBox<String>();
        JButton button = new JButton("Popular Combobox");
        button.addActionListener(listener -> {
            combobox.setModel(new DefaultComboBoxModel(this.ports));
        });

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(button, BorderLayout.PAGE_START);
        panel.add(combobox, BorderLayout.PAGE_END);
        this.add(panel);
        this.pack();
    }
}

Running:

public class Main {
    public static void main(String... args) {
        String [] ports = {"A", "B", "C"};
        new Panel(ports).setVisible(true);
    }
}

exemplo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.