Beispiel #1
0
 /**
  * Recursive traverse of tree to determine selections A leaf is selected if rsm is selected.
  * Nonleaf nodes are selected if all children are selected.
  *
  * @param tn node in the tree for which to determine selection
  * @param nodeidx the ordinal postion in the segments array
  * @param gsm the graph segments selection model
  * @param rsm the table row selection model
  * @return true if given node tn is selected, else false
  */
 private boolean selTraverse(
     TreeNode tn, int[] nodeidx, ListSelectionModel gsm, ListSelectionModel rsm) {
   boolean selected = true;
   if (!tn.isLeaf()) {
     // A nonleaf node is selected if all its children are selected.
     for (int i = 0; i < tn.getChildCount(); i++) {
       TreeNode cn = tn.getChildAt(i);
       selected &= selTraverse(cn, nodeidx, gsm, rsm);
     }
   } else {
     if (tn instanceof RowCluster) {
       // get the row index of the leaf node
       int ri = ((RowCluster) tn).getIndex();
       // A leaf is selected if its row is selected in the row selection rsm.
       selected = rsm.isSelectedIndex(ri);
     }
   }
   // Get the offset into the segments array
   int idx = nodeidx[0] * segOffset;
   if (selected) {
     gsm.addSelectionInterval(idx, idx + (segOffset - 1));
   } else {
     gsm.removeSelectionInterval(idx, idx + (segOffset - 1));
   }
   // Increment the nodeidx in the tree
   nodeidx[0]++;
   return selected;
 }
    public void valueChanged(ListSelectionEvent e) {
      ListSelectionModel lsm = (ListSelectionModel) e.getSource();

      int firstIndex = e.getFirstIndex();
      int lastIndex = e.getLastIndex();
      boolean isAdjusting = e.getValueIsAdjusting();
      output.append(
          "Event for indexes "
              + firstIndex
              + " - "
              + lastIndex
              + "; isAdjusting is "
              + isAdjusting
              + "; selected indexes:");

      if (lsm.isSelectionEmpty()) {
        output.append(" <none>");
      } else {
        // Find out which indexes are selected.
        int minIndex = lsm.getMinSelectionIndex();
        int maxIndex = lsm.getMaxSelectionIndex();
        for (int i = minIndex; i <= maxIndex; i++) {
          if (lsm.isSelectedIndex(i)) {
            output.append(" " + i);
          }
        }
      }
      output.append(newline);
      output.setCaretPosition(output.getDocument().getLength());
    }
  // Implementation of valueChanged
  public void valueChanged(ListSelectionEvent e) {
    if (e.getSource() == table.getSelectionModel()) {
      ListSelectionModel ls = table.getSelectionModel();

      int index = ls.getMinSelectionIndex();
      long id = (long) table.getValueAt(index, 0);

      updateFeesData(id);
    } else {
      ListSelectionModel ls = feestable.getSelectionModel();

      int index = ls.getMinSelectionIndex();

      float feespayed = (float) feestable.getValueAt(index, 1);
      float totalfees = (float) feestable.getValueAt(index, 2);

      feespayedlabel.setText("Fees Payed: " + feespayed);
      totalfeeslabel.setText("Total Fees: " + totalfees);

      if (totalfees - feespayed > 0) {
        feesduelabel.setText("Fees Due: " + (totalfees - feespayed));
      }

      panel_6.revalidate();
    }
  }
Beispiel #4
0
    public void actionPerformed(ActionEvent e) {
      /*
       * This method can be called only if
       * there's a valid selection,
       * so go ahead and remove whatever's selected.
       */

      ListSelectionModel lsm = list.getSelectionModel();
      int firstSelected = lsm.getMinSelectionIndex();
      int lastSelected = lsm.getMaxSelectionIndex();
      listModel.removeRange(firstSelected, lastSelected);

      int size = listModel.size();

      if (size == 0) {
        // List is empty: disable delete, up, and down buttons.
        deleteButton.setEnabled(false);
        upButton.setEnabled(false);
        downButton.setEnabled(false);

      } else {
        // Adjust the selection.
        if (firstSelected == listModel.getSize()) {
          // Removed item in last position.
          firstSelected--;
        }
        list.setSelectedIndex(firstSelected);
      }
    }
  /**
   * Moves the column and heading at <code>columnIndex</code> to <code>newIndex</code>. The old
   * column at <code>columnIndex</code> will now be found at <code>newIndex</code>. The column that
   * used to be at <code>newIndex</code> is shifted left or right to make room. This will not move
   * any columns if <code>columnIndex</code> equals <code>newIndex</code>. This method also posts a
   * <code>columnMoved</code> event to its listeners.
   *
   * @param columnIndex the index of column to be moved
   * @param newIndex new index to move the column
   * @exception IllegalArgumentException if <code>column</code> or <code>newIndex</code> are not in
   *     the valid range
   */
  public void moveColumn(int columnIndex, int newIndex) {
    if ((columnIndex < 0)
        || (columnIndex >= getColumnCount())
        || (newIndex < 0)
        || (newIndex >= getColumnCount()))
      throw new IllegalArgumentException("moveColumn() - Index out of range");

    TableColumn aColumn;

    // If the column has not yet moved far enough to change positions
    // post the event anyway, the "draggedDistance" property of the
    // tableHeader will say how far the column has been dragged.
    // Here we are really trying to get the best out of an
    // API that could do with some rethinking. We preserve backward
    // compatibility by slightly bending the meaning of these methods.
    if (columnIndex == newIndex) {
      fireColumnMoved(new TableColumnModelEvent(this, columnIndex, newIndex));
      return;
    }
    aColumn = (TableColumn) tableColumns.elementAt(columnIndex);

    tableColumns.removeElementAt(columnIndex);
    boolean selected = selectionModel.isSelectedIndex(columnIndex);
    selectionModel.removeIndexInterval(columnIndex, columnIndex);

    tableColumns.insertElementAt(aColumn, newIndex);
    selectionModel.insertIndexInterval(newIndex, 1, true);
    if (selected) {
      selectionModel.addSelectionInterval(newIndex, newIndex);
    } else {
      selectionModel.removeSelectionInterval(newIndex, newIndex);
    }

    fireColumnMoved(new TableColumnModelEvent(this, columnIndex, newIndex));
  }
  /**
   * Returns the number of columns selected.
   *
   * @return the number of columns selected
   */
  public int getSelectedColumnCount() {
    if (selectionModel != null) {
      int iMin = selectionModel.getMinSelectionIndex();
      int iMax = selectionModel.getMaxSelectionIndex();
      int count = 0;

      for (int i = iMin; i <= iMax; i++) {
        if (selectionModel.isSelectedIndex(i)) {
          count++;
        }
      }
      return count;
    }
    return 0;
  }
Beispiel #7
0
  /**
   * Constructs a ClutoTree diaplay which is initialized with tableModel as the data model, and the
   * given selection model.
   *
   * @param clutoSolution The clustering solution
   * @param tableContext The context which manages views and selections.
   * @param tableModel the data model for the parallel coordinate display
   */
  public ClutoTree(ClutoSolution clutoSolution, TableContext tableContext, TableModel tableModel) {
    ctx = tableContext;
    tm = tableModel;
    lsm = ctx.getRowSelectionModel(tm);

    // labelModel
    int ncol = tm.getColumnCount();
    for (int i = 0; i < ncol; i++) {
      labelModel.addElement(tm.getColumnName(i));
    }

    setLayout(new BorderLayout());
    btnP = new JToolBar();
    add(btnP, BorderLayout.NORTH);
    labelChoice.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
              labelColumn = 0;
              String ln = (String) e.getItem();
              if (ln != null) {
                for (int c = 0; c < tm.getColumnCount(); c++) {
                  if (ln.equals(tm.getColumnName(c))) {
                    labelColumn = c;
                    break;
                  }
                }
              }
              graph.invalidate();
              validate();
              repaint();
            }
          }
        });
    btnP.add(labelChoice);

    graph = new SimpleGraph();
    graph.getGraphDisplay().setOpaque(true);
    graph.getGraphDisplay().setBackground(Color.white);
    graph.getGraphDisplay().setGridColor(new Color(220, 220, 220));
    graph.showGrid(false);
    graph.showAxis(BorderLayout.WEST, false);
    graph.showAxis(BorderLayout.EAST, true);
    graph.getAxisDisplay(BorderLayout.EAST).setZoomable(true);
    graph.getAxisDisplay(BorderLayout.EAST).setAxisLabeler(labeler);
    ((LinearAxis) graph.getYAxis()).setTickIncrement(-1.);
    graph.getAxisDisplay(BorderLayout.SOUTH).setZoomable(true);
    gs = new GraphSegments();
    gs.setColor(Color.blue);
    idxSelColor = new IndexSelectColor(Color.cyan, null, new DefaultListSelectionModel());
    gs.setIndexedColor(idxSelColor);
    graph.addGraphItem(gs);
    graph.getGraphDisplay().addMouseListener(ma);

    add(graph);
    if (lsm != null) {
      lsm.addListSelectionListener(selListener);
    }
    display(makeTree(clutoSolution));
  }
  /**
   * Sets the selection model for this <code>TableColumnModel</code> to <code>newModel</code> and
   * registers for listener notifications from the new selection model. If <code>newModel</code> is
   * <code>null</code>, an exception is thrown.
   *
   * @param newModel the new selection model
   * @exception IllegalArgumentException if <code>newModel</code> is <code>null</code>
   * @see #getSelectionModel
   */
  public void setSelectionModel(ListSelectionModel newModel) {
    if (newModel == null) {
      throw new IllegalArgumentException("Cannot set a null SelectionModel");
    }

    ListSelectionModel oldModel = selectionModel;

    if (newModel != oldModel) {
      if (oldModel != null) {
        oldModel.removeListSelectionListener(this);
      }

      selectionModel = newModel;
      newModel.addListSelectionListener(this);
    }
  }
Beispiel #9
0
  private List<Node> getSelectedNodes() {
    List<Node> selectedNodes = new Vector<Node>();
    NodeStatusTableModel myTableModel = (NodeStatusTableModel) getModel();

    ListSelectionModel lsm = getSelectionModel();
    int minIndex = lsm.getMinSelectionIndex();
    int maxIndex = lsm.getMaxSelectionIndex();

    for (int i = minIndex; i <= maxIndex; i++) {
      if (lsm.isSelectedIndex(i)) {
        // System.out.println("row " + i + " is selected");
        Node currNode = myTableModel.getNode(i);
        if (currNode != null) selectedNodes.add(currNode);
      }
    }

    return selectedNodes;
  }
 public void actionPerformed(ActionEvent e) {
   JListMutable list = (JListMutable) e.getSource();
   if (!list.hasFocus()) {
     CellEditor cellEditor = list.getListCellEditor();
     if (cellEditor != null && !cellEditor.stopCellEditing()) {
       return;
     }
     list.requestFocus();
     return;
   }
   ListSelectionModel rsm = list.getSelectionModel();
   int anchorRow = rsm.getAnchorSelectionIndex();
   list.editCellAt(anchorRow, null);
   Component editorComp = list.getEditorComponent();
   if (editorComp != null) {
     editorComp.requestFocus();
   }
 }
Beispiel #11
0
 /**
  * Traververse the tree selecting rows coresponding to leaf nodes of the given node tn
  *
  * @param tn the node from which to start traversing
  * @param rsm the selection model in which to mark selected rows
  */
 private void selectTraverse(TreeNode tn, ListSelectionModel rsm) {
   if (!tn.isLeaf()) {
     for (int i = 0; i < tn.getChildCount(); i++) {
       TreeNode cn = tn.getChildAt(i);
       selectTraverse(cn, rsm);
     }
   } else {
     if (tn instanceof RowCluster) {
       int ri = ((RowCluster) tn).getIndex();
       rsm.addSelectionInterval(ri, ri);
     }
   }
 }
  /**
   * Returns an array of selected columns. If <code>selectionModel</code> is <code>null</code>,
   * returns an empty array.
   *
   * @return an array of selected columns or an empty array if nothing is selected or the <code>
   *     selectionModel</code> is <code>null</code>
   */
  public int[] getSelectedColumns() {
    if (selectionModel != null) {
      int iMin = selectionModel.getMinSelectionIndex();
      int iMax = selectionModel.getMaxSelectionIndex();

      if ((iMin == -1) || (iMax == -1)) {
        return new int[0];
      }

      int[] rvTmp = new int[1 + (iMax - iMin)];
      int n = 0;
      for (int i = iMin; i <= iMax; i++) {
        if (selectionModel.isSelectedIndex(i)) {
          rvTmp[n++] = i;
        }
      }
      int[] rv = new int[n];
      System.arraycopy(rvTmp, 0, rv, 0, n);
      return rv;
    }
    return new int[0];
  }
 private void maybeGrabSelection() {
   if (table.getSelectedRow() != -1) {
     // Grab selection
     ListSelectionModel rowSel = table.getSelectionModel();
     ListSelectionModel colSel = table.getColumnModel().getSelectionModel();
     if (!haveAnchor()) {
       //        System.err.println("Updating from table's selection");
       setSelection(
           rowSel.getAnchorSelectionIndex(), rowSel.getLeadSelectionIndex(),
           colSel.getAnchorSelectionIndex(), colSel.getLeadSelectionIndex());
     } else {
       //        System.err.println("Updating lead from table's selection");
       setSelection(
           getRowAnchor(), rowSel.getLeadSelectionIndex(),
           getColAnchor(), colSel.getLeadSelectionIndex());
     }
     //      printSelection();
   }
 }
  /**
   * Deletes the <code>column</code> from the <code>tableColumns</code> array. This method will do
   * nothing if <code>column</code> is not in the table's columns list. <code>tile</code> is called
   * to resize both the header and table views. This method also posts a <code>columnRemoved</code>
   * event to its listeners.
   *
   * @param column the <code>TableColumn</code> to be removed
   * @see #addColumn
   */
  public void removeColumn(TableColumn column) {
    int columnIndex = tableColumns.indexOf(column);

    if (columnIndex != -1) {
      // Adjust for the selection
      if (selectionModel != null) {
        selectionModel.removeIndexInterval(columnIndex, columnIndex);
      }

      column.removePropertyChangeListener(this);
      tableColumns.removeElementAt(columnIndex);
      invalidateWidthCache();

      // Post columnAdded event notification.  (JTable and JTableHeader
      // listens so they can adjust size and redraw)
      fireColumnRemoved(new TableColumnModelEvent(this, columnIndex, 0));
    }
  }
Beispiel #15
0
  public SimpleTable() {
    JFrame frame = new JFrame("Table");
    frame.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });

    final String[] names = {"First Name", "Last Name", "Id"};
    final Object[][] data = {
      {"Mark", "Andrews", new Integer(1)},
      {"Tom", "Ball", new Integer(2)},
      {"Alan", "Chung", new Integer(3)},
    };

    TableModel dataModel =
        new AbstractTableModel() {
          public int getColumnCount() {
            return names.length;
          }

          public int getRowCount() {
            return data.length;
          }

          public Object getValueAt(int row, int col) {
            return data[row][col];
          }

          public String getColumnName(int column) {
            return names[column];
          }

          public Class getColumnClass(int col) {
            return getValueAt(0, col).getClass();
          }

          public void setValueAt(Object aValue, int row, int column) {
            data[row][column] = aValue;
          }
        };

    aTable = new JTable(dataModel);

    ListSelectionModel listMod = aTable.getSelectionModel();
    listMod.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    listMod.addListSelectionListener(this);

    JScrollPane scrollpane = new JScrollPane(aTable);
    scrollpane.setPreferredSize(new Dimension(300, 300));
    frame.getContentPane().add(scrollpane);
    frame.pack();
    frame.setVisible(true);

    aTable.addMouseListener(
        new MouseAdapter() {
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
              System.out.println(" double click");
            }
          }
        });
  }
  /** Initializes the table. */
  protected void init() {
    dataTable
        .getColumnModel()
        .addColumnModelListener(
            new TableColumnModelListener() {
              public void columnAdded(TableColumnModelEvent e) {
                /** empty block */
              }

              public void columnRemoved(TableColumnModelEvent e) {
                /** empty block */
              }

              public void columnSelectionChanged(ListSelectionEvent e) {
                /** empty block */
              }

              public void columnMarginChanged(ChangeEvent e) {
                refreshTable();
              }

              public void columnMoved(TableColumnModelEvent e) {
                refreshTable();
              }
            });
    // assemble statistics data array
    Dataset workingData = dataTable.getWorkingData();
    double[] xstats = getStatistics(workingData.getXPoints());
    double[] ystats = getStatistics(workingData.getValidYPoints());
    if (statsData == null) {
      statsData = new Object[xstats.length][0];
    }
    for (int i = 0; i < xstats.length; i++) {
      String label = ToolsRes.getString("Table.Entry.Count"); // $NON-NLS-1$
      if (i == 5) {
        statsData[i] =
            new Object[] {label, new Integer((int) xstats[i]), new Integer((int) ystats[i])};
      } else {
        switch (i) {
          case 0:
            label = ToolsRes.getString("Table.Entry.Max");
            break; //$NON-NLS-1$
          case 1:
            label = ToolsRes.getString("Table.Entry.Min");
            break; //$NON-NLS-1$
          case 2:
            label = ToolsRes.getString("Table.Entry.Mean");
            break; //$NON-NLS-1$
          case 3:
            label = ToolsRes.getString("Table.Entry.StandardDev");
            break; //$NON-NLS-1$
          case 4:
            label = ToolsRes.getString("Table.Entry.StandardError"); // $NON-NLS-1$
        }
        statsData[i] = new Object[] {label, new Double(xstats[i]), new Double(ystats[i])};
      }
    }
    // set and configure table model and header
    setModel(tableModel);
    setGridColor(Color.blue);
    setEnabled(false);
    setTableHeader(null); // no table header
    labelRenderer = new LabelRenderer();
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    setDefaultRenderer(Double.class, new ScientificRenderer(3));
    ListSelectionModel selectionModel = dataTable.getSelectionModel();
    selectionModel.addListSelectionListener(
        new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent e) {
            Dataset workingData = dataTable.getWorkingData();
            double[] xstats = getStatistics(workingData.getXPoints());
            double[] ystats = getStatistics(workingData.getValidYPoints());
            int i = 0;
            for (; i < xstats.length - 1; i++) {
              statsData[i][1] = new Double(xstats[i]);
              statsData[i][2] = new Double(ystats[i]);
            }
            statsData[i][1] = new Integer((int) xstats[i]);
            statsData[i][2] = new Integer((int) ystats[i]);
            refreshTable();
          }
        });
    refreshCellWidths();
  }
Beispiel #17
0
 public void cleanUp() {
   if (lsm != null) {
     lsm.removeListSelectionListener(selListener);
   }
 }
  public ListSelectionDemo() {
    super(new BorderLayout());

    String[] listData = {"one", "two", "three", "four", "five", "six", "seven"};
    String[] columnNames = {"French", "Spanish", "Italian"};
    list = new JList(listData);

    listSelectionModel = list.getSelectionModel();
    listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
    JScrollPane listPane = new JScrollPane(list);

    JPanel controlPane = new JPanel();
    String[] modes = {
      "SINGLE_SELECTION", "SINGLE_INTERVAL_SELECTION", "MULTIPLE_INTERVAL_SELECTION"
    };

    final JComboBox comboBox = new JComboBox(modes);
    comboBox.setSelectedIndex(2);
    comboBox.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String newMode = (String) comboBox.getSelectedItem();
            if (newMode.equals("SINGLE_SELECTION")) {
              listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            } else if (newMode.equals("SINGLE_INTERVAL_SELECTION")) {
              listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            } else {
              listSelectionModel.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
            }
            output.append("----------" + "Mode: " + newMode + "----------" + newline);
          }
        });
    controlPane.add(new JLabel("Selection mode:"));
    controlPane.add(comboBox);

    // Build output area.
    output = new JTextArea(1, 10);
    output.setEditable(false);
    JScrollPane outputPane =
        new JScrollPane(
            output,
            ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    // Do the layout.
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    add(splitPane, BorderLayout.CENTER);

    JPanel topHalf = new JPanel();
    topHalf.setLayout(new BoxLayout(topHalf, BoxLayout.LINE_AXIS));
    JPanel listContainer = new JPanel(new GridLayout(1, 1));
    listContainer.setBorder(BorderFactory.createTitledBorder("List"));
    listContainer.add(listPane);

    topHalf.setBorder(BorderFactory.createEmptyBorder(5, 5, 0, 5));
    topHalf.add(listContainer);
    // topHalf.add(tableContainer);

    topHalf.setMinimumSize(new Dimension(100, 50));
    topHalf.setPreferredSize(new Dimension(100, 110));
    splitPane.add(topHalf);

    JPanel bottomHalf = new JPanel(new BorderLayout());
    bottomHalf.add(controlPane, BorderLayout.PAGE_START);
    bottomHalf.add(outputPane, BorderLayout.CENTER);
    // XXX: next line needed if bottomHalf is a scroll pane:
    // bottomHalf.setMinimumSize(new Dimension(400, 50));
    bottomHalf.setPreferredSize(new Dimension(450, 135));
    splitPane.add(bottomHalf);
  }
Beispiel #19
0
  public fileBackupProgram(JFrame frame) {
    super(new BorderLayout());
    this.frame = frame;

    errorDialog = new CustomDialog(frame, "Please enter a new name for the error log", this);
    errorDialog.pack();

    moveDialog = new CustomDialog(frame, "Please enter a new name for the move log", this);
    moveDialog.pack();

    printer = new FilePrinter();
    timers = new ArrayList<>();
    log = new JTextArea(5, 20);
    log.setMargin(new Insets(5, 5, 5, 5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);
    Object obj;
    copy = true;
    listModel = new DefaultListModel();
    // destListModel = new DefaultListModel();
    directoryList = new directoryStorage();

    // Create a file chooser
    fc = new JFileChooser();

    // Create the menu bar.
    menuBar = new JMenuBar();

    // Build the first menu.
    menu = new JMenu("File");
    menu.getAccessibleContext()
        .setAccessibleDescription("The only menu in this program that has menu items");
    menuBar.add(menu);

    editError = new JMenuItem("Save Error Log As...");
    editError
        .getAccessibleContext()
        .setAccessibleDescription("Change the name of the error log file");
    editError.addActionListener(new ErrorListener());
    menu.add(editError);

    editMove = new JMenuItem("Save Move Log As...");
    editMove
        .getAccessibleContext()
        .setAccessibleDescription("Change the name of the move log file");
    editMove.addActionListener(new MoveListener());
    menu.add(editMove);

    exit = new JMenuItem("Exit");
    exit.getAccessibleContext().setAccessibleDescription("Exit the Program");
    exit.addActionListener(new CloseListener());
    menu.add(exit);
    frame.setJMenuBar(menuBar);
    // Uncomment one of the following lines to try a different
    // file selection mode.  The first allows just directories
    // to be selected (and, at least in the Java look and feel,
    // shown).  The second allows both files and directories
    // to be selected.  If you leave these lines commented out,
    // then the default mode (FILES_ONLY) will be used.
    //
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    // fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    openButton = new JButton(openString);
    openButton.setActionCommand(openString);
    openButton.addActionListener(new OpenListener());

    destButton = new JButton(destString);
    destButton.setActionCommand(destString);
    destButton.addActionListener(new DestListener());

    // Create the save button.  We use the image from the JLF
    // Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton(saveString);
    saveButton.setActionCommand(saveString);
    saveButton.addActionListener(new SaveListener());

    URL imageURL = getClass().getResource(greenButtonIcon);
    ImageIcon greenSquare = new ImageIcon(imageURL);
    startButton = new JButton("Start", greenSquare);
    startButton.setSize(60, 20);
    startButton.setHorizontalTextPosition(AbstractButton.LEADING);
    startButton.setActionCommand("Start");
    startButton.addActionListener(new StartListener());

    imageURL = getClass().getResource(redButtonIcon);
    ImageIcon redSquare = new ImageIcon(imageURL);
    stopButton = new JButton("Stop", redSquare);
    stopButton.setSize(60, 20);
    stopButton.setHorizontalTextPosition(AbstractButton.LEADING);
    stopButton.setActionCommand("Stop");
    stopButton.addActionListener(new StopListener());

    copyButton = new JRadioButton("Copy");
    copyButton.setActionCommand("Copy");
    copyButton.setSelected(true);
    copyButton.addActionListener(new RadioListener());

    moveButton = new JRadioButton("Move");
    moveButton.setActionCommand("Move");
    moveButton.addActionListener(new RadioListener());

    ButtonGroup group = new ButtonGroup();
    group.add(copyButton);
    group.add(moveButton);

    // For layout purposes, put the buttons in a separate panel

    JPanel optionPanel = new JPanel();

    GroupLayout layout = new GroupLayout(optionPanel);
    optionPanel.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout.createSequentialGroup().addComponent(copyButton).addComponent(moveButton));
    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(copyButton)
                    .addComponent(moveButton)));

    JPanel buttonPanel = new JPanel(); // use FlowLayout

    layout = new GroupLayout(buttonPanel);
    buttonPanel.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(openButton)
                    .addComponent(optionPanel))
            .addComponent(destButton)
            .addComponent(startButton)
            .addComponent(stopButton)
        // .addComponent(saveButton)
        );
    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(openButton)
                    .addComponent(destButton)
                    .addComponent(startButton)
                    .addComponent(stopButton)
                // .addComponent(saveButton)
                )
            .addComponent(optionPanel));

    buttonPanel.add(optionPanel);
    /*
    buttonPanel.add(openButton);
    buttonPanel.add(destButton);
    buttonPanel.add(startButton);
    buttonPanel.add(stopButton);
    buttonPanel.add(saveButton);
    buttonPanel.add(listLabel);
    buttonPanel.add(copyButton);
    buttonPanel.add(moveButton);
    */
    destButton.setEnabled(false);
    startButton.setEnabled(false);
    stopButton.setEnabled(false);

    // Add the buttons and the log to this panel.

    // add(logScrollPane, BorderLayout.CENTER);

    JLabel listLabel = new JLabel("Monitored Directory:");
    listLabel.setLabelFor(list);

    // Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);
    list.setVisibleRowCount(8);
    JScrollPane listScrollPane = new JScrollPane(list);
    JPanel listPane = new JPanel();
    listPane.setLayout(new BorderLayout());

    listPane.add(listLabel, BorderLayout.PAGE_START);
    listPane.add(listScrollPane, BorderLayout.CENTER);

    listSelectionModel = list.getSelectionModel();
    listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
    // monitored, destination, waitInt, check

    destination = new JLabel("Destination Directory: ");

    waitField = new JFormattedTextField();
    // waitField.setValue(240);
    waitField.setEditable(false);
    waitField.addPropertyChangeListener(new FormattedTextListener());

    waitInt = new JLabel("Wait Interval (in minutes)");
    // waitInt.setLabelFor(waitField);

    checkField = new JFormattedTextField();
    checkField.setSize(1, 10);
    // checkField.setValue(60);
    checkField.setEditable(false);
    checkField.addPropertyChangeListener(new FormattedTextListener());

    check = new JLabel("Check Interval (in minutes)");
    // check.setLabelFor(checkField);

    fireButton = new JButton(fireString);
    fireButton.setActionCommand(fireString);
    fireButton.addActionListener(new FireListener());

    JPanel fieldPane = new JPanel();
    // fieldPane.add(destField);
    layout = new GroupLayout(fieldPane);
    fieldPane.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(waitInt)
                    .addComponent(check))
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(waitField, 60, 60, 60)
                    .addComponent(checkField, 60, 60, 60)));

    layout.setVerticalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(waitInt)
                    .addComponent(waitField))
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(check)
                    .addComponent(checkField)));

    JPanel labelPane = new JPanel();

    labelPane.setLayout(new BorderLayout());

    labelPane.add(destination, BorderLayout.PAGE_START);
    labelPane.add(fieldPane, BorderLayout.CENTER);

    layout = new GroupLayout(labelPane);
    labelPane.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    layout.setHorizontalGroup(
        layout
            .createSequentialGroup()
            .addGroup(
                layout
                    .createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(destination)
                    .addComponent(fieldPane)));

    layout.setVerticalGroup(
        layout.createSequentialGroup().addComponent(destination).addComponent(fieldPane));
    // labelPane.add(destination);
    // labelPane.add(fieldPane);

    try {
      // Read from disk using FileInputStream
      FileInputStream f_in = new FileInputStream(LOG_DIRECTORY + "\\save.data");

      // Read object using ObjectInputStream
      ObjectInputStream obj_in = new ObjectInputStream(f_in);

      // Read an object
      directoryList = (directoryStorage) obj_in.readObject();
      ERROR_LOG_NAME = (String) obj_in.readObject();
      MOVE_LOG_NAME = (String) obj_in.readObject();

      if (ERROR_LOG_NAME instanceof String) {
        printer.changeErrorLogName(ERROR_LOG_NAME);
      }

      if (MOVE_LOG_NAME instanceof String) {
        printer.changeMoveLogName(MOVE_LOG_NAME);
      }

      if (directoryList instanceof directoryStorage) {
        System.out.println("found object");
        // directoryList = (directoryStorage) obj;

        Iterator<Directory> directories = directoryList.getDirectories();
        Directory d;
        while (directories.hasNext()) {
          d = directories.next();

          try {
            listModel.addElement(d.getDirectory().toRealPath());
          } catch (IOException x) {
            printer.printError(x.toString());
          }

          int index = list.getSelectedIndex();
          if (index == -1) {
            list.setSelectedIndex(0);
          }

          index = list.getSelectedIndex();
          Directory dir = directoryList.getDirectory(index);

          destButton.setEnabled(true);
          checkField.setValue(dir.getInterval());
          waitField.setValue(dir.getWaitInterval());
          checkField.setEditable(true);
          waitField.setEditable(true);

          // directoryList.addNewDirectory(d);
          // try {
          // listModel.addElement(d.getDirectory().toString());
          // } catch (IOException x) {
          // printer.printError(x.toString());
          // }

          // timer = new Timer();
          // timer.schedule(new CopyTask(d.directory, d.destination, d.getWaitInterval(), printer,
          // d.copy), 0, d.getInterval());
        }

      } else {
        System.out.println("did not find object");
      }
      obj_in.close();
    } catch (ClassNotFoundException x) {
      printer.printError(x.getLocalizedMessage());
      System.err.format("Unable to read");
    } catch (IOException y) {
      printer.printError(y.getLocalizedMessage());
    }

    // Layout the text fields in a panel.

    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));

    buttonPane.add(fireButton);
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    add(buttonPanel, BorderLayout.PAGE_START);
    add(listPane, BorderLayout.LINE_START);
    // add(destListScrollPane, BorderLayout.CENTER);

    add(fieldPane, BorderLayout.LINE_END);
    add(labelPane, BorderLayout.CENTER);
    add(buttonPane, BorderLayout.PAGE_END);
  }
Beispiel #20
0
  ViewsPane(WordCollection collection) {
    super(null, true, true, false);
    final Messages messages = AppPrefs.getInstance().getMessages();

    // change find label
    setFindButtonLabel(messages.getString("btnFindViews"));

    _collection = collection;
    getList().setModel(new BasicListModel());

    final MainFrame mf = MainFrame.getInstance();
    ListSelectionModel model = getList().getSelectionModel();
    model.addListSelectionListener(
        new ListSelectionListener() {
          public synchronized void valueChanged(ListSelectionEvent evt) {
            try {
              View view = (View) getList().getSelectedValue();
              if (view != null) {
                Setting setting = _collection.getDatabase().getCurrentSetting();
                setting.setViewID(view.getID());
                setting.save();
                mf.updateStatus();
              }
            } catch (DatabaseException e) {
              Dialogs.genericError(e);
            }
          }
        });

    addAddEditDeleteListener(
        new AddEditDeleteListener() {
          public void doAdd(ActionEvent evt) throws DatabaseException {
            final View view = _collection.makeView();
            AddDialog dialog = new AddDialog("lblAddView", view);
            dialog.setVisible(true);
            if (!dialog.isCancelled()) {
              // add default groups and alignments
              AddRunnable task =
                  new AddRunnable() {
                    public void run() {
                      try {
                        ViewDuplicator.makeGroupsAndAlignments(view, view, _collection, false);

                        // update collection view list
                        List views = _collection.getViews();
                        views.add(view);

                        _collection.getDatabase().getCurrentSetting().setViewID(view.getID());
                        refresh();
                      } catch (DatabaseException ex) {
                        exception = ex;
                      }
                    }

                    DatabaseException exception = null;

                    public DatabaseException getException() {
                      return exception;
                    }
                  };
              Messages m = AppPrefs.getInstance().getMessages();
              Dialogs.indeterminateProgressDialog(
                  task,
                  m.getString("pgbWaitString"),
                  m.getString("pgbCurrentTask") + m.getString("lblAddView"));
              if (task.getException()
                  != null) { // so we don't swallow the exception from the other thread.
                throw task.getException();
              }
            }
          }

          public void doCopy(ActionEvent evt) throws DatabaseException {
            ViewDuplicator duplicator =
                new ViewDuplicator((View) getList().getSelectedValue(), _collection);
            TaskDialog dialog = new TaskDialog("lblViewCopy", duplicator);
            dialog.setVisible(true);
            if (!dialog.isCancelled()) {
              // update collection view list
              List views = _collection.getViews();
              View view = duplicator.getDuplicate();
              if (view != null) { // view will be null if attempted duplicate view name.
                views.add(view);
                _collection.getDatabase().getCurrentSetting().setViewID(view.getID());
                refresh();
              }
            }
          }

          public void doDelete(ActionEvent evt) throws DatabaseException {
            View view = (View) getList().getSelectedValue();

            // check for Original view
            View original = _collection.getOriginalView();
            if (view.equals(original)) {
              Dialogs.error(messages.getString("msgErrDeletingOriginalView"));
            } else {
              view.delete();

              // update collection view list
              List views = _collection.getViews();
              views.remove(view);
              changeView(original);

              JSplitPane split = (JSplitPane) getMainComponent();
              int loc = split.getDividerLocation();
              split.setRightComponent(new JLabel(""));
              split.setDividerLocation(loc);
              refresh();
            }
          }

          public void doValidate(ActionEvent evt) {}

          public void doMoveUp(ActionEvent evt) {}

          public void doMoveDown(ActionEvent evt) {}
        });

    getList().setCellRenderer(new ViewNameListCellRenderer());
  }