private void _scrollPaneContactList_scrollDown(ActionEvent actionEvent) {
   if (_listContactList.getLastVisibleIndex() + _listContactList.getVisibleRowCount()
       < _listContactList.getModel().getSize())
     _listContactList.ensureIndexIsVisible(
         _listContactList.getLastVisibleIndex() + _listContactList.getVisibleRowCount());
   else _listContactList.ensureIndexIsVisible(_listContactList.getModel().getSize());
 }
Example #2
0
  @Override
  public void setFont(Font font) {
    if (font == null) font = txtSample.getFont();

    fontList.setSelectedValue(font.getName(), true);
    fontList.ensureIndexIsVisible(fontList.getSelectedIndex());
    sizeList.setSelectedValue("" + font.getSize(), true);
    sizeList.ensureIndexIsVisible(sizeList.getSelectedIndex());

    cbBold.setSelected(font.isBold());
    cbItalic.setSelected(font.isItalic());
  }
Example #3
0
 protected void highlightFirstResult() {
   if (resultsList.getModel().getSize() > 0) {
     resultsList.setSelectedIndex(0);
     resultsList.ensureIndexIsVisible(0);
     resultsList.requestFocus();
   }
 }
Example #4
0
  /**
   * Shows a string message in the client's log with the specified priority
   *
   * @param message
   * @param priority
   */
  public void show(String message, Priority priority) {
    switch (priority) {
      case LOW:
        backGC.add(Color.white);
        break;
      case NORMAL:
        backGC.add(Color.LIGHT_GRAY);
        break;
      case HIGH:
        backGC.add(Color.red);
        break;
      case SEVERE:
        backGC.add(Color.red);
        break;
    }

    if (priority.equals(Priority.SEVERE)) {
      foreGC.add(Color.white);
    } else {
      foreGC.add(Color.black);
    }

    lastMessage = message;

    listModel.addElement(formatMsg(message));
    render.setElements(backGC, foreGC);
    counter++;

    logText.ensureIndexIsVisible(logText.getLastVisibleIndex() + 1);
  }
Example #5
0
 private void showStack(ThreadInfo tinfo, int selectFrame) {
   StackTraceListModel model = new StackTraceListModel(tinfo);
   stackModel = model;
   list.setModel(stackModel);
   list.setSelectedIndex(selectFrame);
   list.ensureIndexIsVisible(selectFrame);
 }
Example #6
0
 public final void setCode(String code) {
   int idx = filteredData.indexOf(code);
   if (idx != -1) {
     selectionList.setSelectedIndex(idx);
     selectionList.ensureIndexIsVisible(idx);
   }
 }
Example #7
0
 /** TODO use model instead of model in view */
 void findExpand(Order param) {
   if (param == Order.Ascent) {
     int index;
     if (mainView.isSelectionEmpty()) {
       index = 0;
     } else {
       index = mainView.getSelectedIndex();
     }
     ListModel model = mainView.getModel();
     while (index++ < model.getSize() - 1) {
       if (((Line) model.getElementAt(index)).getFlag() == Line.Type.PLAIN) {
         break;
       }
     }
     while (index < model.getSize()) {
       if (((Line) model.getElementAt(index)).getFlag() != Line.Type.PLAIN) {
         mainView.setSelectedIndex(index);
         mainView.ensureIndexIsVisible(index);
         break;
       }
       index++;
     }
   } else {
     ListModel model = mainView.getModel();
     int index;
     if (mainView.isSelectionEmpty()) {
       index = model.getSize();
     } else {
       index = mainView.getSelectedIndex();
     }
     while (index-- > 0) {
       if (((Line) model.getElementAt(index)).getFlag() == Line.Type.PLAIN) {
         break;
       }
     }
     while (index >= 0) {
       if (((Line) model.getElementAt(index)).getFlag() != Line.Type.PLAIN) {
         mainView.setSelectedIndex(index);
         mainView.ensureIndexIsVisible(index);
         break;
       }
       index--;
     }
   }
   mainView.repaint(); // TODO for popup menu garbage
 }
  private void initComponents(Font font) {
    fontList.setSelectedValue(font.getFamily(), true);
    fontList.ensureIndexIsVisible(fontList.getSelectedIndex());
    fontListValueChanged(null);

    int size = font.getSize();
    int sizeListSize = sizeList.getModel().getSize();
    int distance = Integer.MAX_VALUE;
    int nearestIndex = -1;
    for (int i = 0; i < sizeListSize; ++i) {
      int value = Integer.parseInt((String) sizeList.getModel().getElementAt(i));
      int d = Math.abs(value - size);
      if (d < distance) {
        nearestIndex = i;
        distance = d;
      }
    }
    if (nearestIndex >= 0) {
      sizeList.setSelectedIndex(nearestIndex);
    } else {
      sizeList.setSelectedValue("12", true);
    }
    sizeList.ensureIndexIsVisible(sizeList.getSelectedIndex());
    sizeListValueChanged(null);

    int style = font.getStyle();
    String selectedValue = null;
    switch (style) {
      case Font.PLAIN:
        selectedValue = PLAIN;
        break;
      case Font.BOLD:
        selectedValue = BOLD;
        break;
      case Font.ITALIC:
        selectedValue = ITALIC;
        break;
      default:
        selectedValue = BOLD_ITALIC;
        break;
    }
    styleList.setSelectedValue(selectedValue, true);
    styleList.ensureIndexIsVisible(styleList.getSelectedIndex());
    styleListValueChanged(null);
  }
Example #9
0
  private void setSelectedIndex(int index) {
    if (index == -1) {
      list.getSelectionModel().clearSelection();
    } else if (list.getModel().getSize() != 0) {
      list.setSelectedIndex(index);

      list.ensureIndexIsVisible(index);
    }
  }
Example #10
0
 public void setPc(int pc) {
   Integer lineNum = pcToLine.get(pc);
   if (lineNum != null) {
     irLines.ensureIndexIsVisible(lineNum);
     irLines.setSelectedIndex(lineNum);
   } else {
     removeSelection();
   }
 }
  /**
   * Set the selected element.
   *
   * @param element the selected element.
   */
  public void setElements(Vector elements) {
    model = new ElementListModel(elements);

    list.setModel(model);

    if (model.getSize() > 0) {
      list.setSelectedIndex(0);
      list.ensureIndexIsVisible(0);
    }
  }
Example #12
0
 private void updateFilter() {
   filteredData.clear();
   String filterTxt = filter.getText().trim().toLowerCase(Locale.ENGLISH);
   for (String code : data) {
     if (code.toLowerCase(Locale.ENGLISH).contains(filterTxt)) {
       filteredData.add(code);
     }
   }
   model.fireContentsChanged();
   int idx = filteredData.indexOf(lastCode);
   if (idx == -1) {
     selectionList.clearSelection();
     if (selectionList.getModel().getSize() > 0) {
       selectionList.ensureIndexIsVisible(0);
     }
   } else {
     selectionList.setSelectedIndex(idx);
     selectionList.ensureIndexIsVisible(idx);
   }
 }
Example #13
0
 void moveCursor(int x, int y) {
   int height = pictView.getSize().height;
   int size = mainView.getModel().getSize();
   //      int first = mainView.getFirstVisibleIndex();
   //      int last = mainView.getLastVisibleIndex();
   //      int h = Math.abs((last - first) / 2);
   //      int index = y * size / height - h;
   int index = y * size / height;
   mainView.ensureIndexIsVisible(index);
   pictView.repaint();
 }
Example #14
0
  /**
   * Shows a string message in the client's log with the specified color
   *
   * @param message
   * @param color
   */
  public void show(String message, Color color) {
    backGC.add(Color.LIGHT_GRAY);
    foreGC.add(color);

    lastMessage = message;

    listModel.addElement(formatMsg(message));
    render.setElements(backGC, foreGC);
    counter++;

    logText.ensureIndexIsVisible(logText.getLastVisibleIndex() + 1);
  }
Example #15
0
 public void addRecentMessage(MessageListElement messageListElement) {
   int size = recentMessageListModel.getSize();
   recentMessageListModel.add(size, messageListElement);
   recentMessageList.ensureIndexIsVisible(size);
   if (playAsReceivedCheckBox.isSelected()) {
     if (messageListElement instanceof MusicMessageListElement) {
       MusicMessageListElement musicMessageListElement =
           (MusicMessageListElement) messageListElement;
       Midi midi = musicMessageListElement.getMidi();
       editor.play(midi);
     }
   }
 }
Example #16
0
  private void assembleAction() {
    String line;
    messages = new Vector();

    mainFrame.resetExecWindow();

    save();

    assembleFailed = false;
    haveAssemblyErrors = false;

    if (Assembler.version()) {
      while ((line = Assembler.output()) != null) {
        messages.addElement(line);
      }

      Assembler.setPaths(baseName, sourcePath);

      if (Assembler.assemble()) {
        while ((line = Assembler.output()) != null) {
          System.out.println(line);

          messages.addElement(line);

          if (line.startsWith(" [ERROR:")) {
            haveAssemblyErrors = true;
          }
        }

        messageList.setListData(messages);
        messageList.ensureIndexIsVisible(0);

        mainFrame.showExecWindow(baseName);
      } else {
        assembleFailed = true;
      }
    } else {
      assembleFailed = true;
    }

    if (assembleFailed) {
      String message =
          String.format(
              "Autocoder failed!\nVerify the correctness of autocoder path\n%s",
              AssemblerOptions.assemblerPath);
      System.out.println(message);

      JOptionPane.showMessageDialog(this, message, "ROPE", JOptionPane.ERROR_MESSAGE);
    }
  }
Example #17
0
  /** Switches the JList to the next record */
  private void switchToNext() {
    // if at the last record
    if (list.getSelectedIndex() + 1 > list.getModel().getSize() - 1) {
      // Then go to the begenning
      list.setSelectedIndex(0);
    } else {
      // otherwise to to the next.
      list.setSelectedIndex(list.getSelectedIndex() + 1);
    }

    // Update the contact pane
    contactdatapane.populateTextBoxesWithRecord(list.getSelectedValue().toString());
    list.ensureIndexIsVisible(list.getSelectedIndex());
  }
  public void actionPerformed(final AnActionEvent event) {
    final ListSelectionModel selectionModel = list.getSelectionModel();
    if (!selectionModel.isSelectionEmpty()) {
      // shift the indices
      final int[] selectedIndices = list.getSelectedIndices();
      listModel.shiftElements(selectedIndices, true);

      // now update the list selection
      for (int i = 0; i < selectedIndices.length; i++) {
        selectedIndices[i] = selectedIndices[i] + 1;
      }
      list.setSelectedIndices(selectedIndices);
      list.ensureIndexIsVisible(selectedIndices[selectedIndices.length - 1]);
    }
  }
Example #19
0
 /** Find next or prev diffs. TODO use model instead of model in view */
 void findOutline(Order param) {
   if (param == Order.Ascent) {
     int index;
     if (mainView.isSelectionEmpty()) {
       index = 0;
     } else {
       index = mainView.getSelectedIndex();
     }
     ListModel model = mainView.getModel();
     while (index++ < model.getSize() - 1) {
       Pair.Type diff = ((Pair) model.getElementAt(index)).getDiff();
       if (diff.isDifferent()) {
         mainView.setSelectedIndex(index);
         mainView.ensureIndexIsVisible(index);
         break;
       }
     }
   } else {
     ListModel model = mainView.getModel();
     int index;
     if (mainView.isSelectionEmpty()) {
       index = model.getSize();
     } else {
       index = mainView.getSelectedIndex();
     }
     while (index-- > 0) {
       Pair.Type diff = ((Pair) model.getElementAt(index)).getDiff();
       if (diff.isDifferent()) {
         mainView.setSelectedIndex(index);
         mainView.ensureIndexIsVisible(index);
         break;
       }
     }
   }
   mainView.repaint(); // TODO for popup menu garbage
 }
Example #20
0
  @SuppressWarnings("unchecked")
  public void setIR(IR ir) {
    this.lineToPosition = HashMapFactory.make();
    this.pcToLine = HashMapFactory.make();
    this.lineToPc = HashMapFactory.make();

    int firstLineWithPosition = NA;

    try {
      methodName.setText("IR: " + ir.getMethod());
      irLineList.clear();
      BufferedReader br = new BufferedReader(new StringReader(ir.toString()));
      int lineNum = 0;
      int position = NA;
      String line;
      while ((line = br.readLine()) != null) {
        irLineList.addElement(line);
        int pc = parseIrLine(line);
        if (pc != NA) {
          IMethod m = ir.getMethod();
          int newPosition = m.getLineNumber(pc);
          if (newPosition != -1) {
            position = newPosition;
          }
          lineToPc.put(lineNum, pc);
          pcToLine.put(pc, lineNum);

          if (position != NA) {
            lineToPosition.put(lineNum, position);
            if (firstLineWithPosition == NA) {
              firstLineWithPosition = lineNum;
            }
          }
        }
        lineNum++;
      }
    } catch (IOException e) {
      // ???
      assert false;
    }

    // focusing on the first line with position
    if (firstLineWithPosition != NA) {
      irLines.setSelectedIndex(firstLineWithPosition);
      irLines.ensureIndexIsVisible(firstLineWithPosition);
    }
  }
Example #21
0
  /** Switches the JList to the previous record. */
  private void switchToPrevious() {
    // If no record is selected
    if (list.getSelectedIndex() == -1) {
      list.setSelectedIndex(0);
    }

    // If at the first record
    if (list.getSelectedIndex() == 0) {
      // goto the last record
      list.setSelectedIndex(list.getModel().getSize() - 1);
    } else {
      // otherwise goto the previous record.
      list.setSelectedIndex(list.getSelectedIndex() - 1);
    }

    // Update the contact pane.
    contactdatapane.populateTextBoxesWithRecord(list.getSelectedValue().toString());
    list.ensureIndexIsVisible(list.getSelectedIndex());
  }
Example #22
0
  protected void highlightNextResult() {
    if (resultsList.getSelectedValue() == null) {
      this.highlightFirstResult();
      return;
    }

    SearchResult sr = (SearchResult) resultsList.getSelectedValue();
    SearchMatch sm = sr.getNextMatch();

    if (sm != null) {
      highlightMatch(sm);
    } else {
      // Next record
      if (resultsList.getSelectedIndex() < resultsList.getModel().getSize() - 1) {
        resultsList.setSelectedIndex(resultsList.getSelectedIndex() + 1);
        resultsList.ensureIndexIsVisible(resultsList.getSelectedIndex());
      } else {
        this.highlightFirstResult();
      }
    }
  }
Example #23
0
  protected void highlightPrevResult() {
    if (resultsList.getSelectedValue() == null) {
      this.highlightFirstResult();
      return;
    }

    SearchResult sr = (SearchResult) resultsList.getSelectedValue();
    SearchMatch sm = sr.getPrevMatch();

    if (sm != null) {
      highlightMatch(sm);
    } else {
      // Previous record
      if (resultsList.getSelectedIndex() > 0) {
        resultsList.setSelectedIndex(resultsList.getSelectedIndex() - 1);
      } else {
        resultsList.setSelectedIndex(resultsList.getModel().getSize() - 1);
      }
      resultsList.ensureIndexIsVisible(resultsList.getSelectedIndex());
      highlightLastResult((SearchResult) resultsList.getSelectedValue());
    }
  }
  /** EdiDialog constructor comment. */
  public void keyReleased(java.awt.event.KeyEvent e) {
    if (e.getSource() == list) {
      switch (e.getKeyCode()) {
        case KeyEvent.VK_DELETE:
        case KeyEvent.VK_BACK_SPACE:
          if (keys.length() > 0) keys.setLength(keys.length() - 1);
          break;
        case KeyEvent.VK_ESCAPE:
          dispose();
          break;
        case KeyEvent.VK_ENTER:
          dispose();
          actionOK();
          break;
        case KeyEvent.VK_SPACE:
          actionAdd();
          break;
        default:
          // keys.append((char) e.getKeyChar());
          list.ensureIndexIsVisible(list.getSelectedIndex());
      }

      //		if (debug)
      //			System.out.println("keys: " + keys);
      return;
    }

    switch (e.getKeyCode()) {
      case KeyEvent.VK_ENTER:
      case KeyEvent.VK_ESCAPE:
        dispose();
        break;
      default:
        break;
    }

    super.keyReleased(e);
  }
Example #25
0
 /** Change the currently displayed board. Pass -1 for no board displayed. */
 protected void setCurrentBoard(int index) {
   if (moveList.getSelectedIndex() != index) {
     moveList.setSelectedIndex(index);
     moveList.ensureIndexIsVisible(index);
   }
   // If a move was requested, but we're changing from the
   // last board, cancel the request
   if (userMoveRequested && index != boardHistory.size() - 1) {
     boardPanel.cancelMoveRequest();
     userMoveRequested = false;
   }
   if (currentBoard != index) {
     currentBoard = index;
     // Might be no board, index -1
     if (index < 0) {
       boardPanel.setCurrentBoard(null);
       fromHereAction.setEnabled(false);
     } else {
       Board b = (Board) boardHistory.get(index);
       // Might be the last board, in which case there is no
       // matching board in the list
       if (b == null) b = (Board) boardHistory.get(boardHistory.size() - 1);
       boardPanel.setCurrentBoard(b);
       fromHereAction.setEnabled(
           b != null && b.getWinner() == Board.NOBODY && b.getTurnsPlayed() > 0 && server == null);
     }
     backAction.setEnabled(index > 0);
     firstAction.setEnabled(index > 0);
     fwdAction.setEnabled(index < boardHistory.size() - 1);
     lastAction.setEnabled(index < boardHistory.size() - 1);
   }
   // If we need a move, and this is the last board, request it
   if (userMoveNeeded && index == boardHistory.size() - 1 && !userMoveRequested) {
     boardPanel.requestMove(this);
     userMoveRequested = true;
   }
 }
 private void _scrollPaneContactList_scrollUp(ActionEvent actionEvent) {
   if (_listContactList.getFirstVisibleIndex() - _listContactList.getVisibleRowCount() >= 0)
     _listContactList.ensureIndexIsVisible(
         _listContactList.getFirstVisibleIndex() - _listContactList.getVisibleRowCount());
   else _listContactList.ensureIndexIsVisible(0);
 }
Example #27
0
  private void processRequest(ResponseReceivedEvent event) {

    HttpRequest request = event.getRequest();

    URI uri = null;
    try {
      uri = new URI(request.getUri());
    } catch (URISyntaxException ex) {
      logger.error(
          "Can't create URI from request uri (" + request.getUri() + ")" + ex.getStackTrace());
    }

    events.addElement(request.getMethod() + " | " + request.getUri());
    executedEvents.ensureIndexIsVisible(events.getSize() - 1);

    int id = ++numberOfRequests;
    event.setId(id);

    /* URLs */
    if (urlBase == null) {
      protocol = uri.getScheme();
      host = uri.getHost();
      port = uri.getPort();
      urlBase = protocol + "://" + host;
      urlBaseString = "PROTOCOL + \"://\" + HOST";
      if (port != -1) {
        urlBase += ":" + port;
        urlBaseString += " + \":\" + PORT";
      }
    }

    String requestUrlBase = uri.getScheme() + "://" + uri.getHost();
    if (uri.getPort() != -1) requestUrlBase += ":" + uri.getPort();
    if (requestUrlBase.equals(urlBase)) event.setWithUrlBase(true);
    else urls.put("url_" + id, requestUrlBase + uri.getPath());

    String headerAuthorization = event.getRequest().getHeader("Authorization");
    request.removeHeader("Authorization");
    if (headerAuthorization != null) {
      if (basicAuth == null) {
        // Split on " " and take 2nd group (Basic credentialsInBase64==)
        String credentials =
            new String(Base64.decodeBase64(headerAuthorization.split(" ")[1].getBytes()));
        basicAuth =
            new BasicAuth(requestUrlBase, credentials.split(":")[0], credentials.split(":")[1]);
        event.setBasicAuth(basicAuth);
      } else {
        if (requestUrlBase.equals(basicAuth.getUrlBase())) event.setBasicAuth(basicAuth);
        else basicAuth = null;
      }
    }

    /* Headers */
    Map<String, String> requestHeaders = new TreeMap<String, String>();
    for (Entry<String, String> entry : request.getHeaders())
      requestHeaders.put(entry.getKey(), entry.getValue());
    requestHeaders.remove("Cookie");

    int bestChoice = 0;
    String headerKey = EMPTY;
    MapDifference<String, String> diff;
    Map<String, String> fullHeaders = new TreeMap<String, String>();
    boolean containsHeaders = false;

    if (headers.size() > 0) {
      for (Entry<String, Map<String, String>> header : headers.entrySet()) {

        fullHeaders = new TreeMap<String, String>(header.getValue());
        containsHeaders = false;

        if (header.getValue().containsKey("headers")) {
          fullHeaders.putAll(headers.get(header.getValue().get("headers")));
          fullHeaders.remove("headers");
          containsHeaders = true;
        }

        diff = Maps.difference(fullHeaders, requestHeaders);
        logger.debug(diff.toString());
        if (diff.areEqual()) {
          headerKey = header.getKey();
          bestChoice = 1;
          break;
        } else if (diff.entriesOnlyOnLeft().size() == 0
            && diff.entriesDiffering().size() == 0
            && !containsHeaders) {
          // header are included in requestHeaders
          headerKey = header.getKey();
          bestChoice = 2;
        } else if (bestChoice > 2
            && diff.entriesOnlyOnRight().size() == 0
            && diff.entriesDiffering().size() == 0
            && !containsHeaders) {
          // requestHeaders are included in header
          headerKey = header.getKey();
          bestChoice = 3;
        }
      }
    }

    switch (bestChoice) {
      case 1:
        event.setHeadersId(headerKey);
        break;
      case 2:
        diff = Maps.difference(headers.get(headerKey), requestHeaders);
        TreeMap<String, String> tm2 = new TreeMap<String, String>(diff.entriesOnlyOnRight());
        headers.put("headers_" + id, tm2);
        headers.get("headers_" + id).put("headers", headerKey);
        event.setHeadersId("headers_" + id);
        break;
      case 3:
        diff = Maps.difference(headers.get(headerKey), requestHeaders);
        TreeMap<String, String> tm3 = new TreeMap<String, String>(diff.entriesInCommon());
        headers.put("headers_" + id, tm3);
        event.setHeadersId("headers_" + id);
        headers.remove(headerKey);
        tm3 = new TreeMap<String, String>(diff.entriesOnlyOnLeft());
        headers.put(headerKey, tm3);
        headers.get(headerKey).put("headers", "headers_" + id);
        break;
      default:
        headers.put("headers_" + id, requestHeaders);
        event.setHeadersId("headers_" + id);
    }

    /* Add check if status is not in 20X */
    if ((event.getResponse().getStatus().getCode() < 200)
        || (event.getResponse().getStatus().getCode() > 210)) event.setWithCheck(true);

    /* Params */
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
    event.getRequestParams().putAll((decoder.getParameters()));

    /* Content */
    if (request.getContent().capacity() > 0) {
      String content = new String(request.getContent().array());
      // We check if it's a form validation and so we extract post params
      if ("application/x-www-form-urlencoded".equals(request.getHeader("Content-Type"))) {
        decoder = new QueryStringDecoder("http://localhost/?" + content);
        event.getRequestParams().putAll(decoder.getParameters());
      } else {
        event.setWithBody(true);
        dumpRequestBody(id, content);
      }
    }

    listEvents.add(event);
  }
Example #28
0
 /**
  * Actualiza la receta seleccionada
  *
  * @param index La posiciĆ³n de la receta que se debe seleccionar
  */
 public void seleccionar(int index) {
   listaRecetas.setSelectedIndex(index);
   listaRecetas.ensureIndexIsVisible(index);
 }
  // FUNCTION TO SIMULATE A STEP IN THE SIMULATION ON THE FRAME
  public void step() {

    /**
     * EACH TIME THE NEXT BUTTON IS PRESSED, ALL THE STATES THAT OCURRED UPTO THE CURRENT STATE ARE
     * EVALUATED. THERE IS A while STATEMENT THAT PERFORMS THIS FUNCTION AND CONTAINS A switch
     * STATEMENT WITHIN IT TO EVALUATE EACH STEP AS IT OCCURS.
     */

    ////////////////////// INITIALIZATION ///////////////////////////////////////

    // UPDATE THE STATE OF THE CACHE AND MEMORY
    for (int i = 0; i < 16; i++) {
      cachePanel.stringBlocks[i] = "";
      cachePanel.boolBlocks[i] = false;
      cachePanel.tag[i] = "";
      cachePanel.boolTags[i] = false;

      statusCacheEmpty[i] = true;
      statusCacheLRU[i] = 0;
    }
    for (int i = 0; i < 8; i++) {
      cachePanel.boolWords[i] = false;
      memoryPanel.boolWords[i] = false;
    }
    for (int i = 0; i < 32; i++) memoryPanel.boolBlocks[i] = false;

    // UPDATE THE BITS IN MAIN MEMORY ADDRESS
    tTag.setText("");
    tWord.setText("");
    tTag.setBackground(new Color(205, 205, 205));
    tWord.setBackground(new Color(205, 205, 205));

    // UPDATE THE CACHE HITS AND MISSES FIELDS
    cacheHits = 0;
    cacheMisses = 0;
    tCacheHits.setText("  0");
    tCacheMisses.setText("  0");

    // UPDATE THE VALUES USED FOR BRINGING MEMORY BLOCKS IN CACHE
    statusLRU = 0;
    memInCache = -1;
    lruCacheBlock = -1;

    // RESET THE VALUE OF addSel
    evaluateIndex = 0;

    // DISABLE ADDRESS GENERATION BUTTONS
    autoGen.setEnabled(false);
    selfGen.setEnabled(false);

    ////////////////////// END INITIALIZATION /////////////////////////////////////

    // IF Next WAS CLICKED, INCREMENT moveStatus
    if (nextClicked) moveStatus++;
    else {
      // DECREMENT moveStatus AND ENABLE NEXT SINCE IT MIGHT BE DISABLED
      moveStatus--;
      next.setEnabled(true);
    }

    // IF NO MORE back MOVES CAN BE MADE, DISABLE back BUTTON
    if (moveStatus == 0) {
      back.setEnabled(false);
      tProgress.setText(
          "You cannot go back any further."
              + "\nPlease click on \"Next\" or \"Restart\" to continue.");
      tProgress.setCaretPosition(0);

      // CLEAR THE SELECTED ADDRESS REFERENCE STRING
      addRefStrList.clearSelection();
    } else
      // ENABLE back BUTTON ONCE THE FIRST MOVE IS MADE
      back.setEnabled(true);

    // INITIALIZE THE VARIABLE THAT KEEPS TRACK OF THE STATE WE ARE CURRENTLY EVALUATING.
    int tempState = 1;

    // CONTINUE TO EVALUATE EACH STATE TILL WE REACH THE CURRENT STATE
    while (tempState <= moveStatus) {

      switch (tempState % 6) {
        case 1: // IF A NEW CYCLE IS BEGINNING, OBTAIN NEXT ADDRESS REFERENCE

          // OBTAIN THE ADDRESS REFERENCE STRING
          addRefStrList.setSelectedIndex(evaluateIndex);

          // ENSURE THAT THE LIST SCROLLS AND SELECTED INDEX IS VISIBLE
          // DUE TO REPAINTING CONSTRAINTS, ONLY DO THIS IN THE CURRENT STATE
          if (tempState == moveStatus) addRefStrList.ensureIndexIsVisible(evaluateIndex);

          // EVALUATE THE TAG, BLOCK AND WORD
          hexAddress = (String) addRefStrList.getSelectedValue();
          int intAddress = Integer.parseInt(hexAddress, 16);
          binAddress = Integer.toBinaryString(intAddress);

          // USING CLASS INTEGER'S parseInt FUNCTION RETURNS A BINARY STRING WITHOUT LEADING 0'S
          // ENSURE THAT binAddress is 8 bits
          if (binAddress.length() < 8) {
            int zeroes = 8 - binAddress.length();
            for (int i = 0; i < zeroes; i++) binAddress = '0' + binAddress;
          }

          tag = binAddress.substring(0, 5);
          word = binAddress.substring(5);

          // CALCULATE THE ACTUAL CACHE AND MEMORY BLOCKS AND WORDS IN QUESTION
          intWordDec = Integer.parseInt(word, 2);
          intBlockDecMem = Integer.parseInt(tag, 2);

          // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
          if (tempState == moveStatus) {
            tProgress.setText(
                "The memory address we want is obtained from the Address Reference String."
                    + "\nIt is (in hexadecimal): "
                    + hexAddress
                    + ".");
            tProgress.setCaretPosition(0);
          }

          break;

        case 2: // EVALUATE THE BITS IN MAIN MEMORY ADDRESS AND HIGHLIGHT THEM

          // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
          if (tempState == moveStatus) {
            tProgress.setText(
                "The hexadecimal address "
                    + hexAddress
                    + " evaluates to its binary equivalent "
                    + binAddress
                    + "."
                    + "\nHence the bits in the Main Memory Address are divided into the following fields\n"
                    + tag
                    + " --> Tag,  "
                    + word
                    + " --> Word."
                    + "\nThe tag bits identify the memory block, "
                    + "and the word bits identify the word within the block.");
            tProgress.setCaretPosition(0);

            // HIGHLIGHT THE BITS IN MAIN MEMORY ADDRESS IN GREEN
            tTag.setBackground(Color.green);
            tWord.setBackground(Color.green);
          }

          tTag.setText("      " + tag);
          tWord.setText("  " + word);

          break;

        case 3: // FIND THE CACHE BLOCK IN QUESTION AND HIGHLIGHT IT

          // UNDO HIGHLIGHTS OF PREVIOUS STEP
          tTag.setBackground(new Color(205, 205, 205));
          tWord.setBackground(new Color(205, 205, 205));

          // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
          if (tempState == moveStatus) {
            tProgress.setText(
                "Every time a memory block is placed in cache, its tag field is stored with it as well."
                    + "\nSo, to find the required memory block in cache, its tag, "
                    + tag
                    + " is compared to all the valid tag fields in cache.");
            tProgress.setCaretPosition(0);
          }

          // GET THE BLOCK IN CACHE WHERE MEMORY BLOCK EXISTS, IF AT ALL
          memInCache = getCacheBlock(tag);

          // IF MEMORY BLOCK IS NOT IN CACHE...
          if (memInCache == -1) {
            if (tempState == moveStatus) {
              tProgress.append(
                  "\n\nSince the memory block is not in cache, there is a cache miss."
                      + "\nSo the block needs to be brought in from memory.");
              tProgress.setCaretPosition(0);
            }

            // GET FIRST EMPTY CACHE BLOCK, IF AVAILABLE
            emptyCacheBlock = getFirstEmptyCacheBlock();

            // IF EMPTY CACHE BLOCK IS AVAILABLE, THIS IS WHERE THE MEMORY WILL BE BROUGHT SO
            // DISPLAY IT
            if (!(emptyCacheBlock == -1)) {

              // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
              if (tempState == moveStatus) {
                tProgress.append(
                    "\nSince the cache has empty space, the first available block will be filled."
                        + "\nSee the highlighted cache block.");
                tProgress.setCaretPosition(0);
              }

              // HIGHLIGHT THE CACHE BLOCK IN YELLOW
              cachePanel.boolBlocks[emptyCacheBlock] = true;
              cachePanel.boolTags[emptyCacheBlock] = true;

              // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
              intBlockDec = emptyCacheBlock;
            }

            // ELSE DISPLAY THE LRU CACHE BLOCK WHICH WILL BE REPLACED
            else {

              // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
              if (tempState == moveStatus) {
                tProgress.append(
                    "\nSince the cache is full, the least recently used cache block will be replaced."
                        + "\nSee the highlighted cache block.");
                tProgress.setCaretPosition(0);
              }

              lruCacheBlock = getLRUCacheBlock();

              // HIGHLIGHT THE CACHE BLOCK IN YELLOW
              cachePanel.boolBlocks[lruCacheBlock] = true;
              cachePanel.boolTags[lruCacheBlock] = true;

              // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
              intBlockDec = lruCacheBlock;
            }

            // UPDATE COUNT OF CACHE MISSES
            cacheMisses++;
            tCacheMisses.setText("  " + cacheMisses);
          } else {

            if (tempState == moveStatus) {
              tProgress.append(
                  "\n\nSince the required memory block is in cache block "
                      + memInCache
                      + " there is a cache hit.");
              tProgress.setCaretPosition(0);
            }

            // HIGHLIGHT THE CACHE BLOCK IN YELLOW
            // TO CAUSE HIGHLIGHTING ON THE CACHE, WE NEED TO MODIFY IT'S STATE, i.e. IT'S DATA
            // MEMBERS
            cachePanel.boolBlocks[memInCache] = true;
            cachePanel.boolWords[intWordDec] = true;
            cachePanel.boolTags[memInCache] = true;

            // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
            intBlockDec = memInCache;

            // UPDATE COUNT OF CACHE HITS
            cacheHits++;
            tCacheHits.setText("  " + cacheHits);
          }

          break;

        case 4: // EVALUATE THE MEMORY BLOCK IN QUESTION AND HIGHLIGHT IT

          // UNDO THE HIGHLIGHTS OF THE PREVIOUS STEP
          cachePanel.boolBlocks[intBlockDec] = false;
          cachePanel.boolWords[intWordDec] = false;
          cachePanel.boolTags[intBlockDec] = false;

          // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
          if (tempState == moveStatus) {
            tProgress.setText(
                "Highlighted is the memory block in question. Since the tag bits are "
                    + tag
                    + ", the memory block, in decimal, is "
                    + intBlockDecMem
                    + ".");
            tProgress.setCaretPosition(0);
          }

          // SET THE MEMORY STATE SO AS TO HIGHLIGHT THE REQUIRED MEMORY BLOCK
          memoryPanel.boolBlocks[intBlockDecMem] = true;

          // SET THE MEMORY STATE SO AS TO HIGHLIGHT THE REQUIRED WORD
          memoryPanel.boolWords[intWordDec] = true;

          break;

        case 5: // HIGHLIGHT THE CACHE BLOCK WITH THE MEMORY BLOCK NOW IN IT

          // UNDO HIGHLIGHTS OF PREVIOUS STEP
          memoryPanel.boolBlocks[intBlockDecMem] = false;
          memoryPanel.boolWords[intWordDec] = false;

          /*
           * NOW, THERE ARE 3 WAYS TO GO FROM HERE
           * 1. IF THERE IS AN EMPTY CACHE BLOCK, SIMPLY BRING THE MEMORY BLOCK INTO CACHE
           * 2. IF THE REQUIRED MEMORY BLOCK IS ALREADY IN CACHE, DO NOTHING
           * 3. IF THE CACHE IS FULL, FIND THE LRU BLOCK AND REPLACE IT WITH THE REQUIRED MEMORY BLOCK
           */

          // IF THE MEMORY BLOCK WAS NOT IN CACHE AND AN EMPTY CACHE BLOCK IS AVAILABLE
          // BRING THE MEMORY BLOCK AND TAG INTO CACHE AND HIGHLIGHT CACHE BLOCK
          if ((memInCache == -1) && !(emptyCacheBlock == -1)) {

            // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
            if (tempState == moveStatus) {
              tProgress.setText(
                  "As we saw earlier, the required memory block was not in cache."
                      + "\nSince there was empty space in cache, we brought the memory block into it."
                      + "\nWe also stored the tag, "
                      + tag
                      + ", of the memory block with the cache block."
                      + "\n\nRemember that the memory block could be brought into any empty cache block."
                      + "\nIn our example, we are using the first available empty block.");
              tProgress.setCaretPosition(0);
            }

            // UPDATE THE COUNTER FOR THE LRU CACHE BLOCK
            statusLRU++;
            statusCacheLRU[emptyCacheBlock] = statusLRU;
            statusCacheEmpty[emptyCacheBlock] = false;

            // UPDATE THE CACHE ARRAYS KEEPING TRACK OF MEMORY BLOCKS AND TAGS
            cachePanel.stringBlocks[emptyCacheBlock] = "" + intBlockDecMem;
            cachePanel.tag[emptyCacheBlock] = tag;

            // HIGHLIGHT THE CACHE BLOCK IN YELLOW
            cachePanel.boolBlocks[emptyCacheBlock] = true;
            cachePanel.boolWords[intWordDec] = true;
            cachePanel.boolTags[emptyCacheBlock] = true;

            // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
            intBlockDec = emptyCacheBlock;

          } // END IF

          // IF MEMORY BLOCK IS ALREADY IN CACHE THEN JUST HIGHLIGHT THE CACHE BLOCK
          else if ((memInCache >= 0) && (memInCache < 16)) {

            // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
            if (tempState == moveStatus) {
              tProgress.setText(
                  "As we saw earlier, the required memory block is already in cache.");
              tProgress.setCaretPosition(0);
            }

            // UPDATE THE COUNTER FOR THE LRU CACHE BLOCK
            statusLRU++;
            statusCacheLRU[memInCache] = statusLRU;

            // HIGHLIGHT THE CACHE BLOCK IN YELLOW
            cachePanel.boolBlocks[memInCache] = true;
            cachePanel.boolWords[intWordDec] = true;
            cachePanel.boolTags[memInCache] = true;

            // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
            intBlockDec = memInCache;

          } // END ELSE IF

          // IF THE MEMORY BLOCK IS NOT IN CACHE AND THE CACHE IS FULL
          // FIND THE LRU CACHE BLOCK AND REPLACE IT WITH THE MEMORY BLOCK, THEN HIGHLIGHT THE CACHE
          // BLOCK
          else {

            // FIND THE LRU CACHE BLOCK
            lruCacheBlock = getLRUCacheBlock();

            // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
            if (tempState == moveStatus) {
              tProgress.setText(
                  "As we saw earlier, the cache is full."
                      + "\nSo we picked the least recently used cache block, "
                      + lruCacheBlock
                      + ", and replaced it with the required memory block.");
              tProgress.setCaretPosition(0);
            }

            // UPDATE THE COUNTER FOR THE LRU CACHE BLOCK
            statusLRU++;
            statusCacheLRU[lruCacheBlock] = statusLRU;
            statusCacheEmpty[lruCacheBlock] = false; // redundant stmt

            // UPDATE THE CACHE ARRAYS KEEPING TRACK OF MEMORY BLOCKS AND TAGS
            cachePanel.stringBlocks[lruCacheBlock] = "" + intBlockDecMem;
            cachePanel.tag[lruCacheBlock] = tag;

            // HIGHLIGHT THE CACHE BLOCK IN YELLOW
            cachePanel.boolBlocks[lruCacheBlock] = true;
            cachePanel.boolWords[intWordDec] = true;
            cachePanel.boolTags[lruCacheBlock] = true;

            // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
            intBlockDec = lruCacheBlock;
          } // END ELSE

          break;

        case 0: // LAST STEP IN CYCLE - CLEANUP STEP!

          // UNDO HIGHLIGHTS OF PREVIOUS STEP
          cachePanel.boolBlocks[intBlockDec] = false;
          cachePanel.boolWords[intWordDec] = false;
          cachePanel.boolTags[intBlockDec] = false;

          tTag.setText("");
          tWord.setText("");

          tTag.setBackground(new Color(205, 205, 205));
          tWord.setBackground(new Color(205, 205, 205));

          // CLEAR THE SELECTED ADDRESS REFERENCE STRING
          addRefStrList.clearSelection();

          // INCREMENT THE INDEX SO AS TO POINT TO THE NEXT ADDRESS REFERENCE STRING
          evaluateIndex++;

          // IF THE LAST ADDRESS REFERENCE STRING HAS BEEN REACHED, DO THE APPROPRIATE
          if (evaluateIndex == listData.size()) {

            if (tempState == moveStatus) {
              tProgress.setText(
                  "This completes the runthrough."
                      + "\nPlease click on \"Restart\", generate the Address Reference String "
                      + "OR click \"Quit\" to finish.");
              tProgress.setCaretPosition(0);
            }
            next.setEnabled(false);

            // ENABLE ADDRESS GENERATION BUTTONS
            autoGen.setEnabled(true);
            selfGen.setEnabled(true);

            reStarted = false;
          }

          // ELSE AN ACCESS CYCLE HAS BEEN COMPLETED SO SHOW THE APPROPRIATE MESSAGE IN THE PROGRESS
          // FIELD
          else {
            if (tempState == moveStatus) {
              tProgress.setText("This completes an access cycle.");
              tProgress.setCaretPosition(0);
            }

            // CLEAR THE SELECTION IN THE ADDRESS REFERENCE STRING
            addRefStrList.clearSelection();
          }

          break;

        default:
          JOptionPane.showMessageDialog(null, "Uh Oh, there's a problem in switch-case!");
      } // END switch

      tempState++;
    } // END while

    // CALL THE REPAINT METHOD
    repaint();
  } // END FUNCTION step
Example #30
0
 private void suggestionListScrolling() {
   JList list = suggestionList.getList();
   int selectedIndex = suggestionList.getSelectedIndex();
   list.ensureIndexIsVisible(selectedIndex);
 }