private void init() {
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setTitle("Strategy Information - " + strategy.getName());

    this.addWindowListener(
        new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
            Dispatcher dispatcher = Dispatcher.getInstance();
            dispatcher.removeListener(StrategyInformationDialog.this);
          }
        });

    JPanel contentPanel = new JPanel(new BorderLayout());
    getContentPane().add(contentPanel, BorderLayout.CENTER);

    JTabbedPane tabbedPane = new JTabbedPane();
    contentPanel.add(tabbedPane, BorderLayout.CENTER);

    JPanel performancePanel = new JPanel(new SpringLayout());
    tabbedPane.addTab("Performance", performancePanel);

    NumberFormat nf2 = NumberFormatterFactory.getNumberFormatter(2);

    PerformanceManager pm = strategy.getPerformanceManager();
    add(performancePanel, "Position", strategy.getPositionManager().getCurrentPosition());
    add(performancePanel, "Trades", pm.getTrades());
    add(performancePanel, "% Profitable", nf2.format(pm.getPercentProfitableTrades()));
    add(performancePanel, "Average trade", nf2.format(pm.getAverageProfitPerTrade()));
    add(performancePanel, "Net Profit", nf2.format(pm.getNetProfit()));
    add(performancePanel, "Max Drawdown", nf2.format(pm.getMaxDrawdown()));
    add(performancePanel, "Profit Factor", nf2.format(pm.getProfitFactor()));
    add(performancePanel, "Kelly", nf2.format(pm.getKellyCriterion()));
    add(performancePanel, "PI", nf2.format(pm.getPerformanceIndex()));
    add(performancePanel, "CPI", nf2.format(pm.getCPI()));
    makeCompactGrid(performancePanel);

    JPanel securityPanel = new JPanel(new SpringLayout());
    tabbedPane.addTab("Instrument", securityPanel);
    add(securityPanel, "Symbol", strategy.getContract().m_symbol);
    add(securityPanel, "Security Type", strategy.getContract().m_secType);
    add(securityPanel, "Exchange", strategy.getContract().m_exchange);
    add(securityPanel, "Multiplier", strategy.getContract().m_multiplier);
    add(securityPanel, "Commission", strategy.getPerformanceManager().getCommission().toString());

    bidAskLabel = new JLabel();
    securityPanel.add(new JLabel("Best bid-ask" + ":"));
    securityPanel.add(bidAskLabel);

    cumBidAskSizesLabel = new JLabel();
    securityPanel.add(new JLabel("Book bid-ask size" + ":"));
    securityPanel.add(cumBidAskSizesLabel);

    makeCompactGrid(securityPanel);

    JPanel parametersPanel = new JPanel(new SpringLayout());
    tabbedPane.addTab("Parameters", parametersPanel);
    StrategyParams params = strategy.getParams();
    add(parametersPanel, "Schedule", strategy.getTradingSchedule().toString());
    for (StrategyParam param : params.getAll()) {
      add(parametersPanel, param.getName(), param.getValue());
    }
    makeCompactGrid(parametersPanel);

    IndicatorManager indicatorManager = strategy.getIndicatorManager();
    if (indicatorManager != null) {
      JPanel indicatorsPanel = new JPanel(new SpringLayout());
      tabbedPane.addTab("Indicators", indicatorsPanel);
      for (Indicator indicator : strategy.getIndicatorManager().getIndicators()) {
        add(indicatorsPanel, indicator.getKey(), indicator.getValue());
      }
      makeCompactGrid(indicatorsPanel);
    }

    getContentPane().setPreferredSize(new Dimension(450, 400));
  }
  /** The main loop for the background thread. It is here that most of the work os orchestrated. */
  public void run() {

    double thisCost = 500.0;
    double oldCost = 0.0;
    double dcost = 500.0;
    int countSame = 0;

    map.update(map.getGraphics());

    while (countSame < 100) {

      generation++;

      int ioffset = matingPopulationSize;
      int mutated = 0;

      // Mate the chromosomes in the favoured population
      // with all in the mating population
      for (int i = 0; i < favoredPopulationSize; i++) {
        Chromosome cmother = chromosomes[i];
        // Select partner from the mating population
        int father = (int) (0.999999 * Math.random() * (double) matingPopulationSize);
        Chromosome cfather = chromosomes[father];

        mutated += cmother.mate(cfather, chromosomes[ioffset], chromosomes[ioffset + 1]);
        ioffset += 2;
      }

      // The new generation is in the matingPopulation area
      // move them to the correct area for sort.
      for (int i = 0; i < matingPopulationSize; i++) {
        chromosomes[i] = chromosomes[i + matingPopulationSize];
        chromosomes[i].calculateCost(cities);
      }

      // Now sort the new mating population
      Chromosome.sortChromosomes(chromosomes, matingPopulationSize);

      double cost = chromosomes[0].getCost();
      dcost = Math.abs(cost - thisCost);
      thisCost = cost;
      double mutationRate = 100.0 * (double) mutated / (double) matingPopulationSize;

      NumberFormat nf = NumberFormat.getInstance();
      nf.setMinimumFractionDigits(2);
      nf.setMinimumFractionDigits(2);

      status.setText(
          "Generation "
              + generation
              + " Cost "
              + (int) thisCost
              + " Mutated "
              + nf.format(mutationRate)
              + "%");

      if ((int) thisCost == (int) oldCost) {
        countSame++;
      } else {
        countSame = 0;
        oldCost = thisCost;
      }
      map.update(map.getGraphics());
    }
    status.setText("Solution found after " + generation + " generations.");
  }
Exemplo n.º 3
0
 static {
   Stroke stroke = new BasicStroke(2);
   selectionShape = stroke.createStrokedShape(hitRect);
   format.setMinimumIntegerDigits(1);
   format.setMinimumFractionDigits(1);
   format.setMaximumFractionDigits(2);
 }
Exemplo n.º 4
0
 /** Return a double parsed from the given string, possibly formatted with a "%" sign */
 public static double parseDouble(String val) throws NumberFormatException, ParseException {
   NumberFormat formatPercent = NumberFormat.getPercentInstance(Locale.US); // for zoom factor
   if (val.indexOf("%") == -1) { // not in percent format !
     return Double.parseDouble(val);
   }
   // else it's a percent format -> parse it
   Number n = formatPercent.parse(val);
   return n.doubleValue();
 }
Exemplo n.º 5
0
  //
  // Sets the frame rate text displayed in the lower left corner.
  //
  void setFrameRateText() {
    NumberFormat nf = NumberFormat.getInstance();

    nf.setMinimumFractionDigits(2);
    nf.setMaximumFractionDigits(2);

    frameRateText.text(
        "frames/sec = " + nf.format((double) frameCount / ((double) (time - lastTime) / 1000.0)));
  }
  /** A class to render numbers in scientific format. */
  class ScientificRenderer extends JLabel implements TableCellRenderer {
    NumberFormat format = NumberFormat.getInstance();

    public ScientificRenderer(int sigfigs) {
      sigfigs = Math.min(sigfigs, 6);
      if (format instanceof DecimalFormat) {
        String pattern = "0.0"; // $NON-NLS-1$
        for (int i = 0; i < sigfigs - 1; i++) {
          pattern += "0"; // $NON-NLS-1$
        }
        pattern += "E0"; // $NON-NLS-1$
        ((DecimalFormat) format).applyPattern(pattern);
      }
    }

    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      setFont(
          getDefaultRenderer(String.class)
              .getTableCellRendererComponent(DatasetStatisticsTable.this, "a", false, false, 0, 0)
              .getFont()); //$NON-NLS-1$
      setText(format.format(value));
      setHorizontalAlignment(SwingConstants.TRAILING);
      return this;
    }
  }
Exemplo n.º 7
0
  public void label(Graphics g, String var, double m, String units, int adj) {
    g.setColor(Color.black);
    g.setFont(font);
    String s = format.format(m);

    g.drawString(var + ": " + s, x + 5, y + h / 2 - 5);
    g.drawString(units, x + w - adj, y + h / 2 - 5);
  }
Exemplo n.º 8
0
 /**
  * Formats the specified value and enters it in the text field.
  *
  * @param value the value to be entered
  */
 public void setValue(double value) {
   if (!isVisible()) return;
   if (minValue != null) value = Math.max(value, minValue.doubleValue());
   if (maxValue != null) value = Math.min(value, maxValue.doubleValue());
   setFormatFor(value);
   setText(format.format(value));
   prevValue = value;
 }
Exemplo n.º 9
0
  public void updateStates() {
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);

    try {
      // System.out.println("getting variables.");
      status = cryo.cryoGetStatusCORBA();
      frame.lblStatus.setText(statusString[status] + " ");
      heater = cryo.cryoGetHeaterCORBA();
      frame.lblHeater.setText(nf.format(heater) + " watts");
      temp = cryo.cryoGetTempCORBA();
      frame.lblTemp.setText(nf.format(temp) + " deg");
      cli = cryo.cryoGetCliCORBA();
      if (Double.isNaN(cli)) {
        frame.lblCli.setText(cli + " ");
      } else frame.lblCli.setText(nf.format(cli) + " ");

    } catch (org.omg.CORBA.COMM_FAILURE cf) {
      // stop thread and try to reconnect to the server
      frame.lblStatus.setText("FAILURE!! Server connected?");
      stop = true;
      return;
    }
  }
Exemplo n.º 10
0
 public Component getTableCellRendererComponent(
     JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
   setFont(
       getDefaultRenderer(String.class)
           .getTableCellRendererComponent(DatasetStatisticsTable.this, "a", false, false, 0, 0)
           .getFont()); //$NON-NLS-1$
   setText(format.format(value));
   setHorizontalAlignment(SwingConstants.TRAILING);
   return this;
 }
Exemplo n.º 11
0
 /**
  * Gets the value from the text field.
  *
  * @return the value
  */
 public double getValue() {
   if (getText().equals(format.format(prevValue))) return prevValue;
   double retValue;
   try {
     retValue = format.parse(getText()).doubleValue();
     if (minValue != null && retValue < minValue.doubleValue()) {
       setValue(minValue.doubleValue());
       return minValue.doubleValue();
     }
     if (maxValue != null && retValue > maxValue.doubleValue()) {
       setValue(maxValue.doubleValue());
       return maxValue.doubleValue();
     }
   } catch (ParseException e) {
     Toolkit.getDefaultToolkit().beep();
     setValue(prevValue);
     return prevValue;
   }
   return retValue;
 }
Exemplo n.º 12
0
 /**
  * @return a double parsed from the value associated with the given key in the given Properties.
  *     returns "def" in key wasn't found, or if a parsing error occured. If "value" contains a "%"
  *     sign, we use a <code>NumberFormat.getPercentInstance</code> to convert it to a double.
  */
 public static double parseProperty(Properties preferences, String key, double def) {
   NumberFormat formatPercent = NumberFormat.getPercentInstance(Locale.US); // for zoom factor
   String val = preferences.getProperty(key);
   if (val == null) return def;
   if (val.indexOf("%") == -1) { // not in percent format !
     try {
       return Double.parseDouble(val);
     } catch (NumberFormatException nfe) {
       nfe.printStackTrace();
       return def;
     }
   }
   // else it's a percent format -> parse it
   try {
     Number n = formatPercent.parse(val);
     return n.doubleValue();
   } catch (ParseException ex) {
     ex.printStackTrace();
     return def;
   }
 }
  public void init() {
    // 添加按钮
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(okButton);

    mainPanel.setLayout(new GridLayout(0, 3));
    mainWin.add(mainPanel, BorderLayout.CENTER);

    JFormattedTextField intField0 =
        new JFormattedTextField(
            new InternationalFormatter(NumberFormat.getIntegerInstance()) {
              protected DocumentFilter getDocumentFilter() {
                return new NumberFilter();
              }
            });
    intField0.setValue(100);
    addRow("只接受数字的文本框", intField0);

    JFormattedTextField intField1 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField1.setValue(new Integer(100));
    // 添加输入校验器
    intField1.setInputVerifier(new FormattedTextFieldVerifier());
    addRow("带输入校验器的文本框", intField1);

    // 创建自定义格式器对象
    IPAddressFormatter ipFormatter = new IPAddressFormatter();
    ipFormatter.setOverwriteMode(false);
    // 以自定义格式器对象创建格式化文本框
    JFormattedTextField ipField = new JFormattedTextField(ipFormatter);
    ipField.setValue(new byte[] {(byte) 192, (byte) 168, 4, 1});
    addRow("IP地址格式", ipField);

    mainWin.add(buttonPanel, BorderLayout.SOUTH);
    mainWin.pack();
    mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainWin.setVisible(true);
  }
  /** Update the statistic */
  public void setStats(int mi, double me, int ma, double sd) {
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(2);
    nf.setMinimumFractionDigits(2);
    nf.setGroupingUsed(false);

    min.setText(Integer.toString(mi));
    max.setText(Integer.toString(ma));

    String s = nf.format(me);
    mean.setText(s);
    s = nf.format(sd);
    stdDev.setText(s);
  }
Exemplo n.º 15
0
/**
 * A Step is associated with a single frame of a TTrack. It contains an array of TPoints that define
 * its image data and a Footprint that determines its screen appearance. This is an abstract class
 * and cannot be instantiated directly.
 *
 * @author Douglas Brown
 */
public abstract class Step implements Cloneable {

  // static fields
  protected static Rectangle hitRect = new Rectangle(-4, -4, 8, 8);
  protected static Shape selectionShape;
  protected static AffineTransform transform = new AffineTransform();
  protected static NumberFormat format = NumberFormat.getNumberInstance(Locale.US);
  protected static Font textLayoutFont = new JTextField().getFont();
  protected static FontRenderContext frc =
      new FontRenderContext(
          null, // no AffineTransform
          false, // no antialiasing
          false); // no fractional metrics

  static {
    Stroke stroke = new BasicStroke(2);
    selectionShape = stroke.createStrokedShape(hitRect);
    format.setMinimumIntegerDigits(1);
    format.setMinimumFractionDigits(1);
    format.setMaximumFractionDigits(2);
  }

  // instance fields
  protected TTrack track; // track this belongs to
  protected int n; // frame number
  protected Footprint footprint; // determines appearance
  protected TPoint[] points; // defines image data
  protected Point[] screenPoints; // for transform conversions
  protected boolean valid; // invalid steps not drawn
  protected Map<TrackerPanel, Mark> marks // tracker panel to Mark
      = new HashMap<TrackerPanel, Mark>();
  protected int defaultIndex = 0; // array index of default TPoint
  protected boolean dataVisible = true; // true if visible in plots, tables

  /**
   * Constructs a Step with the specified frame number.
   *
   * @param track the track
   * @param n the frame number
   */
  protected Step(TTrack track, int n) {
    this.track = track;
    this.n = n;
  }

  /**
   * Gets the frame number.
   *
   * @return the frame number
   */
  public int getFrameNumber() {
    return n;
  }

  /**
   * Sets the footprint.
   *
   * @param footprint the footprint
   */
  public void setFootprint(Footprint footprint) {
    this.footprint = footprint;
  }

  /**
   * Gets the track.
   *
   * @return the track
   */
  public TTrack getTrack() {
    return track;
  }

  /**
   * Gets the array of TPoints contained in this step.
   *
   * @return the TPoints array
   */
  public TPoint[] getPoints() {
    return points;
  }

  /**
   * Gets the index of a point in the points[] array.
   *
   * @param p the point
   * @return the index, or -1 if not found
   */
  public int getPointIndex(TPoint p) {
    for (int i = 0; i < points.length; i++) {
      if (points[i] == p) return i;
    }
    return -1;
  }

  /**
   * Gets the default point. The default point is the point initially selected when the step is
   * created.
   *
   * @return the default TPoint
   */
  public TPoint getDefaultPoint() {
    return points[defaultIndex];
  }

  /**
   * Sets the default point index. This defines the index of the points array used to get the point
   * initially selected when the step is created.
   *
   * @param index the index
   */
  public void setDefaultPointIndex(int index) {
    index = Math.min(index, points.length - 1);
    defaultIndex = Math.max(0, index);
  }

  /**
   * Erases this on the specified tracker panel. Erasing adds the current bounds to the dirty region
   * and nulls the step's mark to trigger creation of a new one.
   *
   * @param trackerPanel the tracker panel
   */
  public void erase(TrackerPanel trackerPanel) {
    if (marks.get(trackerPanel) == null) return; // already dirty
    trackerPanel.addDirtyRegion(getBounds(trackerPanel)); // old bounds
    marks.put(trackerPanel, null); // triggers new mark
  }

  /**
   * Erases and remarks this on the specified tracker panel. Remarking creates a new mark for the
   * step and adds both the old and new bounds to the tracker panel's dirty region.
   *
   * @param trackerPanel the tracker panel
   */
  public void remark(TrackerPanel trackerPanel) {
    erase(trackerPanel);
    trackerPanel.addDirtyRegion(getBounds(trackerPanel)); // new bounds
  }

  /**
   * Repaints this on the specified tracker panel. Repainting a step first remarks it and then
   * requests a repaint of the panel's dirty region.
   *
   * @param trackerPanel the tracker panel
   */
  public void repaint(TrackerPanel trackerPanel) {
    remark(trackerPanel);
    trackerPanel.repaintDirtyRegion();
  }

  /** Erases this on all tracker panels. */
  public void erase() {
    Iterator<TrackerPanel> it = marks.keySet().iterator();
    while (it.hasNext()) erase(it.next());
  }

  /** Remarks this on all tracker panels. */
  public void remark() {
    Iterator<TrackerPanel> it = marks.keySet().iterator();
    while (it.hasNext()) remark(it.next());
  }

  /** Repaints this on all tracker panels. */
  public void repaint() {
    Iterator<TrackerPanel> it = marks.keySet().iterator();
    while (it.hasNext()) repaint(it.next());
  }

  /**
   * Draws this step.
   *
   * @param panel the drawing panel requesting the drawing
   * @param g the graphics context on which to draw
   */
  public void draw(DrawingPanel panel, Graphics g) {
    if (track.trackerPanel == panel) {
      AutoTracker autoTracker = track.trackerPanel.getAutoTracker();
      if (autoTracker.isInteracting(track)) return;
    }
    TrackerPanel trackerPanel = (TrackerPanel) panel;
    boolean highlighted = (trackerPanel.getFrameNumber() == n);
    if (trackerPanel.autoTracker != null
        && trackerPanel.autoTracker.getWizard().isVisible()
        && trackerPanel.autoTracker.getTrack() == track) {
      highlighted = false;
    }
    getMark(trackerPanel).draw((Graphics2D) g, highlighted);
  }

  /**
   * Finds the Interactive located at the specified pixel position.
   *
   * @param panel the drawing panel
   * @param xpix the x pixel position
   * @param ypix the y pixel position
   * @return the TPoint that is hit, or null
   */
  public Interactive findInteractive(DrawingPanel panel, int xpix, int ypix) {
    boolean highlighted = (track.trackerPanel.getFrameNumber() == getFrameNumber());
    AutoTracker autoTracker = track.trackerPanel.getAutoTracker();
    TrackerPanel trackerPanel = (TrackerPanel) panel;
    setHitRectCenter(xpix, ypix);
    for (int i = 0; i < points.length; i++) {
      if (points[i] == null || Double.isNaN(points[i].getX())) continue;
      if (hitRect.contains(points[i].getScreenPosition(trackerPanel))) {
        if (highlighted && autoTracker.isDrawingKeyFrameFor(track, i)) return null;
        return points[i];
      }
    }
    return null;
  }

  /**
   * Gets the screen bounds of this step on the specified tracker panel.
   *
   * @param trackerPanel the tracker panel drawing the step
   * @return the bounding rectangle
   */
  public Rectangle getBounds(TrackerPanel trackerPanel) {
    boolean highlighted = (trackerPanel.getFrameNumber() == n);
    return getMark(trackerPanel).getBounds(highlighted);
  }

  /**
   * Gets the mark for the specified panel.
   *
   * @param trackerPanel the tracker panel
   * @return the mark
   */
  protected Mark getMark(TrackerPanel trackerPanel) {
    Mark mark = marks.get(trackerPanel);
    TPoint selection = null;
    if (mark == null) {
      selection = trackerPanel.getSelectedPoint();
      Point p = null;
      valid = true; // assume true
      for (int n = 0; n < points.length; n++) {
        if (!valid) continue;
        // determine if point is valid (ie not NaN)
        valid = valid && !Double.isNaN(points[n].getX()) && !Double.isNaN(points[n].getY());
        screenPoints[n] = points[n].getScreenPosition(trackerPanel);
        if (valid && selection == points[n]) p = screenPoints[n];
      }
      mark = footprint.getMark(screenPoints);
      if (p != null) { // point is selected, so draw selection shape
        transform.setToTranslation(p.x, p.y);
        int scale = FontSizer.getIntegerFactor();
        if (scale > 1) {
          transform.scale(scale, scale);
        }
        final Color color = footprint.getColor();
        final Mark stepMark = mark;
        final Shape selectedShape = transform.createTransformedShape(selectionShape);
        mark =
            new Mark() {
              public void draw(Graphics2D g, boolean highlighted) {
                stepMark.draw(g, false);
                Paint gpaint = g.getPaint();
                g.setPaint(color);
                g.fill(selectedShape);
                g.setPaint(gpaint);
              }

              public Rectangle getBounds(boolean highlighted) {
                Rectangle bounds = selectedShape.getBounds();
                bounds.add(stepMark.getBounds(false));
                return bounds;
              }
            };
      }
      final Mark theMark = mark;
      mark =
          new Mark() {
            public void draw(Graphics2D g, boolean highlighted) {
              if (!valid) return;
              theMark.draw(g, false);
            }

            public Rectangle getBounds(boolean highlighted) {
              return theMark.getBounds(highlighted);
            }
          };
      marks.put(trackerPanel, mark);
    }
    return mark;
  }

  /**
   * Returns a String describing this step.
   *
   * @return a descriptive string
   */
  public String toString() {
    return "Step " + n; // $NON-NLS-1$
  }

  /**
   * Clones this Step.
   *
   * @return a clone of this step
   */
  public Object clone() {
    try {
      Step step = (Step) super.clone();
      step.points = new TPoint[points.length];
      step.screenPoints = new Point[points.length];
      step.marks = new HashMap<TrackerPanel, Mark>();
      return step;
    } catch (CloneNotSupportedException ex) {
      ex.printStackTrace();
    }
    return null;
  }

  /**
   * Centers the hit testing rectangle on the specified screen point.
   *
   * @param xpix the x pixel position
   * @param ypix the y pixel position
   */
  protected void setHitRectCenter(int xpix, int ypix) {
    hitRect.setLocation(xpix - hitRect.width / 2, ypix - hitRect.height / 2);
  }

  /**
   * Gets the step length. Default length is 1.
   *
   * @return the length of the points array
   */
  public static int getLength() {
    return 1;
  }

  /** An inner superclass of all handles. */
  class Handle extends TPoint {

    /**
     * Constructs a Handle with specified image coordinates.
     *
     * @param x the x coordinate
     * @param y the y coordinate
     */
    public Handle(double x, double y) {
      super(x, y);
    }

    /**
     * Sets the position of this handle on the line nearest the specified screen position.
     * Subclasses must override.
     *
     * @param xScreen the x screen position
     * @param yScreen the y screen position
     * @param trackerPanel the trackerPanel drawing this step
     */
    public void setPositionOnLine(int xScreen, int yScreen, TrackerPanel trackerPanel) {}
  }
}
Exemplo n.º 16
0
/**
 * This is a JTextField that accepts only numbers.
 *
 * @author Douglas Brown
 * @version 1.0
 */
public class NumberField extends JTextField {

  // instance fields
  protected NumberFormat format = NumberFormat.getInstance();
  protected double prevValue;
  protected Double maxValue;
  protected Double minValue;

  /**
   * Constructs a NumberField.
   *
   * @param columns the number of character columns
   */
  public NumberField(int columns) {
    super(columns);
  }

  /**
   * Gets the value from the text field.
   *
   * @return the value
   */
  public double getValue() {
    if (getText().equals(format.format(prevValue))) return prevValue;
    double retValue;
    try {
      retValue = format.parse(getText()).doubleValue();
      if (minValue != null && retValue < minValue.doubleValue()) {
        setValue(minValue.doubleValue());
        return minValue.doubleValue();
      }
      if (maxValue != null && retValue > maxValue.doubleValue()) {
        setValue(maxValue.doubleValue());
        return maxValue.doubleValue();
      }
    } catch (ParseException e) {
      Toolkit.getDefaultToolkit().beep();
      setValue(prevValue);
      return prevValue;
    }
    return retValue;
  }

  /**
   * Formats the specified value and enters it in the text field.
   *
   * @param value the value to be entered
   */
  public void setValue(double value) {
    if (!isVisible()) return;
    if (minValue != null) value = Math.max(value, minValue.doubleValue());
    if (maxValue != null) value = Math.min(value, maxValue.doubleValue());
    setFormatFor(value);
    setText(format.format(value));
    prevValue = value;
  }

  /**
   * Sets the resolution for this number field.
   *
   * @param delta the change in value that must be resolvable
   */
  public void setResolution(double delta) {
    /** implemented in subclasses */
  }

  /**
   * Sets a minimum value for this field.
   *
   * @param min the minimum allowed value
   */
  public void setMinValue(double min) {
    minValue = new Double(min);
  }

  /**
   * Sets a maximum value for this field.
   *
   * @param max the maximum allowed value
   */
  public void setMaxValue(double max) {
    maxValue = new Double(max);
  }

  /**
   * Gets the format for this field.
   *
   * @return the format
   */
  public NumberFormat getFormat() {
    return format;
  }

  /**
   * Sets the format for a specified value. Subclasses may override this to modify the format before
   * displaying the value.
   *
   * @param value the value to be displayed
   */
  public void setFormatFor(double value) {
    /** implemented in subclasses */
  }
}
Exemplo n.º 17
0
  public FormatTestFrame() {
    JPanel buttonPanel = new JPanel();
    okButton = new JButton("Ok");
    buttonPanel.add(okButton);
    add(buttonPanel, BorderLayout.SOUTH);

    mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout(0, 3));
    add(mainPanel, BorderLayout.CENTER);

    JFormattedTextField intField = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField.setValue(new Integer(100));
    addRow("Number:", intField);

    JFormattedTextField intField2 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField2.setValue(new Integer(100));
    intField2.setFocusLostBehavior(JFormattedTextField.COMMIT);
    addRow("Number (Commit behavior):", intField2);

    JFormattedTextField intField3 =
        new JFormattedTextField(
            new InternationalFormatter(NumberFormat.getIntegerInstance()) {
              protected DocumentFilter getDocumentFilter() {
                return filter;
              }
            });
    intField3.setValue(new Integer(100));
    addRow("Filtered Number", intField3);

    JFormattedTextField intField4 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField4.setValue(new Integer(100));
    intField4.setInputVerifier(
        new InputVerifier() {
          public boolean verify(JComponent component) {
            JFormattedTextField field = (JFormattedTextField) component;
            return field.isEditValid();
          }
        });
    addRow("Verified Number:", intField4);

    JFormattedTextField currencyField = new JFormattedTextField(NumberFormat.getCurrencyInstance());
    currencyField.setValue(new Double(10));
    addRow("Currency:", currencyField);

    JFormattedTextField dateField = new JFormattedTextField(DateFormat.getDateInstance());
    dateField.setValue(new Date());
    addRow("Date (default):", dateField);

    DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT);
    format.setLenient(false);
    JFormattedTextField dateField2 = new JFormattedTextField(format);
    dateField2.setValue(new Date());
    addRow("Date (short, not lenient):", dateField2);

    try {
      DefaultFormatter formatter = new DefaultFormatter();
      formatter.setOverwriteMode(false);
      JFormattedTextField urlField = new JFormattedTextField(formatter);
      urlField.setValue(new URL("http://java.sun.com"));
      addRow("URL:", urlField);
    } catch (MalformedURLException ex) {
      ex.printStackTrace();
    }

    try {
      MaskFormatter formatter = new MaskFormatter("###-##-####");
      formatter.setPlaceholderCharacter('0');
      JFormattedTextField ssnField = new JFormattedTextField(formatter);
      ssnField.setValue("078-05-1120");
      addRow("SSN Mask:", ssnField);
    } catch (ParseException ex) {
      ex.printStackTrace();
    }

    JFormattedTextField ipField = new JFormattedTextField(new IPAddressFormatter());
    ipField.setValue(new byte[] {(byte) 130, 65, 86, 66});
    addRow("IP Address:", ipField);
    pack();
  }
  public MainCitiesCriteriaPanel() {
    super(new BorderLayout());

    CountryController countryc = Application.getCountryController();
    CitiesController citiesc = Application.getCitiesController();
    countryName = Application.getCountryName();

    label = new JLabel();
    labelPanel = new JPanel();
    labelPanel.add(label);

    label.setText("Criteria to select main cities for " + countryName.replaceAll("_", " "));

    listModel = new DefaultListModel();

    Iterator<HashMap<String, String>> iter = citiesc.getToponymTypesIterator();
    while (iter.hasNext()) {
      String topTypeName = iter.next().get("code");
      listModel.addElement(topTypeName);
    }
    list = new JList(listModel);
    list.addListSelectionListener(this);
    listPanel = new JScrollPane(list);

    NumberFormat nCitiesFormat = NumberFormat.getInstance();
    nCitiesFormat.setMaximumFractionDigits(0);
    nCitiesFormat.setMaximumIntegerDigits(4);

    NumberFormat distFormat = NumberFormat.getInstance();
    distFormat.setMaximumFractionDigits(0);
    distFormat.setMaximumIntegerDigits(3);

    nCitiesField = new JFormattedTextField(nCitiesFormat);
    distField = new JFormattedTextField(distFormat);

    nCitiesField.setMaximumSize(new Dimension(50, 1));
    distField.setMaximumSize(new Dimension(50, 1));

    rb1 = new JRadioButton("Filter by type", true);
    rb2 = new JRadioButton("Filter by number", false);
    rb3 = new JRadioButton("Filter by distance to the borders (km)", false);

    ButtonGroup bgroup = new ButtonGroup();

    bgroup.add(rb1);
    bgroup.add(rb2);
    bgroup.add(rb3);

    JPanel radioPanel = new JPanel();

    radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
    radioPanel.add(rb1);
    radioPanel.add(listPanel);
    radioPanel.add(rb2);
    radioPanel.add(nCitiesField);
    radioPanel.add(rb3);
    radioPanel.add(distField);

    submit = new JButton();
    back = new JButton();

    submit.setText("OK");
    back.setText("GO BACK");
    submit.addActionListener(this);
    back.addActionListener(this);

    buttonPanel = new JPanel();
    buttonPanel.add(back);
    buttonPanel.add(submit);

    add(labelPanel, BorderLayout.NORTH);
    add(radioPanel, BorderLayout.CENTER);
    add(buttonPanel, BorderLayout.SOUTH);
  }