简体   繁体   English

如何在 JCombobox 中使用其他 class 中的 Object

[英]How to use Object from other class in a JCombobox

I'm new at Java and trying to learn so my apologies if it seems obvious to you:(我是 Java 的新人,正在努力学习,如果您觉得这很明显,我深表歉意:(

I'm trying to import an ArrayList from another class to my JCombobox.我正在尝试将 ArrayList 从另一个 class 导入到我的 JCombobox。 When I import the arraylist in the Combobox from his own class it works but when I call it in the other class it doesn't work I don't know why.当我从他自己的 class 导入 Combobox 中的 arraylist 时,它可以工作,但是当我在另一个 class 中调用它时,它不起作用我不知道为什么。 I had extended the class btw and the list isn't private.我已经扩展了 class 顺便说一下,该列表不是私人的。

My arraylist is empty at first so maybe this is the problem?我的 arraylist 一开始是空的,所以这可能是问题所在? Is it possible to save the new arraylist at the end of the execution of my frame?是否可以在我的框架执行结束时保存新的 arraylist? This is the code where the Arraylist is located:这是 Arraylist 所在的代码:

public class MainForm {
private JTextField textField1;
private JButton resetButton;
private JButton saveButton;
private JTable tablePort;
public JSpinner spinner1;
private JButton updateButton;
private JPanel jpan;
private JScrollPane porttabl;
private JSplitPane rootPanel;
private JComboBox comboBox1;
public List<Port> ports;
private tablePort model;
private  SpinnerModel limit;
private Port selectport;
private int selectedIndex;

public List<Port> getPorts() {
    return ports;
}

public List<Port> setPorts(List<Port> a){
    this.ports = a;
    return ports;
}
public MainForm() {
    ports = new ArrayList<Port>();
    model = new tablePort(ports);
    tablePort.setModel(model);
    limit = new SpinnerNumberModel(0,0,10,1);
    spinner1.setModel(limit);


    saveButton.addActionListener(e-> {
        if(textField1.getText().equals("")){
            JOptionPane.showMessageDialog(null,"Il faut rentrer un nom pour votre bâteau","Erreur",0);
        }else {
            int p = (int) spinner1.getValue();
            Port a = new Port(textField1, 0, 0, spinner1);
            ports.add(a);
            model.fireTableDataChanged();
            comboBox1.setModel(new DefaultComboBoxModel(ports.toArray()));
            setPorts(ports);
            System.out.println(ports);
            System.out.println(model);
            System.out.println(a.getNom());
            System.out.println(a.quais.nbQuai);
            clear();
        }
    });

And here where i want my list:在这里我想要我的清单:

public class TablBateau extends MainForm {
private JPanel panel1;
private JTextField textField1;
private JComboBox comboBox1;
private JCheckBox enMerCheckBox;
private JSplitPane rootPanel;
private JComboBox comboBox2;
private JTable table1;
private JButton button1;
private JButton resetButton;
private JButton button2;
private JButton button3;
public List<Bateau> bateaux;

public TablBateau() {
    button1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

        }
    });
    comboBox1.setModel(new DefaultComboBoxModel(ports.toArray()));
}

The key to your problem is to pass the information to where it is needed by using composition.您的问题的关键是通过使用组合将信息传递到需要的地方。 Objects that need to extract information from another object hold variables of those objects and then call methods on them:需要从另一个 object 中提取信息的对象持有这些对象的变量,然后调用它们的方法:

public class TablBateau extends MainForm {
    private JPanel panel1;
    private JTextField textField1;
    private JComboBox comboBox1;
    private JCheckBox enMerCheckBox;
    private JSplitPane rootPanel;
    private JComboBox comboBox2;
    private JTable table1;
    private JButton button1;
    private JButton resetButton;
    private JButton button2;
    private JButton button3;
    public List<Bateau> bateaux;

    private MainForm mainForm;  // add this

    // pass the MainForm into this clas
    public TablBateau(MainForm mainForm) {
        this.mainForm = mainForm;
        
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

            }
        });
        comboBox1.setModel(new DefaultComboBoxModel(mainForm.getPorts().toArray()));
    }

You pass the currently displayed MainForm instance into your TablBateau instance when you create the latter, by passing it in as a parameter:在创建后者时,将当前显示的 MainForm 实例传递给 TablBateau 实例,方法是将其作为参数传入:

public class MainForm {

    someListener() {
        TablBateau tablBateau = new TablBateau(this);
    }
}   

For example,例如,

class PassingInfo: class 传递信息:

  • Has the main method that starts the Swing GUI具有启动 Swing GUI 的主要方法
  • Creates a MainForm object, puts it into a JFrame, and displays it创建MainForm object,放入JFrame,显示

class Port class 端口

  • Dummy class to represent a Port object.虚拟 class 代表端口 object。
  • This is obviously not the Port class that you are using (but I don't have your code, so I have to use this placeholder class instead)这显然不是您正在使用的端口 class(但我没有您的代码,因此我必须改用此占位符 class)

class MainForm class 主窗体

  • Extends JPanel so that it can be placed into a JFrame or JDialog, or another JPanel, wherever it is needed扩展 JPanel,以便可以将其放入 JFrame 或 JDialog 或其他 JPanel 中,只要需要
  • Holds a List<Port> ports variable that is filled with data from a dummy String array持有一个List<Port> ports变量,该变量填充了来自虚拟字符串数组的数据
  • JButton that displays a modal JDialog that holds the TablBateau JPanel显示包含 TablBateau JPanel 的模态 JDialog 的 JButton
  • Passes the ports list into TablBateau whenever the latter is displayed (not done in constructor in case the ports Port list is changed)每当显示后者时,将端口列表传递到 TablBateau(如果更改端口列表,则不在构造函数中完成)
  • Displays the above in a modal JDialog so that we will know when a selection is made.在模态 JDialog 中显示以上内容,以便我们知道何时进行了选择。
  • After a selection is made (code resumes from past the JDialog being made visible), extract the selection from the TablBateau instance and display in this object's JTextField.做出选择后(代码从过去的 JDialog 恢复可见),从 TablBateau 实例中提取选择并显示在此对象的 JTextField 中。

class TablBateau class TablBateau

  • Extends JPanel so it can be placed into a JFrame or JDialog or other JPanel,...扩展 JPanel,以便它可以放入 JFrame 或 JDialog 或其他 JPanel,...
  • Displays a JComboBox of Ports显示端口的 JComboBox
  • Has a setPorts(...) method that fills the JComboBox.具有填充 JComboBox 的setPorts(...)方法。
  • ActionListener added to combobox that will dispose of the window that contains this JPanel.添加到 combobox 的 ActionListener 将处理包含此 JPanel 的 window。
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class PassingInfo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MainForm mainPanel = new MainForm();
            
            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        });
    }

}
class MainForm extends JPanel {
    private static final String[] PORTS = {"Here", "There", "Everywhere", "Yes", "No", "You", "Know", "What", "I", "Mean"};
    private List<Port> ports;
    private Port selectedPort = null;
    private TablBateau tablBateau;
    private JDialog tablBateauDlg;
    private JTextField selectedPortField = new JTextField(20);
    
    public MainForm() {
        ports = Arrays.stream(PORTS).map(Port::new).collect(Collectors.toList());
        
        JButton showTablBateauButton = new JButton("Show Tabl Bateau");
        showTablBateauButton.addActionListener(e -> showTablBateau());
        
        add(showTablBateauButton);
        
        add(new JLabel("Selected Port:"));
        add(selectedPortField);
        
        int eb = 40;
        setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
    }
    
    public List<Port> getPorts() {
        return ports;
    }
    
    private void showTablBateau() {
        if (tablBateau == null) {
            tablBateau = new TablBateau();
            
            Window windowOwner = SwingUtilities.getWindowAncestor(this);
            
            tablBateauDlg = new JDialog(windowOwner, "Tabl Bateau", ModalityType.APPLICATION_MODAL);
            tablBateauDlg.add(tablBateau);
            tablBateauDlg.pack();
            tablBateauDlg.setLocationByPlatform(true);
        }
        
        tablBateau.setPorts(ports);
        tablBateauDlg.setVisible(true);
        
        selectedPortField.setFocusable(false);
        selectedPort = tablBateau.getSelectedPort();
        selectedPortField.setText(selectedPort.getName());
    }
}
class TablBateau extends JPanel {
    private JComboBox<Port> comboBox1 = new JComboBox<>();
    private List<Port> ports;
    
    public TablBateau() {
        add(comboBox1);
        comboBox1.setPrototypeDisplayValue(new Port("ABCDEFGHIJKLMNOP"));
        
        comboBox1.addActionListener(e -> itemSelected());
        
        int eb = 20;
        setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));

    }
    
    private void itemSelected() {
        Window windowOwner = SwingUtilities.getWindowAncestor(this);
        windowOwner.dispose();
    }

    public Port getSelectedPort() {
        return (Port) comboBox1.getSelectedItem();
    }

    public void setPorts(List<Port> ports) {
        this.ports = ports;
        DefaultComboBoxModel<Port> comboModel = new DefaultComboBoxModel<Port>(ports.toArray(new Port[] {}));
        comboBox1.setModel(comboModel);
        comboBox1.setSelectedIndex(-1);
    }
    
}
class Port {
    String name;

    public Port(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Port: " + getName();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM