public void actionPerformed(ActionEvent e) { // Handle open button action. if (e.getSource() == openButton) { int returnVal = fc.showOpenDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // This is where a real application would open the file. log.append("Opening: " + file.getName() + "." + newline); } else { log.append("Open command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); // Handle save button action. } else if (e.getSource() == saveButton) { int returnVal = fc.showSaveDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // This is where a real application would save the file. log.append("Saving: " + file.getName() + "." + newline); } else { log.append("Save command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); } }
/** The listener method. */ public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source == b1) // click button { try { String message = tf.getText(); server.sendPrivateMessage(parent, selfIdentity, message); ta.append("<" + parent.getUserName() + ">: " + message + lineSeparator); ta.setCaretPosition(ta.getText().length()); tf.setText(""); } catch (RemoteException ex) { System.out.print("Exception encountered while sending" + " private message."); } } if (source == tf) // press return { try { String message = tf.getText(); server.sendPrivateMessage(parent, selfIdentity, message); ta.append("<" + parent.getUserName() + ">: " + message + lineSeparator); ta.setCaretPosition(ta.getText().length()); tf.setText(""); } catch (RemoteException ex) { System.out.print("Exception encountered while sending" + " private message."); } } if (source == jMenuItem3) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Choose or create a new file to store the conversation"); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setDoubleBuffered(true); fileChooser.showOpenDialog(this); File file = fileChooser.getSelectedFile(); try { if (file != null) { Writer writer = new BufferedWriter(new FileWriter(file)); writer.write(ta.getText()); writer.flush(); writer.close(); } } catch (IOException ex) { System.out.println("Can't write to file. " + ex); } } if (source == jMenuItem4) { selfRemove(); this.dispose(); } }
static void log(String message) { if (resetFlag){ logArea.setText(""); miniLogArea.setText(""); } resetFlag = (message.length() == 0); logArea.append(message + "\n"); miniLogArea.append(message + "\n"); logArea.setCaretPosition(logArea.getDocument().getLength()); miniLogArea.setCaretPosition(miniLogArea.getDocument().getLength()); }
/** * Add a line of text to the transcript area. * * @param message text to be added; two line feeds is added at the end. */ private void postMessage(String message) { transcript.append(message + "\n\n"); // The following line is a nasty kludge that was the only way I could find to force // the transcript to scroll so that the text that was just added is visible in // the window. Without this, text can be added below the bottom of the visible area // of the transcript. transcript.setCaretPosition(transcript.getDocument().getLength()); }
public void valueChanged(ListSelectionEvent event) { if (table.getSelectedRow() == -1) textArea.setText(null); else { TableItem item = table.getTableItemAt(table.getSelectedRow()); textArea.setText(item.toString()); } textArea.setCaretPosition(0); }
public LicenseDialog(Component parent) { setTitle("Licensing information"); pnlButtons.add(bttnOk); cbLang.addItem("English"); cbLang.addItem("Eesti"); FlowLayout fl = new FlowLayout(); fl.setAlignment(FlowLayout.LEFT); pnlHeader.setLayout(fl); pnlHeader.add(lblLang); pnlHeader.add(cbLang); pnlMain.setLayout(new BorderLayout()); pnlMain.add(pnlHeader, BorderLayout.NORTH); pnlMain.add(scrollPane, BorderLayout.CENTER); pnlMain.add(pnlButtons, BorderLayout.SOUTH); taLicenseText.setText(getLicenseText()); taLicenseText.setCaretPosition(0); taLicenseText.setLineWrap(true); taLicenseText.setEditable(false); taLicenseText.setWrapStyleWord(true); getContentPane().add(pnlMain); setPreferredSize(new Dimension(500, 600)); setLocationRelativeTo(parent); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); bttnOk.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent evt) { if (evt.getSource() == bttnOk) { dispose(); } } // end actionPerformed }); // end bttnOk Action Listener cbLang.addItemListener( new ItemListener() { public void itemStateChanged(final ItemEvent event) { if (event.getSource() == cbLang && event.getStateChange() == ItemEvent.SELECTED && cbLang.getItemCount() > 0) { taLicenseText.setText(getLicenseText()); taLicenseText.setCaretPosition(0); } } }); // end cbLang item listener pack(); setVisible(true); } // PortPropertiesDialog
public void actionPerformed(ActionEvent evt) { String text = textField.getText(); textArea.append(text + newline); textField.selectAll(); // Make sure the new text is visible, even if there // was a selection in the text area. textArea.setCaretPosition(textArea.getDocument().getLength()); }
/** * Updates all of the components in the panel to match that of the associated Artifact. * * @see #ArtifactView(Artifact, DataProvider) */ public void rebuild() { title.setText(SHTML + TITLE + elem.title + EHTML); donor.setText(SHTML + DONOR + elem.donor + EHTML); subDate.setText(SHTML + SUB_DATE + elem.subDate.toString() + EHTML); objDate.setText(SHTML + OBJ_DATE + elem.objDate.toString() + EHTML); medium.setText(SHTML + MEDIUM + elem.medium + EHTML); accNum.setText(SHTML + ACC_NUM + elem.accNum + EHTML); descView.setText(elem.desc); descView.setCaretPosition(0); validate(); }
private void breakpointHit(char pc) { registersModel.fireUpdate(); memoryModel.fireUpdate(0, RAM_SIZE - 1); // TODO optimize Integer srcline = asmMap.bin2src(pc); if (srcline != null) { try { sourceTextarea.requestFocus(); sourceTextarea.setCaretPosition(sourceTextarea.getLineStartOffset(srcline - 1)); } catch (BadLocationException e) { e.printStackTrace(); } } }
private void showHelp(String help[]) { txtCommand.setText(help[0]); bHelp = true; pResult.removeAll(); pResult.add(txtResultScroll, BorderLayout.CENTER); pResult.doLayout(); txtResult.setText(help[1]); pResult.repaint(); txtCommand.requestFocus(); txtCommand.setCaretPosition(help[0].length()); }
/** * Post a message to the assembler display * * @param message String to append to assembler display text */ public void postMarsMessage(String message) { assemble.append(message); // can do some crude cutting here. If the document gets "very large", // let's cut off the oldest text. This will limit scrolling but the limit // can be set reasonably high. if (assemble.getDocument().getLength() > MAXIMUM_SCROLLED_CHARACTERS) { try { assemble.getDocument().remove(0, NUMBER_OF_CHARACTERS_TO_CUT); } catch (BadLocationException ble) { // only if NUMBER_OF_CHARACTERS_TO_CUT > MAXIMUM_SCROLLED_CHARACTERS } } assemble.setCaretPosition(assemble.getDocument().getLength()); setSelectedComponent(assembleTab); }
/** * Appends each string in the new_strings parameter as a new line in the text area. Sets the caret * is set to the beginning of the text. * * @param new_strings The strings to add. Each entry is added to a new line. This method performs * no action if this parameter is empty or null. */ public void appendStrings(String[] new_strings) { if (new_strings != null) if (new_strings.length != 0) { // Append the text for (int i = 0; i < new_strings.length; i++) { if (i == 0) { if (!text_area.getText().equals("")) text_area.append("\n"); } else text_area.append("\n"); text_area.append(new_strings[i]); } // Reset the caret position text_area.setCaretPosition(0); } }
public void actionPerformed(ActionEvent e) { // Handle open button action. if (e.getSource() == openButton) { int returnVal = fc.showOpenDialog(DirectorySize.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // This is where a real application would open the file. ListSubDirectorySizes(file); } else { log.append("Open command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); // Handle save button action. } else if (e.getSource() == saveButton) { log.setText(""); // reset } }
/** Update the merged BibtexEntry with source and preview panel everytime something is changed */ private void updateAll() { if (!doneBuilding) { // If we've not done adding everything, do not do anything... return; } // Check if the type is changed if (!identical[0]) { if (rb[0][0].isSelected()) { mergedEntry.setType(one.getType()); } else { mergedEntry.setType(two.getType()); } } // Check all fields for (int i = 0; i < joint.size(); i++) { if (!identical[i + 1]) { if (rb[0][i + 1].isSelected()) { mergedEntry.setField(jointStrings[i], one.getField(jointStrings[i])); } else if (rb[2][i + 1].isSelected()) { mergedEntry.setField(jointStrings[i], two.getField(jointStrings[i])); } else { mergedEntry.setField(jointStrings[i], null); } } } // Update the PreviewPanel pp.setEntry(mergedEntry); // Update the Bibtex source view StringWriter sw = new StringWriter(); try { new BibtexEntryWriter(new LatexFieldFormatter(), false).write(mergedEntry, sw); } catch (IOException ex) { LOGGER.error("Error in entry" + ": " + ex.getMessage(), ex); } jta.setText(sw.getBuffer().toString()); jta.setCaretPosition(0); }
public boolean loadSourceFile(File file) { boolean result = false; selectedPath = file.getParent(); BufferedReader sourceFile = null; String directoryPath = file.getParent(); String sourceName = file.getName(); int idx = sourceName.lastIndexOf("."); fileExt = idx == -1 ? "" : sourceName.substring(idx + 1); baseName = idx == -1 ? sourceName.substring(0) : sourceName.substring(0, idx); String basePath = directoryPath + File.separator + baseName; DataOptions.directoryPath = directoryPath; sourcePath = file.getPath(); AssemblerOptions.sourcePath = sourcePath; AssemblerOptions.listingPath = basePath + ".lst"; AssemblerOptions.objectPath = basePath + ".cd"; String var = System.getenv("ROPE_MACROS_DIR"); if (var != null && !var.isEmpty()) { File dir = new File(var); if (dir.exists() && dir.isDirectory()) { AssemblerOptions.macroPath = var; } else { AssemblerOptions.macroPath = directoryPath; } } else { AssemblerOptions.macroPath = directoryPath; } DataOptions.inputPath = AssemblerOptions.objectPath; DataOptions.outputPath = basePath + ".out"; DataOptions.readerPath = null; DataOptions.punchPath = basePath + ".pch"; DataOptions.tape1Path = basePath + ".mt1"; DataOptions.tape2Path = basePath + ".mt2"; DataOptions.tape3Path = basePath + ".mt3"; DataOptions.tape4Path = basePath + ".mt4"; DataOptions.tape5Path = basePath + ".mt5"; DataOptions.tape6Path = basePath + ".mt6"; this.setTitle("EDIT: " + sourceName); fileText.setText(sourcePath); if (dialog == null) { dialog = new AssemblerDialog(mainFrame, "Assembler options"); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension dialogSize = dialog.getSize(); dialog.setLocation( (screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2); } dialog.initialize(); AssemblerOptions.command = dialog.buildCommand(); sourceArea.setText(null); try { sourceFile = new BufferedReader(new FileReader(file)); String line; while ((line = sourceFile.readLine()) != null) { sourceArea.append(line + "\n"); } sourceArea.setCaretPosition(0); optionsButton.setEnabled(true); assembleButton.setEnabled(true); saveButton.setEnabled(true); setSourceChanged(false); undoMgr.discardAllEdits(); result = true; } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (sourceFile != null) { sourceFile.close(); } } catch (IOException ignore) { } } return result; }
public SwingUpdaterUI(String oldBuildDesc, String newBuildDesc, InstallOperation operation) { myOperation = operation; myProcessTitle = new JLabel(" "); myProcessProgress = new JProgressBar(0, 100); myProcessStatus = new JLabel(" "); myCancelButton = new JButton(CANCEL_BUTTON_TITLE); myConsole = new JTextArea(); myConsole.setLineWrap(true); myConsole.setWrapStyleWord(true); myConsole.setCaretPosition(myConsole.getText().length()); myConsole.setTabSize(1); myConsolePane = new JPanel(new BorderLayout()); myConsolePane.add(new JScrollPane(myConsole)); myConsolePane.setBorder(BUTTONS_BORDER); myConsolePane.setVisible(false); myCancelButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { doCancel(); } }); myFrame = new JFrame(); myFrame.setTitle(TITLE); myFrame.setLayout(new BorderLayout()); myFrame.getRootPane().setBorder(FRAME_BORDER); myFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); myFrame.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { doCancel(); } }); JPanel processPanel = new JPanel(); processPanel.setLayout(new BoxLayout(processPanel, BoxLayout.Y_AXIS)); processPanel.add(myProcessTitle); processPanel.add(myProcessProgress); processPanel.add(myProcessStatus); processPanel.add(myConsolePane); for (Component each : processPanel.getComponents()) { ((JComponent) each).setAlignmentX(Component.LEFT_ALIGNMENT); } JPanel buttonsPanel = new JPanel(); buttonsPanel.setBorder(BUTTONS_BORDER); buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS)); buttonsPanel.add(Box.createHorizontalGlue()); buttonsPanel.add(myCancelButton); myProcessTitle.setText("<html>Updating " + oldBuildDesc + " to " + newBuildDesc + "..."); myFrame.add(processPanel, BorderLayout.CENTER); myFrame.add(buttonsPanel, BorderLayout.SOUTH); myFrame.setMinimumSize(new Dimension(500, 50)); myFrame.pack(); myFrame.setLocationRelativeTo(null); myFrame.setVisible(true); myQueue.add( new UpdateRequest() { @Override public void perform() { doPerform(); } }); startRequestDispatching(); }
void appendRoom(String str) { chat.append(str); chat.setCaretPosition(chat.getText().length() - 1); }
void appendEvent(String str) { event.append(str); event.setCaretPosition(chat.getText().length() - 1); }
/* * @param String s - send s to output textArea */ public void setOutput(String s) { // if (debugBoardPanel) { bottomText.append("\n" + s); bottomText.setCaretPosition(bottomText.getDocument().getLength()); // } }
/** Main function for building the merge entry JPanel */ private void initialize() { joint = new TreeSet<>(one.getFieldNames()); joint.addAll(two.getFieldNames()); // Remove field starting with __ TreeSet<String> toberemoved = new TreeSet<>(); for (String field : joint) { if (field.startsWith("__")) { toberemoved.add(field); } } for (String field : toberemoved) { joint.remove(field); } // Create storage arrays rb = new JRadioButton[3][joint.size() + 1]; ButtonGroup[] rbg = new ButtonGroup[joint.size() + 1]; identical = new Boolean[joint.size() + 1]; jointStrings = new String[joint.size()]; // Create main layout String colSpecMain = "left:pref, 5px, center:3cm:grow, 5px, center:pref, 3px, center:pref, 3px, center:pref, 5px, center:3cm:grow"; String colSpecMerge = "left:pref, 5px, fill:3cm:grow, 5px, center:pref, 3px, center:pref, 3px, center:pref, 5px, fill:3cm:grow"; String rowSpec = "pref, pref, 10px, fill:5cm:grow, 10px, pref, 10px, fill:3cm:grow"; StringBuilder rowBuilder = new StringBuilder(""); for (int i = 0; i < joint.size(); i++) { rowBuilder.append("pref, "); } rowBuilder.append("pref"); FormLayout mainLayout = new FormLayout(colSpecMain, rowSpec); FormLayout mergeLayout = new FormLayout(colSpecMerge, rowBuilder.toString()); mainPanel.setLayout(mainLayout); mergePanel.setLayout(mergeLayout); JLabel label = new JLabel(Localization.lang("Use")); Font font = label.getFont(); label.setFont(font.deriveFont(font.getStyle() | Font.BOLD)); mainPanel.add(label, cc.xyw(4, 1, 7, "center, bottom")); // Set headings JLabel headingLabels[] = new JLabel[6]; for (int i = 0; i < 6; i++) { headingLabels[i] = new JLabel(columnHeadings[i]); font = headingLabels[i].getFont(); headingLabels[i].setFont(font.deriveFont(font.getStyle() | Font.BOLD)); mainPanel.add(headingLabels[i], cc.xy(1 + (i * 2), 2)); } mainPanel.add(new JSeparator(), cc.xyw(1, 3, 11)); // Start with entry type EntryType type1 = one.getType(); EntryType type2 = two.getType(); mergedEntry.setType(type1); label = new JLabel(Localization.lang("Entry type")); font = label.getFont(); label.setFont(font.deriveFont(font.getStyle() | Font.BOLD)); mergePanel.add(label, cc.xy(1, 1)); JTextArea type1ta = new JTextArea(type1.getName()); type1ta.setEditable(false); mergePanel.add(type1ta, cc.xy(3, 1)); if (type1.compareTo(type2) != 0) { identical[0] = false; rbg[0] = new ButtonGroup(); for (int k = 0; k < 3; k += 2) { rb[k][0] = new JRadioButton(); rbg[0].add(rb[k][0]); mergePanel.add(rb[k][0], cc.xy(5 + (k * 2), 1)); rb[k][0].addChangeListener( new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { updateAll(); } }); } rb[0][0].setSelected(true); } else { identical[0] = true; } JTextArea type2ta = new JTextArea(type2.getName()); type2ta.setEditable(false); mergePanel.add(type2ta, cc.xy(11, 1)); // For all fields in joint add a row and possibly radio buttons int row = 2; int maxLabelWidth = -1; int tmpLabelWidth = 0; for (String field : joint) { jointStrings[row - 2] = field; label = new JLabel(CaseChangers.UPPER_FIRST.format(field)); font = label.getFont(); label.setFont(font.deriveFont(font.getStyle() | Font.BOLD)); mergePanel.add(label, cc.xy(1, row)); String string1 = one.getField(field); String string2 = two.getField(field); identical[row - 1] = false; if ((string1 != null) && (string2 != null)) { if (string1.equals(string2)) { identical[row - 1] = true; } } tmpLabelWidth = label.getPreferredSize().width; if (tmpLabelWidth > maxLabelWidth) { maxLabelWidth = tmpLabelWidth; } if ("abstract".equals(field) || "review".equals(field)) { // Treat the abstract and review fields special JTextArea tf = new JTextArea(); tf.setLineWrap(true); tf.setEditable(false); JScrollPane jsptf = new JScrollPane(tf); mergeLayout.setRowSpec(row, RowSpec.decode("center:2cm:grow")); mergePanel.add(jsptf, cc.xy(3, row, "f, f")); tf.setText(string1); tf.setCaretPosition(0); } else { JTextArea tf = new JTextArea(string1); mergePanel.add(tf, cc.xy(3, row)); tf.setCaretPosition(0); tf.setEditable(false); } // Add radio buttons if the two entries do not have identical fields if (!identical[row - 1]) { rbg[row - 1] = new ButtonGroup(); for (int k = 0; k < 3; k++) { rb[k][row - 1] = new JRadioButton(); rbg[row - 1].add(rb[k][row - 1]); mergePanel.add(rb[k][row - 1], cc.xy(5 + (k * 2), row)); rb[k][row - 1].addChangeListener( new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { updateAll(); } }); } if (string1 != null) { mergedEntry.setField(field, string1); rb[0][row - 1].setSelected(true); if (string2 == null) { rb[2][row - 1].setEnabled(false); } } else { rb[0][row - 1].setEnabled(false); mergedEntry.setField(field, string2); rb[2][row - 1].setSelected(true); } } else { mergedEntry.setField(field, string1); } if ("abstract".equals(field) || "review".equals(field)) { // Again, treat abstract and review special JTextArea tf = new JTextArea(); tf.setLineWrap(true); tf.setEditable(false); JScrollPane jsptf = new JScrollPane(tf); mergePanel.add(jsptf, cc.xy(11, row, "f, f")); tf.setText(string2); tf.setCaretPosition(0); } else { JTextArea tf = new JTextArea(string2); mergePanel.add(tf, cc.xy(11, row)); tf.setCaretPosition(0); tf.setEditable(false); } row++; } JScrollPane scrollPane = new JScrollPane( mergePanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setBorder(BorderFactory.createEmptyBorder()); mainPanel.add(scrollPane, cc.xyw(1, 4, 11)); mainPanel.add(new JSeparator(), cc.xyw(1, 5, 11)); // Synchronize column widths String rbAlign[] = {"right", "center", "left"}; mainLayout.setColumnSpec(1, ColumnSpec.decode(Integer.toString(maxLabelWidth) + "px")); Integer maxRBWidth = -1; Integer tmpRBWidth; for (int k = 0; k < 3; k++) { tmpRBWidth = headingLabels[k + 2].getPreferredSize().width; if (tmpRBWidth > maxRBWidth) { maxRBWidth = tmpRBWidth; } } for (int k = 0; k < 3; k++) { mergeLayout.setColumnSpec( 5 + (k * 2), ColumnSpec.decode(rbAlign[k] + ":" + maxRBWidth + "px")); } // Setup a PreviewPanel and a Bibtex source box for the merged entry label = new JLabel(Localization.lang("Merged entry")); font = label.getFont(); label.setFont(font.deriveFont(font.getStyle() | Font.BOLD)); mainPanel.add(label, cc.xyw(1, 6, 6)); String layoutString = Globals.prefs.get(JabRefPreferences.PREVIEW_0); pp = new PreviewPanel(null, mergedEntry, null, new MetaData(), layoutString); // JScrollPane jsppp = new JScrollPane(pp, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, // JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); mainPanel.add(pp, cc.xyw(1, 8, 6)); label = new JLabel(Localization.lang("Merged BibTeX source code")); font = label.getFont(); label.setFont(font.deriveFont(font.getStyle() | Font.BOLD)); mainPanel.add(label, cc.xyw(8, 6, 4)); jta = new JTextArea(); jta.setLineWrap(true); JScrollPane jspta = new JScrollPane(jta); mainPanel.add(jspta, cc.xyw(8, 8, 4)); jta.setEditable(false); StringWriter sw = new StringWriter(); try { new BibtexEntryWriter(new LatexFieldFormatter(), false).write(mergedEntry, sw); } catch (IOException ex) { LOGGER.error("Error in entry" + ": " + ex.getMessage(), ex); } jta.setText(sw.getBuffer().toString()); jta.setCaretPosition(0); // Add some margin around the layout mainLayout.appendRow(RowSpec.decode("10px")); mainLayout.appendColumn(ColumnSpec.decode("10px")); mainLayout.insertRow(1, RowSpec.decode("10px")); mainLayout.insertColumn(1, ColumnSpec.decode("10px")); if (mainPanel.getHeight() > DIM.height) { mainPanel.setSize(new Dimension(mergePanel.getWidth(), DIM.height)); } if (mainPanel.getWidth() > DIM.width) { mainPanel.setSize(new Dimension(DIM.width, mergePanel.getHeight())); } // Everything done, allow any action to actually update the merged entry doneBuilding = true; // Show what we've got mainPanel.setVisible(true); javax.swing.SwingUtilities.invokeLater( new Runnable() { @Override public void run() { scrollPane.getVerticalScrollBar().setValue(0); } }); }
public void setBodyText(String text) { mailBodyArea.setText(text); mailBodyArea.setCaretPosition(0); }
public void setup() { setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); title = new JLabel(SHTML + TITLE + elem.title + EHTML); gbc.fill = GridBagConstraints.NONE; gbc.anchor = GridBagConstraints.WEST; gbc.gridy = 4; gbc.gridx = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.weighty = 1.0; add(title, gbc); donor = new JLabel(SHTML + DONOR + elem.donor + EHTML); gbc.gridy = 5; add(donor, gbc); subDate = new JLabel(SHTML + SUB_DATE + elem.subDate.toString() + EHTML); gbc.gridy = 6; add(subDate, gbc); objDate = new JLabel(SHTML + OBJ_DATE + elem.objDate.toString() + EHTML); gbc.gridy = 7; add(objDate, gbc); medium = new JLabel(SHTML + MEDIUM + elem.medium + EHTML); gbc.gridy = 8; add(medium, gbc); accNum = new JLabel(SHTML + ACC_NUM + elem.accNum + EHTML); gbc.gridy = 9; add(accNum, gbc); desc = new JLabel(SHTML + DESC + EHTML); // gbc.anchor = GridBagConstraints.PAGE_START; gbc.insets = new Insets(0, 50, 0, 0); gbc.gridy = 4; gbc.gridx = 2; add(desc, gbc); descView = new JTextArea(); descView.setLineWrap(true); descView.setWrapStyleWord(true); descView.setEditable(false); descView.setText(elem.desc); descView.setFont(new Font("Times New Roman", Font.PLAIN, 13)); JScrollPane scrollPane = new JScrollPane(descView); scrollPane.setPreferredSize(new Dimension(225, 100)); // scrollPane.setBorder(null); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); descView.setCaretPosition(0); gbc.gridy = 5; gbc.gridheight = 4; gbc.gridx = 2; add(scrollPane, gbc); gbc.insets = null; gbc.gridy = 0; gbc.gridx = 0; gbc.gridwidth = 4; gbc.gridheight = 4; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(0, 0, 10, 0); vpan = new V3DPanel(elem, provider); vpan.setPreferredSize(new Dimension(500, 300)); setBackground(BACKGROUND); add(vpan, gbc); validate(); }
public void actionPerformed(ActionEvent e) { saveOld(); area1.setText(""); resetArea2(); try { clientSocket = new Socket(ipaddress.getText(), Integer.parseInt(portNumber.getText())); Random r = new Random(); serverport = 10000 + r.nextInt(8999); // random port :D serverSocket = new ServerSocket(serverport); active = true; editor.setTitleToListen(); connected = true; ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream()); output.writeObject(new JoinNetworkRequest(serverport)); ConnectionData data = getConnectionData(clientSocket, input); lc = new LamportClock(data.getId()); lc.setMaxTime(data.getTs()); dec = new DocumentEventCapturer(lc, editor); er = new EventReplayer(editor, dec, lc); ert = new Thread(er); ert.start(); Peer peer = new Peer( editor, er, data.getHostId(), clientSocket, output, input, lc, clientSocket.getInetAddress().getHostAddress(), data.getPort()); dec.addPeer(peer); Thread thread = new Thread(peer); thread.start(); er.setAcknowledgements(data.getAcknowledgements()); er.setEventHistory(data.getEventHistory()); er.setCarets(data.getCarets()); er.addCaretPos(lc.getID(), 0); for (PeerWrapper p : data.getPeers()) { Socket socket; try { socket = connectToPeer(p.getIP(), p.getPort()); ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream()); outputStream.writeObject( new NewPeerDataRequest(lc.getID(), serverSocket.getLocalPort(), 0)); Peer newPeer = new Peer( editor, er, p.getId(), socket, outputStream, inputStream, lc, p.getIP(), p.getPort()); dec.addPeer(newPeer); Thread t = new Thread(newPeer); t.start(); } catch (IOException ex) { continue; } } Thread t1 = new Thread( new Runnable() { @Override public void run() { waitForConnection(); } }); t1.start(); area1.setText(data.getTextField()); area1.setCaretPosition(0); setDocumentFilter(dec); dec.sendObjectToAllPeers(new UnlockRequest(lc.getTimeStamp())); changed = false; Connect.setEnabled(false); Disconnect.setEnabled(true); Listen.setEnabled(false); Save.setEnabled(false); SaveAs.setEnabled(false); } catch (NumberFormatException | IOException e1) { setTitle("Unable to connect"); } }
// CONSTRUCTOR public FACFrame() { // SET PROPERTIES OF THE MAIN FRAME setTitle("Fully Associative Cache"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setIconImage(Toolkit.getDefaultToolkit().createImage(FACFrame.class.getResource("cam.gif"))); // CREATE COMPONENTS AND SET THEIR PROPERTIES // NAVIGATION BUTTONS restart = new JButton("Restart"); next = new JButton("Next"); back = new JButton("Back"); quit = new JButton("Quit"); // CACHE HITS AND MISSES INFO. lCacheHits = new JLabel("Cache Hits"); lCacheMisses = new JLabel("Cache Misses"); tCacheHits = new JTextField(5); tCacheMisses = new JTextField(5); tCacheHits.setEditable(false); tCacheHits.setFont(new Font("Monospaced", Font.BOLD, 14)); tCacheHits.setText(" 0"); tCacheMisses.setEditable(false); tCacheMisses.setFont(new Font("Monospaced", Font.BOLD, 14)); tCacheMisses.setText(" 0"); // PROGRESS UPDATE AREA tProgress = new JTextArea(3, 45); tProgress.setEditable(false); tProgress.setLineWrap(true); tProgress.setWrapStyleWord(true); tProgress.setCaretPosition(0); tProgress.setFont(new Font("Serif", Font.BOLD + Font.ITALIC, 16)); tProgress.setText( "Welcome to Fully Associative Cache!\nThe system specs are as follows -" + "\n 16 Blocks in Cache\n 32 Blocks in Main Memory\n 8 Words per Block" + "\n The replacement algorithm shown is the Least-Recently-Used algorithm" + "\n as it is the most commonly used one." + "\nPlease generate the Address Reference String." + "\nThen click on \"Next\" to continue."); progressScroll = new JScrollPane(); progressScroll.getViewport().add(tProgress); progressScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); lProgress = new JLabel("PROGRESS UPDATE"); // ADDRESS REFERENCE STRING addRefStrList = new JList(); addRefStrList.setEnabled(false); addRefStrScroll = new JScrollPane(); addRefStrScroll.getViewport().setView(addRefStrList); addRefStrScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); addRefStrScroll.setPreferredSize(new Dimension(140, 300)); // BUTTONS USED TO ADDRESS GENERATION autoGen = new JButton("Auto Generate Add. Ref. Str."); selfGen = new JButton("Self Generate Add. Ref. Str."); // BITS IN MAIN MEMORY ADDRESS lBits = new JLabel(" TAG WORD"); tTag = new JTextField(9); tTag.setEditable(false); tWord = new JTextField(7); tWord.setEditable(false); // SET THE FONT STYLES FOR THE BITS IN MAIN MEMORY ADDRESS tTag.setFont(new Font("Monospaced", Font.BOLD, 14)); tWord.setFont(new Font("Monospaced", Font.BOLD, 14)); // REGISTER LISTENERS restart.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { reStart(); } }); next.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { nextClicked = true; step(); } }); back.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { nextClicked = false; step(); } }); quit.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { int confirmQuit = JOptionPane.showConfirmDialog( null, "Really Quit?", "Quit Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); switch (confirmQuit) { case JOptionPane.YES_OPTION: removeInstance(); case JOptionPane.NO_OPTION: break; } } }); autoGen.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { autoGenerateString(); } }); selfGen.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { selfGenerateString(); } }); // DISABLE NAVIGATION BUTTONS FOR NOW next.setEnabled(false); back.setEnabled(false); // CREATE PANELS cachePanel = new FACachePanel(); memoryPanel = new MemoryPanel(); bottomPanel = new JPanel(); cache = new JPanel(); cacheHitsMisses = new JPanel(); pAutoSelfGen = new JPanel(); pAddRefStr = new JPanel(); pEastPanel = new JPanel(); pBitsInMM = new JPanel(); // ADD COMPONENTS TO THE PANELS // PANEL WITH PROGRESS UPDATE TEXT AREA AND NAVIGATION BUTTONS bottomPanel.add(lProgress); bottomPanel.add(progressScroll); bottomPanel.add(restart); bottomPanel.add(next); bottomPanel.add(back); bottomPanel.add(quit); // PANEL WITH CACHE BLOCKS, HITS AND MISSES INFO. cacheHitsMisses.add(lCacheHits); cacheHitsMisses.add(tCacheHits); cacheHitsMisses.add(lCacheMisses); cacheHitsMisses.add(tCacheMisses); cacheHMBorder = BorderFactory.createEtchedBorder(); cacheHitsMisses.setBorder(BorderFactory.createTitledBorder(cacheHMBorder, "")); cache.setLayout(new BorderLayout()); cache.add(cachePanel, "Center"); cache.add(cacheHitsMisses, "South"); // PANEL WITH ADDRESS REFERENCE STRING AND STRING GENERATION BUTTONS pAutoSelfGen.setLayout(new GridLayout(2, 1)); pAutoSelfGen.add(autoGen); pAutoSelfGen.add(selfGen); pAddRefStr.setLayout(new BorderLayout()); pAddRefStr.setPreferredSize(new Dimension(160, 400)); pAddRefStr.add(addRefStrScroll, "Center"); pAddRefStr.add(pAutoSelfGen, "South"); addRefStrBorder = BorderFactory.createEtchedBorder(); pAddRefStr.setBorder( BorderFactory.createTitledBorder(addRefStrBorder, " Address Reference String ")); // PANEL WITH THE MAIN MEMORY ADDRESS BITS INFO. pBitsInMM.setLayout(new BorderLayout()); bitsInMMBorder = BorderFactory.createEtchedBorder(); pBitsInMM.setBorder(BorderFactory.createTitledBorder(bitsInMMBorder, " Main Memory Address ")); pBitsInMM.add(tTag, "Center"); pBitsInMM.add(tWord, "East"); pBitsInMM.add(lBits, "South"); // PANEL CONTAINING THE ADDRESS REF. STRING PANEL AND BITS IN MM PANEL pEastPanel.setLayout(new BorderLayout()); pEastPanel.setPreferredSize(new Dimension(310, 650)); pEastPanel.add(pAddRefStr, "Center"); pEastPanel.add(pBitsInMM, "South"); // ADD COMPONENTS TO THE FRAME CONTAINER Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(cache, "West"); c.add(memoryPanel, "Center"); c.add(pEastPanel, "East"); c.add(bottomPanel, "South"); // INITIALIZE ARRAYS THAT HOLDS STATUS OF EMPTY AND LRU CACHE BLOCKS for (int i = 0; i < 16; i++) { statusCacheEmpty[i] = true; statusCacheLRU[i] = 0; } /* * CALL THE FUNCTION TO GENERATE THE ARRAY addresses, WHICH CONTAINS ALL THE POSSIBLE MEMORY ADDRESSES * THIS ARRAY WILL BE USEFUL IN THE AUTO GENERATION OF ADDRESSES AS WELL AS FOR VALIDATION OF * ADDRESS STRINGS INPUT BY THE USER IF HE/SHE CHOOSES SELF GENERATION. */ createAddresses(); pack(); } // END CONSTRUCTOR
// 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
/** * Appends the contents of new_text to the text area without any modifications. The caret is set * to the beginning of the text. * * @param new_text The new text to add. Nothing is done if this is null. */ public void appendText(String new_text) { if (new_text != null) { text_area.append(new_text); text_area.setCaretPosition(0); } }
private void appendOutput(String str) { if (str != null && !str.equals("")) outputArea.append(str + "\n\n"); outputArea.setCaretPosition(outputArea.getDocument().getLength()); }
/* Add a message to the message area, auto-scroll to end */ public synchronized void message(String s) { mssgArea.append(s + "\n"); mssgArea.setCaretPosition(mssgArea.getDocument().getLength()); }
// called by the Client to append text in the TextArea void append(String str) { chatArea.append(str); chatArea.setCaretPosition(chatArea.getText().length() - 1); }
// FUNCTION ALLOWING THE USER TO SELF GENERATE THE ADDRESS REFERENCE STRING UPTO A MAXIMUM OF 10 // ADDRESSES public void selfGenerateString() { int option = 0; int index = 0; // INITIALIZE THE LIST OF ADDRESS REFERENCE STRINGS // for (int i = 0; i < 10; i++) // listData[i] = ""; // SET THE VALUES OF THE CUSTOM ARGUMENTS USED IN THE UPCOMING CALL TO THE METHOD // JOptionPane.showOptionDialog JTextField textfield = new JTextField(); Object[] array = {"Enter String", textfield}; Object[] options = {"Continue", "Done"}; // ALLOW THE USER TO INPUT UPTO 10 ADDRESSES while ((option == 0) && index < 10) { // CALL THE showOptionDialog METHOD USING THE ABOVE CUSTOM ARGUMENTS option = JOptionPane.showOptionDialog( this, array, "Self Generate", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); // IF THE "CONTINUE" BUTTON WAS CLICKED THEN VALIDATE INPUT if (option == 0) { // THEN VALIDATE INPUT if ((validateInput(textfield.getText())) || (validateInput(textfield.getText().toUpperCase()))) { // IF THE INPUT IS VALID, ADD IT TO THE LIST OF ADDRESS REFERENCE STRINGS // listData[index] = textfield.getText().toUpperCase(); listData.add(textfield.getText().toUpperCase()); index++; } else // IF THE INPUT IS INVALID, NOTIFY USER AND PROMPT AGAIN JOptionPane.showMessageDialog( this, "Invalid Input. Please try again.", "Invalid Input", JOptionPane.ERROR_MESSAGE); // RESET THE TEXTFIELD textfield.setText(""); } // ELSE IF DONE BUTTON WAS CLICKED ON INPUT, VALIDATE INPUT else if ((option == 1) && ((!textfield.getText().equals("")))) { // IF INPUT WAS VALID, ADD TO ADDRESS REFERENCE STRING AND QUIT THE DIALOG BOX if ((validateInput(textfield.getText())) || (validateInput(textfield.getText().toUpperCase()))) { // listData[index] = textfield.getText().toUpperCase(); listData.add(textfield.getText().toUpperCase()); index++; tProgress.setText( "You have generated an Address Reference String of " + index + " address." + "\nPlease click on \"Next\" to continue."); tProgress.setCaretPosition(0); } else { // IF INPUT WAS INVALID, NOTIFY USER AND QUIT THE DIALOG BOX JOptionPane.showMessageDialog( this, "Invalid Input. Quitting without saving last entry.", "Invalid Input", JOptionPane.ERROR_MESSAGE); tProgress.setText( "You have generated an Address Reference String of " + index + " address." + "\nPlease click on \"Next\" to continue."); tProgress.setCaretPosition(0); } } } // PUT THE STRING OF INPUTS INTO THE ADDRESS REFERENCE STRING LISTBOX addRefStrList.setListData(listData); // ENABLE Next BUTTON AND DISABLE Back BUTTON ONLY IF AT LEAST ONE VALID ENTRY WAS MADE if (index > 0) { // moveStatus = 0; next.setEnabled(true); back.setEnabled(false); } } // END FUNCTION selfGenerateString