/*
* UserInputPanel.java
*
* Created on 24.02.2009, 17:11:00
*/
package reportgen.gui.execute;
import com.toedter.calendar.JDateChooser;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.Document;
import reportgen.utils.ReportException;
import reportgen.prototype.utils.RowCount;
import reportgen.ren.report.userinput.UserInput;
import reportgen.ren.report.userinput.UserInputChunk;
import reportgen.ren.report.userinput.UserInputEditable;
import reportgen.ren.report.userinput.UserInputSelect;
/**
*
* @author axe
*/
public class UserInputPanel extends javax.swing.JPanel {
private UserInputChunk chunk;
private ArrayList<String> errors = new ArrayList<String>();
public UserInputPanel(UserInputChunk chunk) {
initComponents();
this.chunk = chunk;
Iterator<UserInput> it = chunk.getData().iterator();
JPanel parent = this;
int errorIndex = 0;
while(it.hasNext()) {
Component comp = null;
KnockModelListener knockModel = null;
UserInput userInput = it.next();
errors.add(null);
if(userInput instanceof UserInputEditable) {
//еденичное значение
UserInputEditable uie = (UserInputEditable) userInput;
if(uie.getValue() instanceof Boolean) {
//булевое
JCheckBox check = new JCheckBox("Да", (Boolean)uie.getValue());
comp = check;
CheckBoxActionListener model = new CheckBoxActionListener(uie, errorIndex);
knockModel = model;
check.addActionListener(model);
} else if(uie.getValue() instanceof Date) {
JDateChooser dc = new JDateChooser((Date)uie.getValue());
comp = dc;
DateListener model = new DateListener(uie, errorIndex);
knockModel = model;
dc.getDateEditor().addPropertyChangeListener(model);
} else {
//не булевое - целое, вещественное, строка
JTextArea ta = new JTextArea(uie.getValue().toString());
comp = ta;
TxtFieldDocumentListener model = new TxtFieldDocumentListener(uie, errorIndex);
knockModel = model;
ta.getDocument().addDocumentListener(model);
}
} else if(userInput instanceof UserInputSelect) {
//выбор из множества
UserInputSelect uis = (UserInputSelect) userInput;
ArrayList<Integer> selectedRows = uis.getSelected();
if(uis.getActiveRows().isSingle()) {
//единичный выбор
JComboBox combo = new JComboBox(uis.getOptions().toArray());
if(selectedRows == null
|| selectedRows.size() != 1) {
combo.setSelectedIndex(-1);
uis.setSelected(null);
} else {
combo.setSelectedIndex(selectedRows.get(0));
}
comp = combo;
ComboItemListener model = new ComboItemListener(uis, errorIndex);
knockModel = model;
combo.addItemListener(model);
} else {
//множественный выбор
JList list = new JList(uis.getOptions().toArray());
if(selectedRows == null
|| selectedRows.size() == 0) {
list.setSelectedIndex(-1);
uis.setSelected(null);
} else {
for(Integer row: selectedRows) {
list.getSelectionModel().addSelectionInterval(row, row);
}
}
comp = list;
ListBoxSelectionListener model = new ListBoxSelectionListener(uis, errorIndex);
knockModel = model;
list.addListSelectionListener(model);
}
} else {
JLabel label = new JLabel("Unknown value");
label.setBorder(BorderFactory.createEtchedBorder());
comp = label;
}
JPanel titlePane = new JPanel(new BorderLayout(5, 5));
JLabel title = new JLabel(userInput.getTitle());
titlePane.add(title, BorderLayout.CENTER);
JCheckBox enableCheck = new JCheckBox("");
if(!userInput.isCanBeOmitted()) {
enableCheck.setEnabled(false);
enableCheck.setSelected(true);
} else {
enableCheck.setSelected(false);
enableCheck.addActionListener(new CheckBoxListener(comp, userInput,
errorIndex, knockModel));
comp.setEnabled(false);
userInput.clearSelection();
}
titlePane.add(enableCheck, BorderLayout.WEST);
JPanel head = new JPanel(new BorderLayout(5, 5));
head.add(titlePane, BorderLayout.NORTH);
head.add(comp, BorderLayout.CENTER);
JPanel newParent = new JPanel(new BorderLayout(5, 5));
parent.add(head, BorderLayout.NORTH);
parent.add(newParent, BorderLayout.CENTER);
parent = newParent;
errorIndex++;
}
}
private class CheckBoxListener implements ActionListener {
private Component comp;
private UserInput ui;
private int errorIndex;
private KnockModelListener knockModelListener;
public CheckBoxListener(Component comp, UserInput ui,
int errorIndex, KnockModelListener knockModelListener) {
this.comp = comp;
this.ui = ui;
this.errorIndex = errorIndex;
this.knockModelListener = knockModelListener;
}
@Override
public void actionPerformed(ActionEvent e) {
JCheckBox combo = (JCheckBox) e.getSource();
if(combo.isSelected()) {
comp.setEnabled(true);
try {
knockModelListener.knock(comp);
} catch (ReportException ex) {
errors.set(errorIndex, "Введены неверные данные в поле '" + ui.getTitle() + "'");
}
} else {
comp.setEnabled(false);
ui.clearSelection();
errors.set(errorIndex, null);
}
}
}
public ArrayList<String> getErrors() {
return errors;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
setMinimumSize(new java.awt.Dimension(100, 54));
setPreferredSize(new java.awt.Dimension(100, 372));
setLayout(new java.awt.BorderLayout(5, 5));
}// </editor-fold>//GEN-END:initComponents
private class CheckBoxActionListener implements ActionListener, KnockModelListener {
private UserInputEditable uie;
private int errorIndex;
public CheckBoxActionListener(UserInputEditable uie, int errorIndex) {
this.uie = uie;
this.errorIndex = errorIndex;
}
@Override
public void actionPerformed(ActionEvent e) {
try {
knock((Component) e.getSource());
errors.set(errorIndex, null);
} catch (ReportException ex) {
errors.set(errorIndex, "Введены неверные данные в поле '" + uie.getTitle() +"'");
}
}
@Override
public void knock(Component comp) throws ReportException {
JCheckBox check = (JCheckBox) comp;
uie.setValue(new Boolean(check.isSelected()));
}
}
private class DateListener implements PropertyChangeListener,KnockModelListener {
private UserInputEditable uie;
private int errorIndex;
public DateListener(UserInputEditable uie, int errorIndex) {
this.uie = uie;
this.errorIndex = errorIndex;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!evt.getPropertyName().equals("date")) {
return;
}
try {
uie.setValue(evt.getNewValue());
errors.set(errorIndex, null);
} catch (Exception ex) {
errors.set(errorIndex, "Неверная дата в поле '" + uie.getTitle() + "'");
}
}
@Override
public void knock(Component comp) {
try {
uie.setValue(((JDateChooser)comp).getDate());
errors.set(errorIndex, null);
} catch (Exception ex) {
errors.set(errorIndex, "Неверная дата в поле '" + uie.getTitle() + "'");
}
}
}
private class TxtFieldDocumentListener implements DocumentListener,KnockModelListener {
private UserInputEditable uie;
private int errorIndex;
public TxtFieldDocumentListener(UserInputEditable uie, int errorIndex) {
this.uie = uie;
this.errorIndex = errorIndex;
}
@Override public void insertUpdate(DocumentEvent e) { changed(e); }
@Override public void removeUpdate(DocumentEvent e) { changed(e); }
@Override public void changedUpdate(DocumentEvent e) {}
private void changed(DocumentEvent e) {
updateValue(e.getDocument());
}
@Override
public void knock(Component comp) {
JTextArea tf = (JTextArea) comp;
updateValue(tf.getDocument());
}
private void updateValue(Document doc) {
Class cls = uie.getCls();
try {
try {
if(cls.equals(Long.class)) {
uie.setValue(Long.parseLong(doc.getText(0, doc.getLength())));
} else if(cls.equals(Double.class)) {
uie.setValue(Double.parseDouble(doc.getText(0, doc.getLength())));
} else if(cls.equals(String.class)) {
uie.setValue(doc.getText(0, doc.getLength()));
} else {
throw new ReportException("Неизвестный тип выражения в поле '" + uie.getTitle() +"'");
}
} catch (ReportException ex) {
throw ex;
} catch (Exception ex) {
throw new ReportException("Выражение введенное в поле '" + uie.getTitle() +"' некорректно!");
}
errors.set(errorIndex, null);
} catch (Exception ex) {
errors.set(errorIndex, ex.getLocalizedMessage());
}
}
}
private class ComboItemListener implements ItemListener,KnockModelListener {
private UserInputSelect uis;
private int index;
public ComboItemListener(UserInputSelect uis, int index) {
this.uis = uis;
this.index = index;
}
@Override
public void itemStateChanged(ItemEvent e) {
knock((Component) e.getSource());
}
@Override
public void knock(Component comp) {
JComboBox box = (JComboBox) comp;
ArrayList<Integer> selected = new ArrayList<Integer>();
int selIndex = box.getSelectedIndex();
if(selIndex != -1) {
selected.add(selIndex);
uis.setSelected(selected);
}
errors.set(index, null);
}
}
private class ListBoxSelectionListener implements ListSelectionListener,KnockModelListener {
private UserInputSelect uis;
private int index;
public ListBoxSelectionListener(UserInputSelect uis, int index) {
this.uis = uis;
this.index = index;
}
@Override
public void valueChanged(ListSelectionEvent e) {
updateValue((JList)e.getSource());
}
@Override
public void knock(Component comp) {
updateValue((JList) comp);
}
private void updateValue(JList list) {
try {
int sel[] = list.getSelectedIndices();
if(sel.length == 0) {
throw new ReportException("Нужно выбрать как минимум один элемент в списке '"
+ uis.getTitle() + "'");
}
RowCount activeRows = uis.getActiveRows();
if(sel.length > activeRows.getMaximum()) {
throw new ReportException("Нужно выбрать не более " +
activeRows.getMaximum() + "элементов в списке '" + uis.getTitle() + "'");
}
if(sel.length < activeRows.getMinimum()) {
throw new ReportException("Нужно выбрать не менее " +
activeRows.getMinimum() + "элементов в списке '" + uis.getTitle() + "'");
}
ArrayList<Integer> selection = new ArrayList<Integer>();
for(int i : sel) {
selection.add(new Integer(i));
}
uis.setSelected(selection);
errors.set(index, null);
} catch (Exception ex) {
errors.set(index, ex.getLocalizedMessage());
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}