Я должен заполнить два Jcombobox, сначала загрузив данные из текстового файла, перенести их в массив и, наконец, в Jcombobox. Названия комбоксов - MakesCMB и ModelCMB. Мне удалось загрузить MakeCMB. Хотелось бы помочь загрузить ModelCMB
make-models.txt (содержит следующее)
Alfa Romeo-Giulia, Spider, Stelvio
Audi-A3, A4, Q3, A6, A1, Q2, Q5
BMW-1 Series, 2 Series, 3 Series, 5 Series, X1, X3
Citroen-C1, C2, C3, C4, C5
В классе FileIO. java -
public class FileIO {
public static String loadFromFile(String fileName){
//creating object of Path
Path path = Paths.get("files/" + fileName);
String output = "";
try{
BufferedReader reader = null;
reader = Files.newBufferedReader(path);
String line = null;
while ((line = reader.readLine())!=null){
output += line + "\n";
}
reader.close();
}catch(IOException Ex){
System.out.println("Error " + Ex);
}
return output;
}
}
Main содержание программы
public class CarInsuranceQuoteGenerator extends javax.swing.JFrame {
//private String [] types = {"MPV-10", "SUV-10", "4WD-12", "VAN-12", "TRUCK-15"};
private String[] types = FileIO.loadFromFile("types.txt").split("\n");
private String[] make = FileIO.loadFromFile("makes-models.txt").split("\n");
//private String [] make = {"Alfa Romeo", "Audi", "BMW", "Citroen"};
private String [] AlphaRomeo = {"Giulia", "Spider", "Stelvio"};
private String [] Audi = {"A3","A4","Q3","A6","A1","Q2","Q5"};
private String [] BMW = {"1 Series", "2 Series", "3 Series", "5 Series", "X1", "X3"};
private String [] Citroen = {"C1", "C2", "C3", "C4", "C5"};
/**
* Creates new form CarInsuranceQuoteGenerator
*/
public CarInsuranceQuoteGenerator() {
initComponents();
loadTypes();
loadMake();
ModelCMB.removeAllItems();
ModelCMB.setModel(new DefaultComboBoxModel (AlphaRomeo));
}
public void loadTypes(){
TypesCMB.removeAllItems();
/*for (int i = 0; i < make.length; i++){
System.out.println(make[i].split(","));
}*/
for (String t : types){
MakeCMB.addItem(t.substring(0,t.indexOf("-")));
TypesCMB.addItem(t);
//TypesCMB.setSelectedIndex(0);
}
}
public void loadMake(){
MakeCMB.removeAllItems();
for (String t : make){
MakeCMB.addItem(t.substring(0,t.indexOf("-") ));
MakeCMB.setSelectedIndex(-1);
}
}
public void loadModel(int index){
if (index == 0){
ModelCMB.setModel(new DefaultComboBoxModel (AlphaRomeo));
}
else if (index == 1){
ModelCMB.setModel(new DefaultComboBoxModel(Audi));
}
else if (index == 2){
ModelCMB.setModel(new DefaultComboBoxModel(BMW));
}
else{
ModelCMB.setModel(new DefaultComboBoxModel(Citroen));
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jPanel1 = new javax.swing.JPanel();
RegistrationNumber = new javax.swing.JLabel();
RegNoTXT = new javax.swing.JTextField();
Type = new javax.swing.JLabel();
TypesCMB = new javax.swing.JComboBox<>();
Make = new javax.swing.JLabel();
MakeCMB = new javax.swing.JComboBox<>();
Model = new javax.swing.JLabel();
ModelCMB = new javax.swing.JComboBox<>();
Value = new javax.swing.JLabel();
ValueTXT = new javax.swing.JTextField();
QuoteBTN = new javax.swing.JButton();
ViewBTN = new javax.swing.JButton();
DU21 = new javax.swing.JCheckBox();
jCheckBox1 = new javax.swing.JCheckBox();
jScrollPane2 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jMenuBar1 = new javax.swing.JMenuBar();
File = new javax.swing.JMenu();
Exit = new javax.swing.JMenuItem();
Help = new javax.swing.JMenu();
About = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Car Registration");
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Car Insurance Quote Generator");
RegistrationNumber.setText("Registration Number:");
Type.setText("Type:");
TypesCMB.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
Make.setText("Make:");
MakeCMB.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
MakeCMB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MakeCMBActionPerformed(evt);
}
});
Model.setText("Model:");
ModelCMB.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
Value.setText("Value: €");
QuoteBTN.setMnemonic('A');
QuoteBTN.setText("Add Quote");
QuoteBTN.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QuoteBTNActionPerformed(evt);
}
});
ViewBTN.setMnemonic('V');
ViewBTN.setText("View All");
DU21.setText("Accident? (Last 12 Months)");
jCheckBox1.setText("Driver Under 21?");
jTextPane1.setText("Reg No\tMake\tModel\tDrive -21\tAccident?\tFee\n--------\t------\t-------\t-----------\t-----------\t----");
jScrollPane2.setViewportView(jTextPane1);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(Value, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ValueTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(QuoteBTN)
.addGap(18, 18, 18)
.addComponent(ViewBTN))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Model)
.addComponent(Make)
.addComponent(Type)
.addComponent(RegistrationNumber))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(RegNoTXT)
.addComponent(TypesCMB, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(MakeCMB, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ModelCMB, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(45, 45, 45)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jCheckBox1)
.addComponent(DU21))))
.addGap(0, 27, Short.MAX_VALUE))
.addComponent(jScrollPane2))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(RegistrationNumber)
.addComponent(RegNoTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Type)
.addComponent(TypesCMB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Make)
.addComponent(MakeCMB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(5, 5, 5)
.addComponent(jCheckBox1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Model)
.addComponent(ModelCMB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DU21, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Value)
.addComponent(ValueTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(QuoteBTN)
.addComponent(ViewBTN))
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
.addContainerGap())
);
File.setText("File");
Exit.setText("Exit");
Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ExitActionPerformed(evt);
}
});
File.add(Exit);
jMenuBar1.add(File);
Help.setMnemonic('H');
Help.setText("Help");
About.setText("About");
About.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AboutActionPerformed(evt);
}
});
Help.add(About);
jMenuBar1.add(Help);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
pack();
}// </editor-fold>
private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void AboutActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JDialog dialog = new JDialog(this,true);
dialog.setVisible(true);
}
private void MakeCMBActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
loadModel(MakeCMB.getSelectedIndex());
}
private void QuoteBTNActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String s = RegNoTXT.getText();
double p = 0;
try{
p = Double.parseDouble(ValueTXT.getText());
}catch(NumberFormatException vex){
JOptionPane.showMessageDialog(this,"Please insert a monetary value.\nEg. 20.50");
}
if ((!s.isEmpty()) || (p == 0)){
if (!Validate(s)){
JOptionPane.showMessageDialog(this, "Serial Number must contain 4 characters and 2 digits");
}
else {
RegNoTXT.setText("");
JOptionPane.showMessageDialog(this, "Enter Another Serial number.");
}
}
}
private boolean Validate(String S){
return S.matches("[A-Za-z]{4}[0-9]{2}");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CarInsuranceQuoteGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CarInsuranceQuoteGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CarInsuranceQuoteGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CarInsuranceQuoteGenerator.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CarInsuranceQuoteGenerator().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem About;
private javax.swing.JCheckBox DU21;
private javax.swing.JMenuItem Exit;
private javax.swing.JMenu File;
private javax.swing.JMenu Help;
private javax.swing.JLabel Make;
private javax.swing.JComboBox<String> MakeCMB;
private javax.swing.JLabel Model;
private javax.swing.JComboBox<String> ModelCMB;
private javax.swing.JButton QuoteBTN;
private javax.swing.JTextField RegNoTXT;
private javax.swing.JLabel RegistrationNumber;
private javax.swing.JLabel Type;
private javax.swing.JComboBox<String> TypesCMB;
private javax.swing.JLabel Value;
private javax.swing.JTextField ValueTXT;
private javax.swing.JButton ViewBTN;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
}