Duda JAVA Index 2 out of bounds for length 2

  • 0 Respuestas
  • 868 Vistas

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado Hacker fashion

  • *
  • Underc0der
  • Mensajes: 44
  • Actividad:
    0%
  • Actividad:
    0%
  • Reputación 3
  • La información es poder!!
    • Ver Perfil

Duda JAVA Index 2 out of bounds for length 2

  • en: Marzo 28, 2019, 04:33:54 pm
Hola chicos buenas tardes a todos

Me estoy iniciando en esto de JAVA pero la verdad es que soy algo mala para esto y tengo un problema en este codigo, es una tabla que despliega una lista de navieras
y tiene opcion para ingresar Dias y Costo de demurrage(demora) por dias, esto lo muestra en una tabla
con 3 columnas (ShipLine, Demurrage Days, Cost Per Day) entonces quisiera poder actualizar los datos de
Days y price_per_day, el boton de Add/Update me funcionaba bien pero desde que meti una nueva columna
llamada price_per_day me lanza el siguiente error: 
Index 2 out of bounds for length 2
he googleado y entiendo que talvez me falte agregar columnas a mi TableModel,
es decir supongo que mi código agrega columnas de UI a la tabla pero no las agrega al modelo entonces nose como modificar esto,
ya que tambien quisiera poder agregar dos decimales y el signo de $ a los registros de price_per_day pero debido al error de la longitud no me deja.

entonces pues basicamente me faltan 2 cosas:
1-poder arreglar el boton de actualizar
2-mostrar la cantidad de la columna price_per_day con formato de dos decimales y signo de $ (algo asi como $100.00)


¿Qué hago? espero me puedan ayudar o decir como hacerlo  plisss :(

Código: [Seleccionar]
package com.integritas.tracargo.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import com.integritas.tracargo.constanst.Label;
import com.integritas.tracargo.controller.DemurrageController;
import com.integritas.tracargo.controller.ShipLineController;
import com.integritas.tracargo.util.DateUtil;
import com.integritas.tracargo.vo.DemurrageVO;
import com.integritas.tracargo.vo.ShipLineVO;

public class DemurragePanel extends JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;

private JFrame demurragePanel;

private DemurrageController demurrageController;
private ShipLineController shipLineController;
private List<ShipLineVO> shipLineList = null;
private String[] columNames = null;
private JTable demurrageTable;
private JComboBox shippingLinecombBox;
private JTextField jTextAdd;
private JTextField jTextAddCostPerDay;
private DateUtil dateUtil;

public DemurragePanel() {
demurrageController = new DemurrageController();
shipLineController = new ShipLineController();
columNames = new String[] { "SHIP_LINE_ID", Label.SHIP_LINE, Label.DEMURRAGE_DAYS, Label.DEMURRAGE_COST_PER_DAY  } ;
dateUtil = new DateUtil();

}

@SuppressWarnings({ "unchecked", "rawtypes" })
public void inicialize() {

demurragePanel = new JFrame();
demurragePanel.setIconImage(new ImageIcon("resources/TracargoF1.png").getImage());
demurragePanel.setTitle(Label.DEMURRAGE_PANEL);
demurragePanel.setBounds(100, 100, 820, 620);//100,100,520,420
demurragePanel.setLocationRelativeTo(null);
demurragePanel.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
demurragePanel.getContentPane().setLayout(null);


JLabel jLabelDescription = new JLabel();
jLabelDescription.setText("<html> Tracargo can monitor the number of demurrage days accrued <br> by each shipment and send alerts notifying you when free demurrage days will expire. <br>Please select the appropriate  shipping line and the corresponding number of free demurrage days. <font color=\"red\"> Then enter in the Demurrage cost per day. </font> </html>");

jLabelDescription.setBounds(15, 5, 500, 80);
jLabelDescription.setFont(new Font("Calibri", Font.BOLD, 13));
demurragePanel.getContentPane().add(jLabelDescription);


JLabel jLabelShipline = new JLabel("Shipping Line" + ":");
jLabelShipline.setBounds(285, 100, 120, 25); //15,100,120,25
jLabelShipline.setFont(new Font("Calibri", Font.BOLD, 13));
demurragePanel.getContentPane().add(jLabelShipline);

shipLineList = new ArrayList<ShipLineVO>();
shipLineList.add(new ShipLineVO("0", "Select a Ship Line"));

try {
shipLineList.addAll(shipLineController.getShipLineList());
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}

shippingLinecombBox = new JComboBox(shipLineList.toArray());
shippingLinecombBox.setBounds(399, 97, 120, 25); //120,100,120,25
shippingLinecombBox.setFont(new Font("Tahoma", Font.BOLD, 13));
shippingLinecombBox.setSelectedIndex(0);
demurragePanel.getContentPane().add(shippingLinecombBox);

JLabel jLabelDays = new JLabel("Days" + ":");
jLabelDays.setBounds(285, 140,60, 25); //245,100,60,25
jLabelDays.setFont(new Font("Calibri", Font.BOLD, 13));
demurragePanel.getContentPane().add(jLabelDays);

jTextAdd = new JTextField();
jTextAdd.setBounds(325, 140, 65, 25); //285,100,55,25
jTextAdd.setFont(new Font("Calibri", Font.BOLD, 13));
demurragePanel.getContentPane().add(jTextAdd);

/////////////////////////////////////////////////////////////
//////////////This Version of Tracargo Fase 6 //////////////
/////////////Tania Rivera 14/03/2019 //////////////////////
//////////////////////////////////////////////////////////
JLabel jLabelDemurrageCostPerDay = new JLabel("Demurrage cost per day" + ":");
jLabelDemurrageCostPerDay.setBounds(399, 140, 135, 25); //245,100,60,25
jLabelDemurrageCostPerDay.setForeground(Color.red);
jLabelDemurrageCostPerDay.setFont(new Font("Calibri", Font.BOLD, 13));
demurragePanel.getContentPane().add(jLabelDemurrageCostPerDay);


jTextAddCostPerDay = new JTextField();
jTextAddCostPerDay.setBounds(540, 140, 65, 25); //325,140,65,25
jTextAddCostPerDay.setFont(new Font("Calibri", Font.BOLD, 13));
demurragePanel.getContentPane().add(jTextAddCostPerDay); 

/////////////////////////////////////////////////////////////
//////////////This Version of Tracargo Fase 6 //////////////
/////////////Tania Rivera 14/03/2019 //////////////////////
//////////////////////////////////////////////////////////
JButton jbtnAdd = new JButton("Add/Update");
jbtnAdd.setBounds(640, 135, 120, 30); //340,100,120,30
jbtnAdd.setFont(new Font("Tahoma", Font.BOLD, 13));

//jbtnAdd.setFocusPainted(true);


jbtnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jbtnAdd_actionPerformed(e);
}
}); 
demurragePanel.getContentPane().add(jbtnAdd);

JPopupMenu popUpMenu = new JPopupMenu();

JMenuItem deleteMItem = new JMenuItem("Delete");
deleteMItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteDemurrage_actionPerformed(e);
}
});
popUpMenu.add(deleteMItem);

JPanel panel = new JPanel();
panel.setBounds(270, 250, 250, 180); //15,150,250,180  //270,250, 250, 180
panel.setLayout(null);

demurrageTable = new JTable();
demurrageTable.setRowSelectionAllowed(true);
demurrageTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
demurrageTable.setRowHeight(20); //20
demurrageTable.addMouseListener(new PopupListener(popUpMenu));

JScrollPane demurrageScrollPane = new JScrollPane();
demurrageScrollPane.setSize(250, 180); //250, 180
demurrageScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
demurrageScrollPane.setViewportView(demurrageTable);
panel.add(demurrageScrollPane, BorderLayout.CENTER);
demurragePanel.getContentPane().add(panel, BorderLayout.CENTER);

updateTable();

demurragePanel.setVisible(true);


}


public void updateTable() {

List<DemurrageVO> demurrageList = null;

try {
demurrageList = demurrageController.getAll();
Object[][] dataTable = null;

int row = 0;

if (demurrageList != null) {
                System.out.print("Tamaño:"+ demurrageList.size()); //ttttt
dataTable = new Object[demurrageList == null ? 0 : demurrageList.size()][columNames.length];

for (DemurrageVO item : demurrageList) {

dataTable[row][0] = item.getShipLineID();
dataTable[row][1] = item.getShipLine();
dataTable[row][2] = item.getDays();
dataTable[row][3] = item.getprice_per_day(); //Tania Rivera
//dataTable[row][3] = Integer.toString(item.getprice_per_day()); //Tania Rivera
row++;
}

demurrageTable.setModel(new DefaultTableModel(dataTable, columNames) {



@Override
public boolean isCellEditable(int row, int column) {
// all cells false
return false;
}
});

demurrageTable.getColumnModel().getColumn(0).setMinWidth(0);
demurrageTable.getColumnModel().getColumn(0).setMaxWidth(0);



/////////////////centrar datos de la columna////////////////////
DefaultTableCellRenderer tcr1 = new DefaultTableCellRenderer();
tcr1.setHorizontalAlignment(SwingConstants.CENTER);
JTable table;
demurrageTable.getColumnModel().getColumn(2).setCellRenderer(tcr1);

////////////////centrar datos de la columna/////////////////////
DefaultTableCellRenderer tcr2 = new DefaultTableCellRenderer();
tcr2.setHorizontalAlignment(SwingConstants.CENTER);
JTable table2;
demurrageTable.getColumnModel().getColumn(3).setCellRenderer(tcr2);



//DecimalFormat formato = new DecimalFormat("$#,###.###");
//String valorFormateado = formato.format(123456.789);

// double price_per_day = 100;
// double Days = 5;
// double precioFinal = (price_per_day * Days);


// DecimalFormat formato = new DecimalFormat("$#,###.###");
//String valorFormateado = formato.format(123456.789);

// System.out.println(precioFinal);


}

} catch (Exception e) {
JOptionPane.showMessageDialog(null, "" + e.getMessage());
}

}

public void jbtnAdd_actionPerformed(ActionEvent e) {

DemurrageVO demurrageVO = new DemurrageVO();


ShipLineVO shipLine = (ShipLineVO) shippingLinecombBox.getSelectedItem();


if (shipLine.getId().equals("0")) {
JOptionPane.showMessageDialog(null, "Select a ship line to continue");
return;
}

if (jTextAdd.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Please enter the days of demurrage");
return;

}


/////////////////////////////////////////////////////////////
//////////////This Version of Tracargo Fase 6 //////////////
/////////////Tania Rivera 14/03/2019 //////////////////////
//////////////////////////////////////////////////////////
// if (jTextAdd.getText().equals("")) {
// JOptionPane.showMessageDialog(null, "Please enter cost per day demurrage");
//return;
//}

// try {
// Integer.valueOf(jTextAddCostPerDay.getText());
// } catch (Exception e1) {
// JOptionPane.showMessageDialog(null, "Please enter cost per day demurrage");
// return;
//} 

//////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

try {
Integer.valueOf(jTextAdd.getText());
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, "Invalid number format for Days");
return;
}


//if (Integer.valueOf(jTextAddCostPerDay.getText()) <= 0) {
//JOptionPane.showMessageDialog(null, "Invalid number format for cost per day demurrage");
//return;
  //} 


demurrageVO.setShipLineID(shipLine.getId());
demurrageVO.setDays(Integer.valueOf(jTextAdd.getText()));
demurrageVO.setprice_per_day(Integer.valueOf(jTextAddCostPerDay.getText())); //Tania Rivera


try {

if (demurrageController.findByShipLine(shipLine.getId()) == 0) { // add
demurrageController.add(demurrageVO);
} else {// Update
demurrageController.update(demurrageVO);
JOptionPane.showMessageDialog(null, "Demurrage days for " + shipLine.getName() + " was updated");
}
updateTable();
shippingLinecombBox.setSelectedIndex(0);
jTextAdd.setText("");
} catch (Exception e1) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, e1.getMessage());

}
}


public void deleteDemurrage_actionPerformed(ActionEvent e) {
if (this.demurrageTable.getSelectedRow() != -1) {

String shipLineName = (String) this.demurrageTable.getModel()
.getValueAt(this.demurrageTable.getSelectedRow(), 1);

int confirm = JOptionPane.showConfirmDialog(null,
"Do you want to delete demurrage days for: " + shipLineName + "?", "Confirm", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {

String shipLineID = (String) this.demurrageTable.getModel()
.getValueAt(this.demurrageTable.getSelectedRow(), 0);
try {
demurrageController.delete(shipLineID);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
updateTable();
}
}


public static void main(String[] args) {
DemurragePanel demurragePanel = new DemurragePanel();
demurragePanel.inicialize();

}

}


Saludos