I am trying to highlight Java syntax using StyleRanges in SWT StyledText boxes. Here is the relevant code.
String code = text.getText();
int fromIndex = 0;
String keyword = "public";
if(code.toLowerCase().contains(keyword.toLowerCase())){
System.out.println("Match found");
Shell shell = text.getShell();
Display display = shell.getDisplay();
System.out.println("Got shell and display...");
Color orange = new Color(display, 255, 127, 0);
int index = code.indexOf(keyword, fromIndex);
int length = keyword.length();
StyleRange styleRange = new StyleRange(0, 22, orange, null,SWT.BOLD);
text.setStyleRange(styleRange);
System.out.println("colored...");
fromIndex = index;
}
but the StyleRanges do nothing? Can someone help me out with this?
Edit: If i use this new code
`private void Color_Code(StyledText text) {
Shell shell = this.getShell();
Display display = shell.getDisplay();
String[] lines = text.getText().split("\\n");
String keyWord = "public";
Color red = display.getSystemColor(SWT.COLOR_RED);
int offset = 0;
for (String line : lines)
{
int index = line.indexOf(keyWord);
if (index != -1)
{
StyleRange range = new StyleRange(index + offset, keyWord.length(), red, null, SWT.BOLD);
text.setStyleRange(range);
}
offset += line.length() + 1; // +1 for the newline character
}
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}`
Tree population code: private void Populate_Method_Tree(Tree tree) {
// TODO Auto-generated method stub
for (int i = 0; i < SampleHandler.f.MCCCLONES.size(); i++) {
int id = SampleHandler.f.MCCCLONES.get(i).getMCCID();
TreeItem temp = new TreeItem(tree, SWT.V_SCROLL);
temp.setText("MCCID: " + id);
Populate_Drop_Down(id);
}
}
Dropdown Population code:
protected void Populate_Drop_Down(int id) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
for (int i = 0; i < SampleHandler.f.MCCCLONES.size(); i++) {
if (id == SampleHandler.f.MCCCLONES.get(i).getMCCID()) {
ArrayList<String> Method_Names = new ArrayList<>();
for (int j = 0; j < SampleHandler.f.MCCCLONES.get(i)
.getMethod_Clones().size(); j++) {
String name = SampleHandler.f.MCCCLONES.get(i)
.getMethod_Clones().get(j).getMethod()
.getFileName();
String[] parts = name.split("[\\\\ .]");
Method_Names.add(parts[parts.length - 2]
+ " "
+ Integer
.toString(SampleHandler.f.MCCCLONES
.get(i).getMethod_Clones()
.get(j).getMethod()
.getMethodID()));
}
String[] Methds = new String[Method_Names.size()];
Methds = Method_Names.toArray(Methds);
combo.setItems(Methds);
combo.setText(Methds[0]);
String[] parts = Methds[0].split("[\\s+]");
int MID = Integer.parseInt(parts[1]);
Fill_Code(MID);
}
}
}
Textbox filling code:
private void Fill_Code(int MID) {
// TODO Auto-generated method stub
for (int i = 0; i < SampleHandler.f.METHODS.size(); i++) {
if (SampleHandler.f.METHODS.get(i).getMethodID() == MID) {
text.setText(SampleHandler.f.METHODS.get(i).getCode());
//Color_Code(text);
}
}
}
it highlight the word public in my first instance but stops populating my dropdown menu and tree.
There has to be something wrong with your other code. Everything works just fine here.
Here is an example:
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
StyledText text = new StyledText(shell, SWT.BORDER | SWT.MULTI | SWT.WRAP);
text.setText("public class Text\n{\n public static void main(String[] args)\n {\n System.out.println(\"Text\");\n }\n}");
String[] lines = text.getText().split("\\n");
String keyWord = "public";
Color red = display.getSystemColor(SWT.COLOR_RED);
int offset = 0;
for (String line : lines)
{
int index = line.indexOf(keyWord);
if (index != -1)
{
StyleRange range = new StyleRange(index + offset, keyWord.length(), red, null, SWT.BOLD);
text.setStyleRange(range);
}
offset += line.length() + 1; // +1 for the newline character
}
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
Looks like this:
Related
I'm trying to quickly highlight my specific text in JTextArea. The code I need is running too slow, and I would like to know if there is a faster way to highlight text without crashing the whole application.
I have over 5000 words to scroll through and see if there is a need to highlight them or not, but this code doesn't work great for me. I'm looking for a better way to do it. This is my code:
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter
{
public MyHighlightPainter(Color color) {
super(color);
}
}
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.yellow);
public void Highligh(JTextComponent textComp, String pattern)
{
try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
for(int pos = 0; (pos=text.toUpperCase().indexOf(pattern.toUpperCase(),pos))>=0; pos += pattern.length())
hilite.addHighlight(pos, pos+pattern.length(), myHighlightPainter);
} catch (Exception e) {}
}
public void keyReleased(KeyEvent arg0) {
String text = vocabolario.getText();
String[] parziale = new String[5000];
try {
String p1 = "SELECT definizione FROM Cherubini WHERE definizione LIKE '%", p2 = "%';", px = vocabolario.getText(), query = p1+px+p2;
ResultSet rs = Main.conn().createStatement().executeQuery(query);
while(rs.next())
{
String[] dati = { rs.getString("definizione") };
for(int i = 0; i < dati.length; i++) { parziale[i] = dati[i]; textArea.append(parziale[i]+"\n"); }
}
}
catch(SQLException exc) {}
Highligh(textArea,vocabolario.getText());
}
});
for(int pos = 0; (pos=text.toUpperCase().indexOf(pattern.toUpperCase(),pos))>=0; pos += pattern.length())
Why do you keep converting the data to upper case? This should only be done once:
String upperText = text.toUpperCase();
String upperPattern = pattern.toUpperCase();
for(int pos = 0; (pos = upperText.indexOf(upperPattern, pos)) >= 0; pos += pattern.length())
So I build a shell that looks like the following
After I click the change path button, I prompt for the path and then set the text. The problem is after doing so new text gets cut off if its too long like so.
I am using a Label to display the path, and the only method I'm using in the listener regarding the Laebl is the setText() method. Is there a way to not have this happen? I am using SWT and prefer to maintain the grid layout so I can have the 2 columns. Any info would be helpful. Thank you.
Here's the code
String unit[] = {"Pixil", "Inch"};
final CustomAttribute realWidth = new CustomAttribute(String.valueOf(obj.getGraph().getWidth(null)));
final CustomAttribute realHeight = new CustomAttribute(String.valueOf(obj.getGraph().getHeight(null)));
double[] sizes = obj.convertToSizes();
if(sizes != null){
realWidth.setValue(sizes[0]);
realHeight.setValue(sizes[1]);
}
final Shell shell = new Shell(d);
shell.setImage(ApplicationPlugin.getImage(ApplicationPlugin.QUATTRO_ICON));
shell.setLayout(new org.eclipse.swt.layout.GridLayout(2,true));
shell.setText(EDIT_IMG_WINDOW_TITLE);
//width info
final Label labelWidth = new Label(shell, SWT.HORIZONTAL);
final Text textWidth = new Text(shell,SWT.SINGLE | SWT.BORDER);
//height info
final Label labelHeight = new Label(shell, SWT.HORIZONTAL);
final Text textHeight = new Text(shell,SWT.SINGLE | SWT.BORDER);
//units info
final Combo unitCombo = new Combo (shell, SWT.READ_ONLY);
final Button ratioBox = new Button (shell, SWT.CHECK);
ratioBox.setText(EDIT_IMG_RADIO);
//path info
final Button pathButton = new Button (shell, SWT.PUSH);
pathButton.setText(EDIT_IMG_PATH);
final Label pathText = new Label(shell, SWT.HORIZONTAL);
pathText.setText(obj.getTextData()[0]);
Button change = new Button (shell, SWT.PUSH);
change.setText(EDIT_IMG_SAVE_BUTTON);
ModifyListener heightListener = new ModifyListener(){
public void modifyText(ModifyEvent e) {
if(realImgListen && textHeight.getText() != ""){
realImgListen = false;
try{
double oldHeight = realHeight.getDouble();
double newHeight = Double.parseDouble(textHeight.getText());
double oldWidth = Double.parseDouble(textWidth.getText());
if(unitCombo.getSelectionIndex() == 1){
newHeight = newHeight * designer.getPixilPerInch();
oldWidth = oldWidth * designer.getPixilPerInch();
}
realHeight.setValue(newHeight);
double[] sizes = obj.convertToSizes();
if(sizes != null)
realWidth.setValue(sizes[0]);
else
realWidth.setValue(oldWidth);
if(realHeight.getDouble() > SheetCanvas.sheetYSize)
realHeight.setValue(SheetCanvas.sheetYSize);
if(realHeight.getDouble() < 1)
realHeight.setValue(1);
if(ratioBox.getSelection() == true){
double scale = Double.parseDouble(realHeight.getValue()) / oldHeight;
realWidth.setValue(String.valueOf(realWidth.getDouble()*scale));
if(unitCombo.getSelectionIndex() == 0)
textWidth.setText(String.valueOf((int)Math.round(Double.parseDouble(realWidth.getValue()))));
else
textWidth.setText(String.valueOf(Double.parseDouble(realWidth.getValue())/designer.getPixilPerInch()));
}
obj.storeSizingInfo(realWidth.getDouble(), realHeight.getDouble(), 0);
realImgListen = true;
}
catch(NumberFormatException e2){
realImgListen = true;
}
}
}
};
ModifyListener widthListener = new ModifyListener(){
public void modifyText(ModifyEvent e) {
if(realImgListen && textHeight.getText() != ""){
realImgListen = false;
try{
double oldWidth = realWidth.getDouble();
double newWidth = Double.parseDouble(textWidth.getText());
double oldHeight = Double.parseDouble(textHeight.getText());
if(unitCombo.getSelectionIndex() == 1){
newWidth = newWidth * designer.getPixilPerInch();
oldHeight = oldHeight * designer.getPixilPerInch();
}
realWidth.setValue(newWidth);
double[] sizes = obj.convertToSizes();
if(sizes != null)
realHeight.setValue(sizes[1]);
else
realHeight.setValue(oldHeight);
if(realWidth.getDouble() > SheetCanvas.sheetYSize)
realWidth.setValue(SheetCanvas.sheetYSize);
if(realWidth.getDouble() < 1)
realWidth.setValue(1);
if(ratioBox.getSelection() == true){
double scale = Double.parseDouble(realWidth.getValue()) / oldWidth;
realHeight.setValue(String.valueOf(realHeight.getDouble()*scale));
if(unitCombo.getSelectionIndex() == 0)
textHeight.setText(String.valueOf((int)Math.round(Double.parseDouble(realHeight.getValue()))));
else
textHeight.setText(String.valueOf(Double.parseDouble(realHeight.getValue())/designer.getPixilPerInch()));
}
obj.storeSizingInfo(realWidth.getDouble(), realHeight.getDouble(), 0);
realImgListen = true;
}
catch(NumberFormatException e2){
realImgListen = true;
}
}
}
};
textHeight.addModifyListener(heightListener);
textWidth.addModifyListener(widthListener);
unitCombo.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
realImgListen = false;
if(unitCombo.getSelectionIndex() == 0){
textWidth.setText(String.valueOf((int)Math.rint(realWidth.getDouble())));
textHeight.setText(String.valueOf((int)Math.rint(realHeight.getDouble())));
}
else{
textWidth.setText(String.valueOf(realWidth.getDouble()/designer.getPixilPerInch()));
textHeight.setText(String.valueOf(realHeight.getDouble()/designer.getPixilPerInch()));
}
realImgListen = true;
}
});
change.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
Double width = realWidth.getDouble();
Double height = realHeight.getDouble();
String line1;
if(obj.getTextData() != null)
line1 = obj.getTextData()[0];
else
line1 = null;
String[] textData = {line1,null};
obj.setTextData(textData);
obj.storeSizingInfo(Math.rint(width), Math.rint(height),0);
designer.updateDataFromSource(settings);
designer.repaint();
updatePanelButtons();
shell.close();
}
});
pathButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//path button
String path = null;
path = getPathFromBrowser(FILE_CHOOSER_IMAGE_TITLE_STR,DEFAULT_PATH,acceptedImgFormats,null,SWT.OPEN);
pathText.setText(path);
if(path != null){
String[] paths = settings.getCustomImagePath();
int pathIndex = 0;
for(int i = 0; i < paths.length; i++){
if(obj.getTextData()[0].equals(paths[i]))
pathIndex = i;
}
paths[pathIndex] = path;
settings.setCustomImagePath(paths);
paths = settings.getCustomImageChoices();
paths[pathIndex] = getFileNameFromPath(path);
settings.setCustomImageChoices(paths);
designer.updateDataFromSource(settings);
String[] textData = obj.getTextData();
textData[0] = path;
if(textData.length > 1)
textData[1] = null;
obj.setTextData(textData);
}
}
});
textWidth.setTextLimit(7);
textHeight.setTextLimit(7);
labelWidth.setText(EDIT_IMG_WIDTH);
labelHeight.setText(EDIT_IMG_HEIGHT);
unitCombo.setItems(unit);
unitCombo.select(0);
ratioBox.setSelection(true);
org.eclipse.swt.graphics.Rectangle clientArea = shell.getClientArea();
unitCombo.setBounds(clientArea.x, clientArea.y, 300, 200);
shell.pack();
shell.open();
Shell shellTemp = SWT_AWT.new_Shell(d, designer);
Monitor primary = d.getPrimaryMonitor();
org.eclipse.swt.graphics.Rectangle bounds = primary.getBounds();
org.eclipse.swt.graphics.Rectangle rect = shell.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
shell.setLocation(x, y);
shell.moveAbove(shellTemp);
shellTemp.dispose();
shell.addListener(SWT.Close, new Listener() {
#Override
public void handleEvent(Event event) {
editingImg();
}
});
realImgListen = false;
textWidth.setText(String.valueOf((int)Double.parseDouble(realWidth.getValue())));
textHeight.setText(String.valueOf((int)Double.parseDouble(realHeight.getValue())));
realImgListen = true;
The width of your columns is currently being set to the width of the widest control - probably 'Maintain Image Ratio'. If you set the the path text to anything longer than that it will be truncated.
You could set a width hint on the path control to set its size:
GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false);
data.widthHint = 100; // You choose the width
pathText.setLayoutData(data);
Note that you have specified that the columns are of equal width so this will add similar space to the first column. You might want to switch to unequal width columns.
Alternatively you can ask the Shell to recalculate the size after you set the new text. Just call:
shell.pack();
It looks like that you are redrawing the change path label components and you are not wrapping the label .
That why at the time of redrawing some part of the text is not visible.
Use warping or you can also increase the screen size
Firstly, I would like to say I am not asking for an answer more so advice so I can learn from this problem. Every time I run my code I get Array Index Out of Bounds on Line 254 of the ArrayOperations java file.
if (SearchKey == tempArray[middle])
I have added as many checks as I possibly can to this code and also have commented it as much as possible for your ease. Once again I am looking for advice on this not just a direct answer if possible. The Error always seems to give me the negative version of 1/2 of my data items
ex: 100,000 data items, Array Index Out of Bounds: -49,999.
import javax.swing.*;
// File-related imports
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class ArrayOperations
{
// File Parameters
String DataFilePath;
String DataFileName;
String KeysFilePath;
String KeysFileName;
int NumberOfDataItems;
int NumberOfKeys;
int N;
int BucketHashArraySize;
int NoBuckets;
//Array
int[] OriginalArray = new int[1000000];
int[] SortedArray = new int[1000000];
int[] HashedArray = new int[2000000];
int[] BucketHashedArray = new int[2000000];
int[] KeysArray = new int[1000000];
long SSAverageAccessTime;
long SSAverageCompSuc;
long SSAverageCompFailed;
long SSNumberKeysSuc;
long SSNumberKeysFailed ;
long BSAverageAccessTime;
long BSAverageCompSuc ;
long BSAverageCompFailed;
long BSNumberKeysSuc ;
long BSNumberKeysFailed ;
long HSAverageAccessTime;
long HSAverageCompSuc ;
long HSAverageCompFailed;
long HSNumberKeysSuc ;
long HSNumberKeysFailed ;
public ArrayOperations()
{
// File Parameters
DataFilePath = null;
DataFileName = null;
KeysFilePath = null;
KeysFileName = null;
NumberOfDataItems=0;
NumberOfKeys =0;
N =0;
BucketHashArraySize = 0;
NoBuckets =0;
// Statistics
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
}
public void ReadDataFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
DataFilePath = chooser.getSelectedFile().getPath();
DataFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (DataFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(DataFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
OriginalArray[index] = integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfDataItems = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfDataItems = 0;
}
public void ReadKeysFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Keys File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
KeysFilePath = chooser.getSelectedFile().getPath();
KeysFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (KeysFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(KeysFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
KeysArray[index]= integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfKeys = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfKeys = 0;
}
public void SequentialSearch()
{
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
for (int k=0; k<NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
for (int d=0; d<NumberOfDataItems; d++)
{
TotalNumberOfComparisons++;
if (SearchKey == OriginalArray[d])
{
found = true;
}
if (found)break;
}
if(found)
{
SSAverageCompSuc = SSAverageCompSuc + TotalNumberOfComparisons;
SSNumberKeysSuc ++;
}
else
{
SSAverageCompFailed = SSAverageCompFailed + TotalNumberOfComparisons;
SSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
SSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
SSAverageAccessTime = 0;
if(SSNumberKeysSuc != 0)
SSAverageCompSuc = Math.round (SSAverageCompSuc / SSNumberKeysSuc) ;
else
SSAverageCompSuc = 0;
if (SSNumberKeysFailed != 0)
SSAverageCompFailed = Math.round (SSAverageCompFailed / SSNumberKeysFailed) ;
else
SSNumberKeysFailed = 0;
return;
}
public void BinarySearch()
{
// makes a temporary array the length of the number of data items we gave it int[] tempArray = new int[NumberOfDataItems];
// copies a portion of the original array (origionalArray = new int[1000000] above) that has the data inputs
// we are copying only the portion of the original array the was given the data inputs when we opened the data item .txt
for (int i = 0; i < NumberOfDataItems; i ++)
{
tempArray[i]=OriginalArray[i];
}
// takes the temporary array and sorts it
java.util.Arrays.sort(tempArray);
BSAverageAccessTime = 0;
BSAverageCompSuc = 0;
BSAverageCompFailed = 0;
BSNumberKeysSuc = 0;
BSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
int low = 0;
int high = tempArray.length-1;
// sets the midpoint
int middle = (low-high)/2;
for(int k = 0; k<NumberOfKeys; k++)
{
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
for (int d=0; d< Math.log(tempArray.length -1); d++)
{
TotalNumberOfComparisons++;
// makes sure low doesn't go out of bounds
if (low < 0)
{
low = 0;
}
// make sure high doesn't go out of bounds
if(high >= tempArray.length)
{
high = tempArray.length-1;
}
// checks the midpoint against the key we are using
if (SearchKey == tempArray[middle])
{
found = true;
}
// makes sure that if the midpoint doesn't equal the key we get false
else
if (low == high && SearchKey != tempArray[middle])
{
found = false;
}
// if the key is greater than the middle we check the upper portion
else
if (SearchKey > tempArray[middle])
{
low = (middle +1);
}
// if the key is less than the middle we check the lower portion
else
if (SearchKey < tempArray[middle])
high = (middle -1);
if (found)break;
}
if(found)
{
BSAverageCompSuc = BSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
BSAverageCompFailed = BSAverageCompFailed + TotalNumberOfComparisons;
BSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
BSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
BSAverageAccessTime = 0;
if(BSNumberKeysSuc != 0)
BSAverageCompSuc = Math.round (BSAverageCompSuc / BSNumberKeysSuc) ;
else
BSAverageCompSuc = 0;
if (BSNumberKeysFailed != 0)
BSAverageCompFailed = Math.round (BSAverageCompFailed / BSNumberKeysFailed) ;
else
BSNumberKeysFailed = 0;
return;
}
public void HashedSearch()
{
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
}
public int FindPrime()
{
return 0;
}
public void Initialize()
{
}
public void BHSearch()
{
}
}
Here is the Java GUI Code:
// GUI-related imports
import java.awt.*;
import java.awt.event.*;
// File-related imports
import java.io.IOException;
public class Project04 extends Frame implements ActionListener
{
ArrayOperations arr = new ArrayOperations();
String command = "";
public static void main(String[] args)
{
Frame frame = new Project04();
frame.setResizable(false);
frame.setSize(900,620);
frame.setVisible(true);
}
public Project04()
{
setTitle("Search Routines");
// Create Menu Bar and menu items
MenuBar mb = new MenuBar();
setMenuBar(mb);
// Create Menu Group Labeled "File"
Menu FileMenu = new Menu("File");
// Add it to Menu Bar
mb.add(FileMenu);
// Create Menu Items
// Add action Listener
// Add to "File" Menu Group
MenuItem miOpen = new MenuItem("Open");
miOpen.addActionListener(this);
FileMenu.add(miOpen);
MenuItem miExit = new MenuItem("Exit");
miExit.addActionListener(this);
FileMenu.add(miExit);
// Create Menu Group Labeled "File"
Menu SearchMenu = new Menu("Search");
// Add it to Menu Bar
mb.add(SearchMenu);
// Create Menu Items
// Add action Listener
// Add to "Search" Menu Group
MenuItem miSequentialSearch = new MenuItem("Sequential Search");
miSequentialSearch.addActionListener(this);
SearchMenu.add(miSequentialSearch);
MenuItem miBinarySearch = new MenuItem("Binary Search");
miBinarySearch.addActionListener(this);
SearchMenu.add(miBinarySearch);
MenuItem miHashedSearch = new MenuItem("Hashed Search");
miHashedSearch.addActionListener(this);
SearchMenu.add(miHashedSearch);
WindowListener l = new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
public void windowActivated(WindowEvent ev)
{
repaint();
}
public void windowStateChanged(WindowEvent ev)
{
repaint();
}
};
ComponentListener k = new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
repaint();
}
};
// register listeners
this.addWindowListener(l);
this.addComponentListener(k);
}
//******************************************************************************
// called by windows manager whenever the application window performs an action
// (select a menu item, close, resize, ....
//******************************************************************************
public void actionPerformed (ActionEvent ev)
{
// figure out which command was issued
command = ev.getActionCommand();
// take action accordingly
if("Open".equals(command))
{
try
{
arr.ReadDataFile();
arr.ReadKeysFile();
}
catch (IOException ioe)
{
System.exit(0);
}
repaint();
}
else
if("Exit".equals(command))
{
System.exit(0);
}
else
if("Sequential Search".equals(command))
{
arr.SequentialSearch();
repaint();
}
if("Binary Search".equals(command))
{
arr.BinarySearch();
repaint();
}
if("Hashed Search".equals(command))
{
arr.HashedSearch();
repaint();
}
if("Bucket Hashed Search".equals(command))
{
arr.BHSearch();
repaint();
}
}
//********************************************************
// called by repaint() to redraw the screen
//********************************************************
public void paint(Graphics g)
{
if("Open".equals(command))
{
// Acknowledge that file was opened
if (arr.DataFileName != null)
{
g.drawString("File -- "+arr.DataFileName+" -- was successfully opened", 300, 200);
g.drawString("Number of Data Items = "+Integer.toString(arr.NumberOfDataItems), 330, 250);
}
else
{
g.drawString("NO Data File is Open", 300, 200);
}
if (arr.KeysFileName != null)
{
g.drawString("File -- "+arr.KeysFileName+" -- was successfully opened", 300, 300);
g.drawString("Number of Keys = "+Integer.toString(arr.NumberOfKeys), 330, 350);
}
else
{
g.drawString("NO Keys File is Open", 300, 300);
}
return;
}
if("Sequential Search".equals(command) || "Binary Search".equals(command)||
"Hashed Search".equals(command) || "Bucket Hashed Search".equals(command) )
{
g.drawRect(100, 100, 700, 420);
g.drawString("Experiment", 135, 200);
g.drawLine(250,100,250,520);
g.drawString("Data File Attributes -- "+Integer.toString(arr.NumberOfDataItems)+" Data Items", 450, 130);
g.drawString("Key File Attributes -- "+Integer.toString(arr.NumberOfKeys)+" Keys", 450, 155);
g.drawLine(250,175,800,175);
g.drawString("Measured Criteria", 475,190 );
g.drawLine(250,215,800,215);
g.drawString("Successful Search", 410, 230);
g.drawString("Unccessful Search", 640, 230);
g.drawLine(360,245,800,245);
g.drawLine(100,310,800,310);
g.drawString("Sequential Search", 110, 325);
g.drawLine(100,340,800,340);
g.drawString("Average", 285, 260);
g.drawString("Access", 285, 275);
g.drawString("Time", 290, 290);
g.drawLine(360,215,360,520);
g.drawString("#", 400, 260);
g.drawString("Keys", 400, 275);
g.drawString("Found", 390, 290);
g.drawLine(470,245,470,520);
g.drawString("Average", 500, 260);
g.drawString("No. Of", 500, 275);
g.drawString("Comparisons", 485, 290);
g.drawLine(580,215,580,520);
g.drawString("# ", 620, 260);
g.drawString("Keys", 620, 275);
g.drawString("Not Found", 600, 290);
g.drawLine(690,245,690,520);
g.drawString("Average", 720, 260);
g.drawString("No. Of", 720, 275);
g.drawString("Comparisons", 700, 290);
g.drawString(Long.toString(arr.SSAverageAccessTime), 255, 325);
g.drawString(Long.toString(arr.SSNumberKeysSuc), 365, 325);
g.drawString(Long.toString(arr.SSAverageCompSuc), 475, 325);
g.drawString(Long.toString(arr.SSNumberKeysFailed), 585, 325);
g.drawString(Long.toString(arr.SSAverageCompFailed), 695, 325);
g.drawString("Binary Search", 110, 355);
g.drawLine(100,370,800,370);
g.drawString(Long.toString(arr.BSAverageAccessTime), 255, 355);
g.drawString(Long.toString(arr.BSNumberKeysSuc), 365, 355);
g.drawString(Long.toString(arr.BSAverageCompSuc), 475, 355);
g.drawString(Long.toString(arr.BSNumberKeysFailed), 585, 355);
g.drawString(Long.toString(arr.BSAverageCompFailed), 695, 355);
g.drawString("Hashed Search", 110, 385);
g.drawLine(100,400,800,400);
g.drawString(Long.toString(arr.HSAverageAccessTime), 255, 385);
g.drawString(Long.toString(arr.HSNumberKeysSuc), 365, 385);
g.drawString(Long.toString(arr.HSAverageCompSuc), 475, 385);
g.drawString(Long.toString(arr.HSNumberKeysFailed), 585, 385);
g.drawString(Long.toString(arr.HSAverageCompFailed), 695, 385);
// add code to display results for other searches
}
}
}
You are doing a wrong calculation
change below:
int middle = (low-high)/2;
to:
int middle = (high-low)/2;
low is always less than high so you are getting a negative number and that negative index will not exist in your array.
Although I have not checked any other possible problems or the algorithm's validity, the above is the solution to the problem you are having
I need help tweaking my code. I need to write a program that outputs the count of individual ascii characters in a txt file that the user uploads, but I'm having a lot of problems trying to get the array that I count into the GUI portion of the program that "draws" the data on the screen.
I have the output looking how I want, but I can't figure out how to get the character count up there
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.FileReader; // both needed
import java.io.BufferedReader;
import java.io.IOException;
public class textreader extends Frame implements ActionListener
{
String dataFilePath = null;
String dataFileName = null;
int[] counter = new int[256];
String command = "";
public static void main(String[] args)
{
Frame frame = new textreader();
frame.setResizable(true);
frame.setSize(1000,850);
frame.setVisible(true);
}
public textreader()
{
setTitle("Text File Processing");
// Menu Creation
MenuBar mn = new MenuBar();
setMenuBar(mn);
// Create "File" and add it
Menu fileMenu = new Menu("File");
mn.add(fileMenu);
// Create Menu Items, Add action Listener, Add to "File" Menu Group
// Open file
MenuItem miOpen = new MenuItem("Open");
miOpen.addActionListener(this);
fileMenu.add(miOpen);
// Process file
MenuItem miProcess = new MenuItem("Process");
miProcess.addActionListener(this);
fileMenu.add(miProcess);
// Exit program
MenuItem miExit = new MenuItem("Exit");
miExit.addActionListener(this);
fileMenu.add(miExit);
// To Terminate
WindowListener d = new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
public void windowActivated(WindowEvent ev)
{
repaint();
}
public void windowStateChanged(WindowEvent ev)
{
repaint();
}
};
ComponentListener k = new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
repaint();
}
};
// listener registry
this.addWindowListener(d);
this.addComponentListener(k);
}
public void actionPerformed (ActionEvent ev)
{
// which command was issued?
command = ev.getActionCommand();
// act
if("Open".equals(command))
{
dataFilePath = null;
dataFileName = null;
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
dataFilePath = chooser.getSelectedFile().getPath();
dataFileName = chooser.getSelectedFile().getName();
}
repaint();
}
else
if("Process".equals(command))
{
try
{
// Initialize
int[] aCount = new int[256];
// "Instantiate" streams
BufferedReader inputStream = new BufferedReader(new FileReader(dataFilePath));
// read the file line by line and count the characters read
String line = null;
char c = 0;
int lineLength = 0;
int charValue = 0;
while ((line = inputStream.readLine()) != null)
{
// ********* process line
for (int i = 0; i < line.length(); i++)
{
char ch = line.charAt(i);
if (ch >= 0 && ch <= 255)
{
counter[(int)ch]++;
}
else
{ // silently ignore non-ASCII characters
}
// count newline at the end
counter['\n']++;
}
}
}
catch(IOException ioe)
{
System.out.print("You want to run that by me again?");
}
repaint();
}
else
if("Exit".equals(command))
{
System.exit(0);
}
}
//********************************************************
//called by repaint() to redraw the screen
//********************************************************
public void paint(Graphics g)
{
if("Open".equals(command))
{
// Acknowledge that file was opened
if (dataFileName != null)
{
g.drawString("File -- "+dataFileName+" -- was successfully opened", 400, 400);
}
else
{
g.drawString("NO File is Open", 400, 400);
}
return;
}
else
if("Process".equals(command))
{
for(int i = 0; i < 256; i++)
{
int x = 100;
int y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 30;
int line = 0;
for(int j = 0; j < 256; j++)
{
line++;
g.drawString(Integer.toString(j), x, y);
g.drawString(Character.toString((char)j), x + 50, y); // Converts the # to a char, then to a String
// This part of the code adds a new column when the flag reaches 43
if(line == 45)
{
x = x + 150;
y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 15;
line = 0;
}
y = y+15;
}
}
return;
}
}
}
Your charValue variable appears to break your logic. You should remove it. This is sufficient:
for (int i=0; i<alphabetArray.length; i++)
alphabetArray[i] = 0; // set initial values
while ((line = inputStream.readLine()) != null) {
for(int i=0; i<line.length(); i++)
alphabetArray[(int)line.charAt(i)]++; // use the ASCII value of the character as an index
}
Your alphabet counter also seems to go out of scope. Either (1) make alphabetArray an instance variable of the class, or (2) display its contents before it goes out of scope. I think #1 is preferable.
I'd also be concerned about this line:
System.out.println(c + " : "+ char.alphabetArray[i]);
char is a datatype, and alphabetArray does not exist inside of it (and technically doesn't exist anywhere at this point since it's gone out of scope). c is also undefined. Take advantage of ASCII values! However, be careful printing non-printable characters and such. Your output will look really funky.
System.out.println((char)i + " : "+ alphabetArray[i]);
Of course, you'd still need to make alphabetArray accessible somehow.
I have a table with 4 columns. I try to integrate a ToolTip for all cells of the third column.
With my Code the ToolTip only appears for the cells of the first column.
This is my Code:
protected void checkAction() throws Exception {
System.out.println("Start Test");
//Erstellen einer neuen Shell
final Shell shell = new Shell();
shell.setSize(280, 300);
shell.setText("Testtabelle");
//Erstellen einer neuen Tabelle
final Table table = new Table(shell, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
table.setLinesVisible(true);
table.setHeaderVisible(true);
//Einlesen der Überschriften und Vergabe der Namen
String[] titles = {"Element", "Stage", "Type", "Generate-User", "Change-User" };
for (int i = 0; i < titles.length; i++) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(titles[i]);
}
// Inhalte hinzufügen
final int count = 4;
for (int i = 0; i < count; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0, "Test "+i);
item.setText(1, ""+(i+1));
item.setText(2, "Testtype");
item.setText(3, "562910");
item.setText(4, "423424");
}
// Disable native tooltip
table.setToolTipText ("");
// Implement a "fake" tooltip
final Listener labelListener = new Listener () {
public void handleEvent (Event event) {
Label label = (Label)event.widget;
Shell shell = label.getShell ();
switch (event.type) {
case SWT.MouseDown:
Event e = new Event ();
e.item = (TableItem) label.getData ("_TABLEITEM");
// Assuming table is single select, set the selection as if
// the mouse down event went through to the table
table.setSelection (new TableItem [] {(TableItem) e.item});
table.notifyListeners (SWT.Selection, e);
shell.dispose ();
table.setFocus();
break;
case SWT.MouseExit:
shell.dispose ();
break;
}
}
};
Listener tableListener = new Listener () {
Shell tip = null;
Label label = null;
public void handleEvent (Event event) {
switch (event.type) {
case SWT.Dispose:
case SWT.KeyDown:
case SWT.MouseMove: {
if (tip == null) break;
tip.dispose ();
tip = null;
label = null;
break;
}
case SWT.MouseHover: {
TableItem item = table.getItem (new Point (event.x, event.y));
if (item != null) {
if (tip != null && !tip.isDisposed ()) tip.dispose ();
tip = new Shell (shell, SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL);
FillLayout layout = new FillLayout ();
layout.marginWidth = 2;
tip.setLayout (layout);
label = new Label (tip, SWT.NONE);
label.setData ("_TABLEITEM", item);
if (item.getText().equals("Test 3")){
label.setText ("Jonas Intfeld");
}
else{
label.setText (item.getText ());
}
label.addListener (SWT.MouseExit, labelListener);
label.addListener (SWT.MouseDown, labelListener);
Point size = tip.computeSize (SWT.DEFAULT, SWT.DEFAULT);
Rectangle rect = item.getBounds (0);
Point pt = table.toDisplay (rect.x, rect.y);
tip.setBounds (pt.x, pt.y, size.x, size.y);
tip.setVisible (true);
}
}
}
}
};
table.addListener (SWT.Dispose, tableListener);
table.addListener (SWT.KeyDown, tableListener);
table.addListener (SWT.MouseMove, tableListener);
table.addListener (SWT.MouseHover, tableListener);
// Tabelle und Shell Packen
for (int i = 0; i < titles.length; i++) {
table.getColumn(i).pack();
}
table.setSize(table.computeSize(SWT.DEFAULT, 200));
shell.pack();
// Shell öffnen
try { shell.open();
} catch (SWTException e) {
System.out.println("Test: "+e);
shell.close();
}
}
Is there any way to activate the Tooltip for the 3. Column ?
At the moment when I move over the cells in the 3. column the Tooltip appears for the 1. column.
Maybe the best option is to search the column by title?
Your problem is this line:
Rectangle rect = item.getBounds(0);
You are asking for the bounds of the first column. Just change the index to the column where you want your tooltip to appear and you'll be fine:
Rectangle rect = item.getBounds(2);
If you need to get the column index from the mouse position, use this code:
Point point = new Point(event.x, event.y);
int column = 0;
for (int i = 0; i < table.getColumnCount(); i++)
{
if (item.getBounds(i).contains(point))
{
column = i;
break;
}
}
Rectangle rect = item.getBounds(column);