Ejemplo n.º 1
0
  private void createReport() {
    Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
    Account root = engine.getRootAccount();

    baseCommodity = engine.getDefaultCurrency();

    numberFormat = CommodityFormat.getFullNumberFormat(baseCommodity);
    SimpleDateFormat df = new SimpleDateFormat("dd-MMMMM-yyyy");

    dates = getDates();

    // title and dates
    pl.add(rb.getString("Title.ProfitLoss"));
    pl.add("");
    pl.add("From " + df.format(dates[0]) + " To " + df.format(dates[1]));
    pl.add("");
    pl.add("");

    // Income
    pl.add("Income");
    pl.add("------------------------------------------------------");
    getBalances(root, dates, AccountType.INCOME);

    // Add up the  Gross Income.
    BigDecimal total1 = BigDecimal.ZERO;
    for (Object aBalance1 : balance) {
      total1 = total1.add((BigDecimal) aBalance1);
    }
    pl.add("------------------------------------------------------");
    pl.add(formatAcctNameOut(rb.getString("Word.GrossIncome")) + " " + formatDecimalOut(total1));
    pl.add("------------------------------------------------------");
    pl.add("");
    pl.add("");

    // Expense
    pl.add("Expenses");
    pl.add("------------------------------------------------------");
    balance = new ArrayList<>();
    getBalances(root, dates, AccountType.EXPENSE);

    // Add up the Gross Expenses
    BigDecimal total2 = BigDecimal.ZERO;
    for (Object aBalance : balance) {
      total2 = total2.add((BigDecimal) aBalance);
    }
    pl.add("------------------------------------------------------");
    pl.add(formatAcctNameOut(rb.getString("Word.GrossExpense")) + " " + formatDecimalOut(total2));
    pl.add("------------------------------------------------------");
    pl.add("");
    pl.add("");

    // Net Total
    pl.add("------------------------------------------------------");
    pl.add(
        formatAcctNameOut(rb.getString("Word.NetIncome"))
            + " "
            + formatDecimalOut(total1.add(total2)));
    pl.add("======================================================");
  }
  private void initComponents() {
    Preferences preferences = Preferences.userNodeForPackage(RemoteConnectionDialog.class);

    setPort(preferences.getInt(LAST_PORT, JpaNetworkServer.DEFAULT_PORT));
    setHost(preferences.get(LAST_HOST, "localhost"));

    cancelButton = new JButton(rb.getString("Button.Cancel"));
    okButton = new JButton(rb.getString("Button.Ok"));

    cancelButton.addActionListener(this);
    okButton.addActionListener(this);
  }
  private void initComponents() {
    datePanel = new DatePanel();
    numberCombo = new TransactionNumberComboBox(account);

    okButton = new JButton(rb.getString("Button.Ok"));
    cancelButton = new JButton(rb.getString("Button.Cancel"));

    okButton.addActionListener(this);
    cancelButton.addActionListener(this);

    getRootPane().setDefaultButton(okButton);
  }
  private void initComponents() {

    final Resource rb = Resource.get();

    setTitle(rb.getString("Title.DefTranNum"));

    okButton = new JButton(rb.getString("Button.Ok"));
    cancelButton = new JButton(rb.getString("Button.Cancel"));
    insertButton = new JButton(rb.getString("Button.Insert"));
    removeButton = new JButton(rb.getString("Button.Remove"));

    upButton = new JButton(Resource.getIcon("/jgnash/resource/stock_up-16.png"));
    downButton = new JButton(Resource.getIcon("/jgnash/resource/stock_down-16.png"));

    insertButton.addActionListener(this);
    cancelButton.addActionListener(this);
    okButton.addActionListener(this);
    removeButton.addActionListener(this);
    upButton.addActionListener(this);
    downButton.addActionListener(this);

    model = new DefaultListModel<>();
    final List<String> items =
        EngineFactory.getEngine(EngineFactory.DEFAULT).getTransactionNumberList();

    for (String s : items) {
      model.addElement(s);
    }

    list = new JList<>(model);

    entryField = new JTextFieldEx(10);
  }
Ejemplo n.º 5
0
  private void initComponents() {
    feeField = new JFloatField(account.getCurrencyNode());

    feeButton = new JButton(Resource.getIcon("/jgnash/resource/document-properties.png"));
    feeButton.setMargin(new Insets(0, 0, 0, 0));

    feeButton.addActionListener(this);
    feeButton.setFocusPainted(false);

    if (ThemeManager.isLookAndFeelNimbus()) {
      NimbusUtils.reduceNimbusButtonMargin(feeButton);
      feeButton.setIcon(
          NimbusUtils.scaleIcon(Resource.getIcon("/jgnash/resource/document-properties.png")));
    }
  }
  private void layoutMainPanel() {
    Resource rb = Resource.get();

    initComponents();

    FormLayout layout = new FormLayout("2dlu, right:d, $lcgap, max(40dlu;d), $lcgap, d", "min");

    DefaultFormBuilder builder = new DefaultFormBuilder(layout, this);
    setLayout(layout);

    setBorder(Borders.EMPTY);

    builder.add(new JLabel(rb.getString("Label.Year")), CC.xy(2, 1));
    builder.add(yearSpinner, CC.xy(4, 1));
    builder.add(sparklinePanel, CC.xy(6, 1));
  }
Ejemplo n.º 7
0
  private void layoutMainPanel() {
    initComponents();

    FormLayout layout = new FormLayout("p:g", "");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);

    builder.setDefaultDialogBorder();

    builder.appendTitle(rb.getString("Message.TransToPrint"));
    builder.append(ButtonBarFactory.buildLeftAlignedBar(selectButton, clearButton, invertButton));
    builder.nextLine();
    builder.appendUnrelatedComponentsGapRow();
    builder.nextLine();
    builder.appendRow(RowSpec.decode("f:75dlu:g"));
    builder.append(new JScrollPane(table));
    builder.nextLine();
    builder.appendUnrelatedComponentsGapRow();
    builder.nextLine();
    builder.append(ButtonBarFactory.buildOKCancelBar(okButton, cancelButton));

    getContentPane().add(builder.getPanel(), BorderLayout.CENTER);

    pack();

    setMinimumSize(getSize());
  }
Ejemplo n.º 8
0
  public GenericCloseDialog(final Window parent, final JComponent panel, final String title) {
    super(parent);
    setTitle(title);
    setModal(true);
    setIconImage(Resource.getImage("/jgnash/resource/gnome-money.png"));
    this.component = panel;
    layoutMainPanel();

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setLocationRelativeTo(parent);
  }
Ejemplo n.º 9
0
/**
 * A simple dialog with a close button
 *
 * @author Craig Cavanaugh
 */
public class GenericCloseDialog extends JDialog implements ActionListener {

  private final Resource rb = Resource.get();

  private JButton closeButton;

  private final JComponent component;

  public GenericCloseDialog(final Window parent, final JComponent panel, final String title) {
    super(parent);
    setTitle(title);
    setModal(true);
    setIconImage(Resource.getImage("/jgnash/resource/gnome-money.png"));
    this.component = panel;
    layoutMainPanel();

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setLocationRelativeTo(parent);
  }

  public GenericCloseDialog(final JComponent panel, final String title) {
    this(UIApplication.getFrame(), panel, title);
  }

  JComponent getComponent() {
    return component;
  }

  private void layoutMainPanel() {
    FormLayout layout = new FormLayout("fill:p:g", "f:p:g, $ugap, f:p");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);
    builder.border(Borders.DIALOG);

    closeButton = new JButton(rb.getString("Button.Close"));

    builder.append(component);
    builder.nextLine();
    builder.nextLine();
    builder.append(StaticUIMethods.buildCloseBar(closeButton));

    getContentPane().add(builder.getPanel());
    pack();

    closeButton.addActionListener(this);
  }

  /** Invoked when an action occurs. */
  @Override
  public void actionPerformed(final ActionEvent e) {
    if (e.getSource() == closeButton) {
      dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }
  }
}
  public RemoteConnectionDialog(final JFrame parent) {
    super(parent, true);
    setTitle(rb.getString("Title.ConnectServer"));
    layoutMainPanel();

    setMinimumSize(getSize());

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    DialogUtils.addBoundsListener(this);
  }
Ejemplo n.º 11
0
  private void layoutMainPanel() {
    initComponents();

    FormLayout layout = new FormLayout("p, 8dlu, 85dlu:g", "");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout, this);

    builder.appendSeparator(rb.getString("Title.SelDestAccount"));
    builder.nextLine();
    builder.appendRelatedComponentsGapRow();
    builder.nextLine();
    builder.appendRow(RowSpec.decode("p"));
    builder.append(helpPane, 3);

    builder.nextLine();
    builder.appendRelatedComponentsGapRow();
    builder.nextLine();
    builder.append(rb.getString("Label.DestAccount"), accountCombo);
    builder.nextLine();
    builder.append(rb.getString("Label.DateFormat"), dateFormatCombo);
  }
Ejemplo n.º 12
0
  private void buildPanel() {
    initComponents();

    FormLayout layout =
        new FormLayout("max(20dlu;d), 4dlu, 75dlu:grow(1.0)", "f:d, 3dlu, f:d, 10dlu, f:d");
    CellConstraints cc = new CellConstraints();

    layout.setRowGroups(new int[][] {{1, 3, 5}});

    JPanel p = new JPanel(layout);

    p.setBorder(Borders.DIALOG);
    p.add(new JLabel(rb.getString("Label.Date")), cc.xy(1, 1));
    p.add(datePanel, cc.xy(3, 1));
    p.add(new JLabel(rb.getString("Label.Number")), cc.xy(1, 3));
    p.add(numberCombo, cc.xy(3, 3));
    p.add(StaticUIMethods.buildOKCancelBar(okButton, cancelButton), cc.xyw(1, 5, 3));

    getContentPane().add(p, BorderLayout.CENTER);
  }
  private void layoutMainPanel() {
    initComponents();

    FormLayout layout = new FormLayout("p, 4dlu, fill:70dlu:g", "");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);
    builder.border(Borders.DIALOG);

    builder.append(rb.getString("Label.DatabaseServer"), hostField);
    builder.append(rb.getString("Label.Port"), portField);
    builder.append(rb.getString("Label.Password"), passwordField);

    builder.nextLine();
    builder.appendUnrelatedComponentsGapRow();
    builder.nextLine();
    builder.append(StaticUIMethods.buildOKCancelBar(okButton, cancelButton), 3);

    getContentPane().add(builder.getPanel());

    pack();

    setResizable(false);
  }
Ejemplo n.º 14
0
  Date[] getDates() {

    Date start = new Date();
    start = DateUtils.subtractYear(start);

    JDateField startField = new JDateField();
    JDateField endField = new JDateField();

    startField.setValue(start);

    FormLayout layout = new FormLayout("right:p, 4dlu, p:g", "");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);
    builder.setRowGroupingEnabled(true);

    builder.append(rb.getString("Label.StartDate"), startField);
    builder.append(rb.getString("Label.EndDate"), endField);
    builder.nextLine();
    builder.appendUnrelatedComponentsGapRow();
    builder.nextLine();

    JPanel panel = builder.getPanel();

    int option =
        JOptionPane.showConfirmDialog(
            null,
            new Object[] {panel},
            rb.getString("Message.StartEndDate"),
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.PLAIN_MESSAGE);

    if (option == JOptionPane.OK_OPTION) {
      return getLastDays(startField.dateValue(), endField.dateValue());
    }

    return null;
  }
Ejemplo n.º 15
0
  String getFileName() {
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    chooser.addChoosableFileFilter(
        new FileNameExtensionFilter(rb.getString("Message.TXTFile"), "txt"));

    if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
      String fileName = chooser.getSelectedFile().getAbsolutePath();
      if (!fileName.endsWith(".txt")) {
        fileName = fileName + ".txt";
      }
      return fileName;
    }
    return null;
  }
Ejemplo n.º 16
0
  static void fixWindowManager() {
    Toolkit toolkit = Toolkit.getDefaultToolkit();

    if (toolkit.getClass().getName().equals("sun.awt.X11.XToolkit")) {

      // Oracle Bug #6528430 - provide proper app name on Linux
      try {
        Field awtAppClassNameField = toolkit.getClass().getDeclaredField("awtAppClassName");
        awtAppClassNameField.setAccessible(true);
        awtAppClassNameField.set(toolkit, Resource.getAppName());
      } catch (NoSuchFieldException | IllegalAccessException ex) {
        Logger.getLogger(StaticUIMethods.class.getName())
            .log(Level.INFO, ex.getLocalizedMessage(), ex);
      }

      // Workaround for main menu, pop-up & mouse issues for Gnome 3 shell and Cinnamon
      if ("gnome-shell".equals(System.getenv("DESKTOP_SESSION"))
          || "cinnamon".equals(System.getenv("DESKTOP_SESSION"))
          || "gnome".equals(System.getenv("DESKTOP_SESSION"))
          || (System.getenv("XDG_CURRENT_DESKTOP") != null
              && System.getenv("XDG_CURRENT_DESKTOP").contains("GNOME"))) {
        try {
          Class<?> x11_wm = Class.forName("sun.awt.X11.XWM");

          Field awt_wMgr = x11_wm.getDeclaredField("awt_wmgr");
          awt_wMgr.setAccessible(true);

          Field other_wm = x11_wm.getDeclaredField("OTHER_WM");
          other_wm.setAccessible(true);

          if (awt_wMgr.get(null).equals(other_wm.get(null))) {
            Field metaCity_Wm = x11_wm.getDeclaredField("METACITY_WM");
            metaCity_Wm.setAccessible(true);
            awt_wMgr.set(null, metaCity_Wm.get(null));
            Logger.getLogger(StaticUIMethods.class.getName())
                .info("Installed window manager workaround");
          }
        } catch (ClassNotFoundException
            | NoSuchFieldException
            | SecurityException
            | IllegalArgumentException
            | IllegalAccessException ex) {
          Logger.getLogger(StaticUIMethods.class.getName())
              .log(Level.INFO, ex.getLocalizedMessage(), ex);
        }
      }
    }
  }
Ejemplo n.º 17
0
  private void layoutMainPanel() {
    FormLayout layout = new FormLayout("fill:p:g", "f:p:g, $ugap, f:p");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);
    builder.border(Borders.DIALOG);

    closeButton = new JButton(rb.getString("Button.Close"));

    builder.append(component);
    builder.nextLine();
    builder.nextLine();
    builder.append(StaticUIMethods.buildCloseBar(closeButton));

    getContentPane().add(builder.getPanel());
    pack();

    closeButton.addActionListener(this);
  }
  public AccountSecurityComboBox(final Account acc) {
    super();

    if (acc == null || acc.getAccountType().getAccountGroup() != AccountGroup.INVEST) {
      throw new IllegalArgumentException(
          Resource.get().getString("Message.Error.InvalidAccountGroup"));
    }

    this.account = acc;

    addAll(account.getSecurities());

    if (model.getSize() > 0) {
      setSelectedIndex(0);
    }

    registerListeners();
  }
Ejemplo n.º 19
0
  private void initComponents() {
    setTitle(rb.getString("Title.TransactionList"));

    selectButton = new JButton(rb.getString("Button.SelectAll"));
    clearButton = new JButton(rb.getString("Button.ClearAll"));
    invertButton = new JButton(rb.getString("Button.InvertSelection"));
    okButton = new JButton(rb.getString("Button.Ok"));
    cancelButton = new JButton(rb.getString("Button.Cancel"));

    model = new Model(_getPrintableTransactions());
    table = new FormattedJTable(model);

    table.getSelectionModel().addListSelectionListener(this);

    cancelButton.addActionListener(this);
    okButton.addActionListener(this);

    selectButton.addActionListener(this);
    clearButton.addActionListener(this);
    invertButton.addActionListener(this);
  }
Ejemplo n.º 20
0
/**
 * Displays a dialog that list all printable transactions. Specific transactions can be selected to
 * print.
 *
 * @author Craig Cavanaugh
 */
public class TransactionListDialog extends JDialog
    implements ActionListener, ListSelectionListener {

  private final Resource rb = Resource.get();

  private final String PRINT = rb.getString("Item.Print");

  private Model model = null;

  private boolean returnStatus = false; // return status of dialog

  private JTable table;

  private JButton cancelButton;

  private JButton clearButton;

  private JButton invertButton;

  private JButton okButton;

  private JButton selectButton;

  public TransactionListDialog() {
    super(UIApplication.getFrame(), true);
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    layoutMainPanel();
    setLocationRelativeTo(UIApplication.getFrame());
  }

  private void initComponents() {
    setTitle(rb.getString("Title.TransactionList"));

    selectButton = new JButton(rb.getString("Button.SelectAll"));
    clearButton = new JButton(rb.getString("Button.ClearAll"));
    invertButton = new JButton(rb.getString("Button.InvertSelection"));
    okButton = new JButton(rb.getString("Button.Ok"));
    cancelButton = new JButton(rb.getString("Button.Cancel"));

    model = new Model(_getPrintableTransactions());
    table = new FormattedJTable(model);

    table.getSelectionModel().addListSelectionListener(this);

    cancelButton.addActionListener(this);
    okButton.addActionListener(this);

    selectButton.addActionListener(this);
    clearButton.addActionListener(this);
    invertButton.addActionListener(this);
  }

  private void layoutMainPanel() {
    initComponents();

    FormLayout layout = new FormLayout("p:g", "");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);

    builder.setDefaultDialogBorder();

    builder.appendTitle(rb.getString("Message.TransToPrint"));
    builder.append(ButtonBarFactory.buildLeftAlignedBar(selectButton, clearButton, invertButton));
    builder.nextLine();
    builder.appendUnrelatedComponentsGapRow();
    builder.nextLine();
    builder.appendRow(RowSpec.decode("f:75dlu:g"));
    builder.append(new JScrollPane(table));
    builder.nextLine();
    builder.appendUnrelatedComponentsGapRow();
    builder.nextLine();
    builder.append(ButtonBarFactory.buildOKCancelBar(okButton, cancelButton));

    getContentPane().add(builder.getPanel(), BorderLayout.CENTER);

    pack();

    setMinimumSize(getSize());
  }

  /** Closes the dialog */
  private void closeDialog() {
    dispatchEvent(new WindowEvent(TransactionListDialog.this, WindowEvent.WINDOW_CLOSING));
    table.getSelectionModel().removeListSelectionListener(this);
    table = null;
  }

  private List<Transaction> _getPrintableTransactions() {
    List<Transaction> l = new ArrayList<>();

    for (Transaction t : EngineFactory.getEngine(EngineFactory.DEFAULT).getTransactions()) {
      if (PRINT.equalsIgnoreCase(t.getNumber())) {
        l.add(t);
      }
    }

    Collections.sort(l); // use natural sort order
    return l;
  }

  public boolean getReturnStatus() {
    return returnStatus;
  }

  public List<Transaction> getPrintableTransactions() {
    return model.getPrintableTransactions();
  }

  /**
   * Invoked when an action occurs.
   *
   * @param e event
   */
  @Override
  public void actionPerformed(final ActionEvent e) {
    if (e.getSource() == okButton) {
      returnStatus = true;
      closeDialog();
    } else if (e.getSource() == cancelButton) {
      returnStatus = false;
      closeDialog();
    } else if (e.getSource() == clearButton) {
      model.clearAll();
    } else if (e.getSource() == selectButton) {
      model.selectAll();
    } else if (e.getSource() == invertButton) {
      model.invertAll();
    }
  }

  /**
   * Called whenever the value of the selection changes.
   *
   * @param e the event that characterizes the change.
   */
  @Override
  public void valueChanged(final ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) {
      return;
    } // ignore extra messages

    if (e.getSource() == table.getSelectionModel()) {
      int i = table.getSelectedRow();
      if (i >= 0) {
        Wrapper w = model.getWrapperAt(i);
        w.print = !w.print;
        model.fireTableRowsUpdated(i, i);
        table.clearSelection();
      }
    }
  }

  private class Model extends AbstractTableModel {

    private static final long serialVersionUID = 6665735758964949493L;

    private final ArrayList<Wrapper> wrapperList = new ArrayList<>(); // list of transactions

    private final String[] columnNames = {
      rb.getString("Column.Print"),
      rb.getString("Column.Date"),
      rb.getString("Column.Payee"),
      rb.getString("Column.Account"),
      rb.getString("Column.Amount")
    };

    private final DateFormat dateFormatter = DateUtils.getShortDateFormat();

    private final CommodityFormat commodityformat = CommodityFormat.getFullFormat();

    protected Model(final List<Transaction> list) {

      for (Transaction t : list) {
        wrapperList.add(new Wrapper(t));
      }
    }

    @Override
    public String getColumnName(final int c) {
      return columnNames[c];
    }

    @Override
    public Class<?> getColumnClass(final int column) {
      if (column == 4) {
        return BigDecimal.class;
      }

      return String.class;
    }

    /**
     * Returns the number of columns in the model. A <code>JTable</code> uses this method to
     * determine how many columns it should create and display by default.
     *
     * @return the number of columns in the model
     * @see #getRowCount
     */
    @Override
    public int getColumnCount() {
      return columnNames.length;
    }

    /**
     * Returns the number of rows in the model. A <code>JTable</code> uses this method to determine
     * how many rows it should display. This method should be quick, as it is called frequently
     * during rendering.
     *
     * @return the number of rows in the model
     * @see #getColumnCount
     */
    @Override
    public int getRowCount() {
      return wrapperList.size();
    }

    /**
     * Returns the value for the cell at <code>columnIndex</code> and <code>rowIndex</code>.
     *
     * @param rowIndex the row whose value is to be queried
     * @param columnIndex the column whose value is to be queried
     * @return the value Object at the specified cell
     */
    @Override
    public Object getValueAt(final int rowIndex, final int columnIndex) {
      Wrapper w = wrapperList.get(rowIndex);

      Account baseAccount;

      if (w.transaction.getTransactionEntries().size() > 1) {
        baseAccount = w.transaction.getCommonAccount();
      } else {
        baseAccount = w.transaction.getTransactionEntries().get(0).getDebitAccount();
      }

      switch (columnIndex) {
        case 0:
          if (w.print) {
            return AccountTableModel.RECONCILED_SYM;
          }
          return null;
        case 1:
          return dateFormatter.format(w.transaction.getDate());
        case 2:
          return w.transaction.getPayee();
        case 3:
          return baseAccount.getName();
        case 4:
          return commodityformat.format(
              w.transaction.getAmount(baseAccount).abs(), baseAccount.getCurrencyNode());
        default:
          return null;
      }
    }

    protected Wrapper getWrapperAt(final int i) {
      return wrapperList.get(i);
    }

    public List<Transaction> getPrintableTransactions() {

      ArrayList<Transaction> list = new ArrayList<>();

      for (Wrapper w : wrapperList) {
        if (w.print) {
          list.add(w.transaction);
        }
      }

      return list;
    }

    protected void clearAll() {
      int size = wrapperList.size();
      for (int i = 0; i < size; i++) {
        getWrapperAt(i).print = false;
      }
      fireTableDataChanged();
    }

    protected void selectAll() {
      int size = wrapperList.size();
      for (int i = 0; i < size; i++) {
        getWrapperAt(i).print = true;
      }
      fireTableDataChanged();
    }

    protected void invertAll() {
      int size = wrapperList.size();
      for (int i = 0; i < size; i++) {
        getWrapperAt(i).print = !getWrapperAt(i).print;
      }
      fireTableDataChanged();
    }
  }

  /** Class to wrap a transaction and maintain the selection state of the transaction */
  private static final class Wrapper {

    Transaction transaction;

    boolean print;

    protected Wrapper(final Transaction t) {
      assert t != null;
      this.transaction = t;
    }
  }
}
Ejemplo n.º 21
0
/**
 * A Dialog for getting a date and transaction number.
 *
 * @author Craig Cavanaugh
 */
class DateChkNumberDialog extends JDialog implements ActionListener {

  private final Resource rb = Resource.get();

  private JButton okButton;

  private JButton cancelButton;

  DatePanel datePanel;

  TransactionNumberComboBox numberCombo;

  private final Account account;

  private boolean result = false;

  /**
   * Creates new form AbstractDateChkNumberDialog
   *
   * @param a the account for the transaction. This can be null.
   * @param title Title for the dialog
   */
  DateChkNumberDialog(final Account a, final String title) {
    super(UIApplication.getFrame(), ModalityType.APPLICATION_MODAL);

    setTitle(title);

    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    this.account = a;

    buildPanel();

    if (a != null) {
      numberCombo.setText(a.getNextTransactionNumber());
    }

    pack();
    setMinimumSize(getSize());

    DialogUtils.addBoundsListener(this);
  }

  /** Closes the dialog */
  private void closeDialog() {
    dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
  }

  private void initComponents() {
    datePanel = new DatePanel();
    numberCombo = new TransactionNumberComboBox(account);

    okButton = new JButton(rb.getString("Button.Ok"));
    cancelButton = new JButton(rb.getString("Button.Cancel"));

    okButton.addActionListener(this);
    cancelButton.addActionListener(this);

    getRootPane().setDefaultButton(okButton);
  }

  private void buildPanel() {
    initComponents();

    FormLayout layout =
        new FormLayout("max(20dlu;d), 4dlu, 75dlu:grow(1.0)", "f:d, 3dlu, f:d, 10dlu, f:d");
    CellConstraints cc = new CellConstraints();

    layout.setRowGroups(new int[][] {{1, 3, 5}});

    JPanel p = new JPanel(layout);

    p.setBorder(Borders.DIALOG);
    p.add(new JLabel(rb.getString("Label.Date")), cc.xy(1, 1));
    p.add(datePanel, cc.xy(3, 1));
    p.add(new JLabel(rb.getString("Label.Number")), cc.xy(1, 3));
    p.add(numberCombo, cc.xy(3, 3));
    p.add(StaticUIMethods.buildOKCancelBar(okButton, cancelButton), cc.xyw(1, 5, 3));

    getContentPane().add(p, BorderLayout.CENTER);
  }

  void okAction() {
    result = true;
    closeDialog();
  }

  /**
   * Gets the date entered in the form
   *
   * @return The date entered in the form
   */
  public Date getDate() {
    return datePanel.getDate();
  }

  /**
   * Gets the number entered in the form
   *
   * @return The number entered in the form
   */
  public String getNumber() {
    return numberCombo.getText();
  }

  /** @return true if closed with the Ok Button */
  public boolean getResult() {
    return result;
  }

  @Override
  public void actionPerformed(final ActionEvent e) {
    if (e.getSource() == okButton) {
      okAction();
    } else if (e.getSource() == cancelButton) {
      closeDialog();
    }
  }
}
Ejemplo n.º 22
0
/**
 * Profit loss report
 *
 * @author Michael Mueller
 * @author Craig Cavanaugh
 * @author David Robertson
 */
public class ProfitLossTXT {

  private NumberFormat numberFormat;

  private static final boolean SHOW_EMPTY_ACCOUNT = false;

  private ArrayList<BigDecimal> balance = new ArrayList<>();

  private ArrayList<String> pl = new ArrayList<>();

  private CurrencyNode baseCommodity;

  private Date[] dates;

  private final Resource rb = Resource.get();

  public void run() {
    createReport();
    writePLFile(getFileName());
  }

  private void createReport() {
    Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
    Account root = engine.getRootAccount();

    baseCommodity = engine.getDefaultCurrency();

    numberFormat = CommodityFormat.getFullNumberFormat(baseCommodity);
    SimpleDateFormat df = new SimpleDateFormat("dd-MMMMM-yyyy");

    dates = getDates();

    // title and dates
    pl.add(rb.getString("Title.ProfitLoss"));
    pl.add("");
    pl.add("From " + df.format(dates[0]) + " To " + df.format(dates[1]));
    pl.add("");
    pl.add("");

    // Income
    pl.add("Income");
    pl.add("------------------------------------------------------");
    getBalances(root, dates, AccountType.INCOME);

    // Add up the  Gross Income.
    BigDecimal total1 = BigDecimal.ZERO;
    for (Object aBalance1 : balance) {
      total1 = total1.add((BigDecimal) aBalance1);
    }
    pl.add("------------------------------------------------------");
    pl.add(formatAcctNameOut(rb.getString("Word.GrossIncome")) + " " + formatDecimalOut(total1));
    pl.add("------------------------------------------------------");
    pl.add("");
    pl.add("");

    // Expense
    pl.add("Expenses");
    pl.add("------------------------------------------------------");
    balance = new ArrayList<>();
    getBalances(root, dates, AccountType.EXPENSE);

    // Add up the Gross Expenses
    BigDecimal total2 = BigDecimal.ZERO;
    for (Object aBalance : balance) {
      total2 = total2.add((BigDecimal) aBalance);
    }
    pl.add("------------------------------------------------------");
    pl.add(formatAcctNameOut(rb.getString("Word.GrossExpense")) + " " + formatDecimalOut(total2));
    pl.add("------------------------------------------------------");
    pl.add("");
    pl.add("");

    // Net Total
    pl.add("------------------------------------------------------");
    pl.add(
        formatAcctNameOut(rb.getString("Word.NetIncome"))
            + " "
            + formatDecimalOut(total1.add(total2)));
    pl.add("======================================================");
  }

  void writePLFile(final String fileName) {
    if (fileName == null || dates == null) {
      return;
    }

    try (BufferedWriter writer =
        new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName)))) {
      for (Object aPl : pl) { // write the array list pl to the file
        // print (pl.get(i));
        writer.write(aPl.toString());
        writer.newLine();
      }
      writer.newLine();
    } catch (IOException e) {
      Logger.getLogger(ProfitLossTXT.class.getName()).log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
  }

  private static Date[] getLastDays(final Date start, final Date stop) {
    ArrayList<Date> list = new ArrayList<>();

    Date s = DateUtils.trimDate(start);
    Date t = DateUtils.trimDate(stop);
    list.add(s);
    list.add(t);
    return list.toArray(new Date[list.size()]);
  }

  Date[] getDates() {

    Date start = new Date();
    start = DateUtils.subtractYear(start);

    JDateField startField = new JDateField();
    JDateField endField = new JDateField();

    startField.setValue(start);

    FormLayout layout = new FormLayout("right:p, 4dlu, p:g", "");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);
    builder.setRowGroupingEnabled(true);

    builder.append(rb.getString("Label.StartDate"), startField);
    builder.append(rb.getString("Label.EndDate"), endField);
    builder.nextLine();
    builder.appendUnrelatedComponentsGapRow();
    builder.nextLine();

    JPanel panel = builder.getPanel();

    int option =
        JOptionPane.showConfirmDialog(
            null,
            new Object[] {panel},
            rb.getString("Message.StartEndDate"),
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.PLAIN_MESSAGE);

    if (option == JOptionPane.OK_OPTION) {
      return getLastDays(startField.dateValue(), endField.dateValue());
    }

    return null;
  }

  String getFileName() {
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    chooser.addChoosableFileFilter(
        new FileNameExtensionFilter(rb.getString("Message.TXTFile"), "txt"));

    if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
      String fileName = chooser.getSelectedFile().getAbsolutePath();
      if (!fileName.endsWith(".txt")) {
        fileName = fileName + ".txt";
      }
      return fileName;
    }
    return null;
  }

  /**
   * format output decimal amount
   *
   * @param amt the BigDecimal value to format
   * @return formated string
   */
  private String formatDecimalOut(final BigDecimal amt) {

    int maxLen = 15; // (-000,000,000.00)
    StringBuilder sb = new StringBuilder();

    String formattedAmt = numberFormat.format(amt);

    // right align amount to pre-defined maximum length (maxLen)
    int amtLen = formattedAmt.length();
    if (amtLen < maxLen) {
      for (int ix = amtLen; ix < maxLen; ix++) {
        sb.append(' ');
      }
    }

    sb.append(formattedAmt);

    return sb.toString();
  }

  /**
   * format output account name
   *
   * @param acctName the account name to format
   * @return the formatted account name
   */
  private static String formatAcctNameOut(final String acctName) {

    int maxLen = 30; // max 30 characters
    StringBuilder sb = new StringBuilder(maxLen);

    sb.append(acctName);

    // set name to pre-defined maximum length (maxLen)
    int nameLen = acctName.length();
    for (int ix = nameLen; ix < maxLen; ix++) {
      sb.append(' ');
    }
    sb.setLength(maxLen);

    return sb.toString();
  }

  void getBalances(final Account a, final Date[] dates1, final AccountType type) {

    for (Account child : a.getChildren()) {
      int len = child.getTransactionCount();
      if ((SHOW_EMPTY_ACCOUNT || len > 0) && type == child.getAccountType()) {
        String acctName = child.getName();

        BigDecimal acctBal =
            AccountBalanceDisplayManager.convertToSelectedBalanceMode(
                child.getAccountType(), child.getBalance(dates1[0], dates1[1], baseCommodity));

        // output account name and balance
        pl.add(formatAcctNameOut(acctName) + " " + formatDecimalOut(acctBal));

        balance.add(acctBal);
      }
      if (child.isParent()) {
        getBalances(child, dates1, type);
      }
    }
  }
}
Ejemplo n.º 23
0
 /**
  * Display an error message
  *
  * @param message error message to display
  */
 public static void displayWarning(final String message) {
   displayMessage(message, Resource.get().getString("Title.Warning"), JOptionPane.WARNING_MESSAGE);
 }
Ejemplo n.º 24
0
 /**
  * toString must return a valid description for this page that will appear in the task list of the
  * WizardDialog
  */
 @Override
 public String toString() {
   return "1. " + rb.getString("Title.SelDestAccount");
 }
/**
 * Remote Connection Dialog
 *
 * @author Craig Cavanaugh
 */
public class RemoteConnectionDialog extends JDialog implements ActionListener {

  private final Resource rb = Resource.get();

  private final JPasswordField passwordField = new JPasswordField();

  private final JTextField hostField = new JTextFieldEx();

  private JButton okButton;

  private JButton cancelButton;

  private final JIntegerField portField = new JIntegerField();

  private boolean result = false;

  private static final String LAST_PORT = "lastPort";

  private static final String LAST_HOST = "lastHost";

  public RemoteConnectionDialog(final JFrame parent) {
    super(parent, true);
    setTitle(rb.getString("Title.ConnectServer"));
    layoutMainPanel();

    setMinimumSize(getSize());

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    DialogUtils.addBoundsListener(this);
  }

  @Override
  public void actionPerformed(final ActionEvent e) {
    if (e.getSource() == cancelButton) {
      dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    } else if (e.getSource() == okButton) {
      result = true;

      Preferences preferences = Preferences.userNodeForPackage(RemoteConnectionDialog.class);
      preferences.put(LAST_HOST, hostField.getText());
      preferences.putInt(LAST_PORT, portField.intValue());

      dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }
  }

  public char[] getPassword() {
    return passwordField.getPassword();
  }

  public boolean getResult() {
    return result;
  }

  public String getHost() {
    return hostField.getText();
  }

  public void setHost(String host) {
    hostField.setText(host);
  }

  public void setPort(int port) {
    portField.setIntValue(port);
  }

  public int getPort() {
    return portField.intValue();
  }

  private void initComponents() {
    Preferences preferences = Preferences.userNodeForPackage(RemoteConnectionDialog.class);

    setPort(preferences.getInt(LAST_PORT, JpaNetworkServer.DEFAULT_PORT));
    setHost(preferences.get(LAST_HOST, "localhost"));

    cancelButton = new JButton(rb.getString("Button.Cancel"));
    okButton = new JButton(rb.getString("Button.Ok"));

    cancelButton.addActionListener(this);
    okButton.addActionListener(this);
  }

  private void layoutMainPanel() {
    initComponents();

    FormLayout layout = new FormLayout("p, 4dlu, fill:70dlu:g", "");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);
    builder.border(Borders.DIALOG);

    builder.append(rb.getString("Label.DatabaseServer"), hostField);
    builder.append(rb.getString("Label.Port"), portField);
    builder.append(rb.getString("Label.Password"), passwordField);

    builder.nextLine();
    builder.appendUnrelatedComponentsGapRow();
    builder.nextLine();
    builder.append(StaticUIMethods.buildOKCancelBar(okButton, cancelButton), 3);

    getContentPane().add(builder.getPanel());

    pack();

    setResizable(false);
  }
}
Ejemplo n.º 26
0
/**
 * First part of import wizard for import of QIF files from online sources.
 *
 * @author Craig Cavanaugh
 */
public class PartialOne extends JPanel implements WizardPage, ActionListener {
  private Account destinationAccount;

  private AccountListComboBox accountCombo;

  private JTextPane helpPane;

  private JComboBox<String> dateFormatCombo;

  private final QifAccount qAcc;

  private final Preferences pref = Preferences.userNodeForPackage(PartialOne.class);

  private static final String LAST_ACCOUNT = "lastAccount";

  private static final String DATE_FORMAT = "dateFormat";

  private final Resource rb = Resource.get();

  public PartialOne(QifAccount qAcc) {
    this.qAcc = qAcc;
    layoutMainPanel();
  }

  private void initComponents() {
    accountCombo = new AccountListComboBox();

    helpPane = new JTextPane();
    helpPane.setEditable(false);
    helpPane.setEditorKit(new StyledEditorKit());
    helpPane.setBackground(getBackground());
    helpPane.setText(TextResource.getString("QifOne.txt"));

    /* Create the combo for date format selection */
    String[] formats = {QifUtils.US_FORMAT, QifUtils.EU_FORMAT};
    dateFormatCombo = new JComboBox<>(formats);

    dateFormatCombo.addActionListener(this);
    dateFormatCombo.setSelectedIndex(pref.getInt(DATE_FORMAT, 0));

    accountCombo.addActionListener(this);

    /* Try a set the combobox to the last selected account */
    String lastAccount = pref.get(LAST_ACCOUNT, "");

    Account last = EngineFactory.getEngine(EngineFactory.DEFAULT).getAccountByUuid(lastAccount);

    if (last != null) {
      setAccount(last);
    }
  }

  private void layoutMainPanel() {
    initComponents();

    FormLayout layout = new FormLayout("p, 8dlu, 85dlu:g", "");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout, this);

    builder.appendSeparator(rb.getString("Title.SelDestAccount"));
    builder.nextLine();
    builder.appendRelatedComponentsGapRow();
    builder.nextLine();
    builder.appendRow(RowSpec.decode("p"));
    builder.append(helpPane, 3);

    builder.nextLine();
    builder.appendRelatedComponentsGapRow();
    builder.nextLine();
    builder.append(rb.getString("Label.DestAccount"), accountCombo);
    builder.nextLine();
    builder.append(rb.getString("Label.DateFormat"), dateFormatCombo);
  }

  private void accountAction() {
    destinationAccount = accountCombo.getSelectedAccount();

    /* Save the id of the selected account */
    if (destinationAccount != null) {
      pref.put(LAST_ACCOUNT, destinationAccount.getUuid());
      pref.putInt(DATE_FORMAT, dateFormatCombo.getSelectedIndex());
    }
  }

  @Override
  public boolean isPageValid() {
    // an account was selected, make sure that the destination is valid
    if (destinationAccount == null) {
      destinationAccount = accountCombo.getSelectedAccount();
    }
    return true;
  }

  public Account getAccount() {
    if (destinationAccount == null) {
      destinationAccount = accountCombo.getSelectedAccount();
    }
    return destinationAccount;
  }

  void setAccount(Account account) {
    destinationAccount = account;
    accountCombo.setSelectedAccount(destinationAccount);
  }

  String getDateFormat() {
    return (String) dateFormatCombo.getSelectedItem();
  }

  /** Reparse the dates based on the date format in the combo */
  private void reparseDates() {
    String df = getDateFormat();
    int count = qAcc.numItems();

    for (int i = 0; i < count; i++) {
      QifTransaction qt = qAcc.get(i);
      qt.date = QifUtils.parseDate(qt.oDate, df);
    }

    System.out.println("reparse");
  }

  /**
   * toString must return a valid description for this page that will appear in the task list of the
   * WizardDialog
   */
  @Override
  public String toString() {
    return "1. " + rb.getString("Title.SelDestAccount");
  }

  /** @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */
  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == accountCombo) {
      accountAction();
    } else if (e.getSource() == dateFormatCombo) {
      reparseDates();
    }
  }

  @Override
  public void getSettings(Map<Enum<?>, Object> map) {}

  @Override
  public void putSettings(Map<Enum<?>, Object> map) {}
}
Ejemplo n.º 27
0
 /**
  * Display an error message
  *
  * @param message error message to display
  */
 public static void displayError(final String message) {
   displayMessage(message, Resource.get().getString("Title.Error"), JOptionPane.ERROR_MESSAGE);
 }