Solved

How to change cursor state based on it location in JAVA?

Posted on 2013-11-21
7
283 Views
Last Modified: 2013-11-22
Hi,
I am working on a GUI in Java SWT. This gui has a dialog box where it does some processing in the worker thread. During this time, I show a busy cursor (spinner). The cursor is in spinning state while the process is going on.

If I move the cursor, to the top of the dialog box where we have the blue narrow area (on Windows it's blue by default) the cursor turns out to be a normal cursor.

So, I would like to have the same behavior when I hover over an icon on the dialog box because the cursor is actionable but the spinner makes it look like it cannot do anything.

How can I change the cursor state based on its location?

Please see my code below: (Line 385)

public class ChangeListDlg extends Dialog {
    
    public static SelectedFileFoldersModel model = new SelectedFileFoldersModel();
    public static Display display;
    public static String changelistNum = "";
    
    public String getFileFolders()
    {
        return model.getFileOrFolderData();
    }

    public ChangeListDlg(Shell parent) {
        super(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.APPLICATION_MODAL);
    }
    
    public void open() {
        Shell shell = new Shell(getParent(), getStyle());
        shell.setText("Select changelist");
        try {
			createContents(shell);
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ConfigException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchObjectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ResourceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}               
        
        shell.pack();
        shell.open();
        
        
        int frameX = shell.getSize().x - shell.getClientArea().width;
        int frameY = shell.getSize().y - shell.getClientArea().height;
        shell.setSize(500 + frameX, 300 + frameY); 
        
        
     // Move the dialog to the center of the top level shell.
        Rectangle shellBounds = getParent().getBounds();
        Rectangle dialogSize = shell.getBounds();

        shell.setLocation(
          shellBounds.x + (shellBounds.width - dialogSize.width) / 2,
          shellBounds.y + (shellBounds.height - dialogSize.height) / 2 );
             
        
        display = getParent().getDisplay();
        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }

    public List<IClientSummary> getAllPerforceWorkspaces(IOptionsServer p4d, String userName){
                        
            //for getting all the workspaces
            GetClientsOptions clientOptions = new GetClientsOptions(0, userName, null);
            List<IClientSummary> clientSummaryList = null;
			try {
				clientSummaryList = p4d.getClients(clientOptions);
			} catch (P4JavaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            //System.out.println(clientSummaryList.size());           

        return clientSummaryList;
    }

       
    private void createContents(final Shell shell) throws ConnectionException, AccessException, RequestException, ConfigException, NoSuchObjectException, ResourceException, URISyntaxException {
    	
    	//Connect to Perforce Server
    	final IOptionsServer p4d = ServerFactory.getOptionsServer(
			        ServerFactory.DEFAULT_PROTOCOL_NAME 
			        + "://" + "someserver", null);
			
			p4d.setUserName("tolgar");			

			p4d.connect();
        

        String userName = System.getProperty("user.name");
        //Get the workspace and changelist information from Perforce
        List<IClientSummary> clientSummaryList = getAllPerforceWorkspaces(p4d, userName);
                
        shell.setLayout(new GridLayout(1, false));

        Composite workspaceComp = new Composite(shell, SWT.NONE);
        workspaceComp.setLayout(new RowLayout());
        
        Label label_workspace = new Label(workspaceComp, SWT.NONE);
        label_workspace.setText("Workspace:");
            
        final Combo combo_workspaces = new Combo(workspaceComp, SWT.READ_ONLY);
        combo_workspaces.setEnabled(true);
        
        
        //public static Table table;
    	final List<Integer> changeListsArray = new ArrayList<Integer>();
    	final List<StringBuilder> fileListArray = new ArrayList<StringBuilder>();
    	final List<String> stateArray = new ArrayList<String>();
    	//final List<String> changeListDescriptionsArray = new ArrayList<String>();

        List<String> workspacesArray = new ArrayList<String>();
        final String[] changelistStateArray = {"Pending", "Shelved", "Submitted"};     
        
        //This is to create the data(changelist number, file name, description) in each column using P4JAVA
        final GetChangelistsOptions getoptions = new GetChangelistsOptions();
        for(IClientSummary eachChangeSummary : clientSummaryList){
            String eachClientName = eachChangeSummary.getName();
            workspacesArray.add(eachChangeSummary.getName());
        }
        
        combo_workspaces.setItems(workspacesArray.toArray(new String[workspacesArray.size()]));


        // ----------- the table -----------------
        GridLayout groupLayoutTable = new GridLayout();
        Group groupTable = new Group(shell, SWT.NONE);       
        groupTable.setLayout(groupLayoutTable);        
        
        final Table table = new Table(groupTable, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.WRAP | SWT.MULTI | SWT.CENTER | SWT.CHECK );
        TextCellEditor edit =new TextCellEditor(table,SWT.V_SCROLL);
        GridData tableGridData = new GridData(GridData.FILL_BOTH);
        //tableGridData.horizontalSpan = 2;
        tableGridData.horizontalAlignment = SWT.FILL;
        tableGridData.grabExcessHorizontalSpace = true;
        tableGridData.verticalAlignment = SWT.FILL;
        tableGridData.grabExcessVerticalSpace = true;
        groupTable.setLayoutData(tableGridData);
        
        table.setLinesVisible(true);
        table.setHeaderVisible(true);
        table.getVerticalBar().setVisible(true);
        final String[] titles = { " ", "  Status  ", "Changelist", "File(s)"};
        
        //This is to create the column titles
        for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
            TableColumn column = new TableColumn(table, SWT.NULL);
            column.setText(titles[loopIndex]);
        }
        
        int frameShellWidth = shell.getSize().x;
        tableGridData.widthHint = frameShellWidth;
        table.setLayoutData(tableGridData);
        
        for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
            table.getColumn(loopIndex).pack();
       }
      table.setRedraw(true);
      getoptions.setClientName(combo_workspaces.getText());
        //String selectedWorkspace = combo_workspaces.getText();
        //if(eachClientName.contains(selectedWorkspace)){
      final int[] nextId = new int[1];
        combo_workspaces.addSelectionListener(new SelectionAdapter() {
        	@Override
            public void widgetSelected(SelectionEvent e) {
        		final String selectedWorkspace = combo_workspaces.getText();						
		            	//clear the table
		        table.removeAll();
		        table.setRedraw(true);						            	            	
            	Runnable longJob = new Runnable() {
            	boolean done = false;       
            	int id;
				@Override
				public void run() {
					Thread thread = new Thread(new Runnable() {
						@Override
						public void run() {         
								id = nextId[0]++;

								
//								display.syncExec(new Runnable() {
//									@Override
//									public void run() {
							        	for (String changelistState : changelistStateArray){
							        		
//							                getoptions.setClientName(combo_workspaces.getText());
							        		getoptions.setClientName(selectedWorkspace);
							                
							                if (changelistState.equalsIgnoreCase("Pending")){
							                	getoptions.setType(IChangelist.Type.PENDING);
							                } else if (changelistState.equalsIgnoreCase("Shelved")){
							                	getoptions.setType(IChangelist.Type.SHELVED);
							                } else if(changelistState.equalsIgnoreCase("Submitted")){
							                	getoptions.setType(IChangelist.Type.SUBMITTED);
							                }
							                

							                List<IChangelistSummary> changeLists = null;
											try {					
												changeLists = p4d.getChangelists(null, getoptions);
											} catch (P4JavaException e1) {
												// TODO Auto-generated catch block
												e1.printStackTrace();
											}

							                //System.out.println(eachChangeSummary.getName() +" : "+eachChangeSummary.getDescription() );
							                    for(IChangelistSummary eachChangeList : changeLists){
							                    	
							                    	StringBuilder depotfiles = new StringBuilder();
							                    	changeListsArray.add(eachChangeList.getId());
							                    	//changeListDescriptionsArray.add(eachChangeList.getDescription());
							                    	stateArray.add(changelistState);
							                    	//DEBUG:: System.out.println(eachChangeList.getId()+" - " + eachChangeList.getDescription());
							                    		
							                        IChangelist cinfo = null;
													try {
														if (display.isDisposed() || !p4d.isConnected()) return;
														cinfo = p4d.getChangelist(eachChangeList.getId());
													} catch (ConnectionException e3) {
														// TODO Auto-generated catch block
														e3.printStackTrace();
													} catch (RequestException e3) {
														// TODO Auto-generated catch block
														e3.printStackTrace();
													} catch (AccessException e3) {
														// TODO Auto-generated catch block
														e3.printStackTrace();
													}
							                        List<IFileSpec> filesList = null;
													try {
														if (display.isDisposed() || !p4d.isConnected()) return;
														filesList = cinfo.getFiles(true);
													} catch (ConnectionException e2) {
														// TODO Auto-generated catch block
														e2.printStackTrace();
													} catch (RequestException e2) {
														// TODO Auto-generated catch block
														e2.printStackTrace();
													} catch (AccessException e2) {
														// TODO Auto-generated catch block
														e2.printStackTrace();
													}
							                        try {
							                        	if (display.isDisposed() || !p4d.isConnected()) return;
														filesList = p4d.getChangelistFiles(eachChangeList.getId());
													} catch (ConnectionException e1) {
														// TODO Auto-generated catch block
														e1.printStackTrace();
													} catch (RequestException e1) {
														// TODO Auto-generated catch block
														e1.printStackTrace();
													} catch (AccessException e1) {
														// TODO Auto-generated catch block
														e1.printStackTrace();
													}
							                        for(IFileSpec eachFileSpec : filesList){
							                            //DEBUG:: System.out.println(eachFileSpec.getDepotPathString());
							                            String lineFeed = System.getProperty("line.separator");
							                            if (eachFileSpec.getDepotPathString() != null){
							                            	depotfiles = depotfiles.append(eachFileSpec.getDepotPathString() + ", ");
							                            } else{
							                            	depotfiles = depotfiles.append(eachFileSpec.getLocalPathString() + ", ");
							                            }
							                        }    
							                        fileListArray.add(depotfiles);
							                    }
							        		}
//									}
//								});
							        	if (display.isDisposed() || table.isDisposed()) return;
										display.syncExec(new Runnable() {
											@Override
											public void run() {
								            //This is to populate data in the table
								            for (int loopIndex = 0; loopIndex < changeListsArray.size(); loopIndex++) {
								            	if(fileListArray.get(loopIndex).toString().length() > 0){
								            	  TableItem item = new TableItem(table, SWT.NULL);
								            	  item.setText(1, stateArray.get(loopIndex));
								            	  item.setText(2, changeListsArray.get(loopIndex).toString());
								            	  item.setText(3, fileListArray.get(loopIndex).toString());
								            	  //item.setText(4, changeListDescriptionsArray.get(loopIndex));
								            	  //if (loopIndex % 2 == 0) item.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
								                }else{
								            	  //do not show changelist which does not have file in it.
								              }
								            }
								            
								            for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
								            	table.getColumn(loopIndex).pack();
								            }
							            
							            table.setRedraw(true);
											}
										});
										
								        final boolean processCompleted = true;
							            //clears the table
							            //cleanList(changeListsArray, fileListArray, stateArray, changeListDescriptionsArray, table);
								        cleanList(changeListsArray, fileListArray, stateArray, table);
							            
							            
							            if (display.isDisposed() || !p4d.isConnected()) return;
										display.syncExec(new Runnable() {
											@Override
											public void run() {
												if (processCompleted){
												//text.append("\nCompleted long running task "+id);
												System.out.println("Completed long running task");
												}else{
													return;
												}
											}
										});
										done = true;
										display.wake();
							            
										display.syncExec(new Runnable() {
											@Override
											public void run() {
								        //This is to sort the columns in the table
							            Listener sortListener = new Listener() {
							                int prevSortIndex = -1;
							                int prevSortDirection = 1;
						                    int prevSortDir;
						                    
							                public void handleEvent(Event e) {
							                    TableItem[] items = table.getItems();
							                    Collator collator = Collator.getInstance(Locale.getDefault());
							                    TableColumn column = (TableColumn) e.widget;
							                    int index = column == table.getColumn(0) ? 0 : 1;
							                    if (prevSortIndex == index) {
							                        prevSortDir *= -1;
							                    } else {
							                        prevSortDir = 1;
							                        prevSortIndex = index;
							                    }
							                    for (int i = 1; i < items.length; i++) {
							                        String value1 = items[i].getText(index);
							                        for (int j = 0; j < i; j++) {
							                            String value2 = items[j].getText(index);
							                            if ((collator.compare(value1, value2) * prevSortDir) < 0) {
							                                String[] values = { items[i].getText(0),
							                                        items[i].getText(1), items[i].getText(2),
							                                        items[i].getText(3) };
							                                items[i].dispose();
							                                TableItem item = new TableItem(table, SWT.NONE, j);
							                                item.setText(values);
							                                items = table.getItems();
							                                break;
							                            }
							                        }
							                    }
							                    table.setSortColumn(column);
							                }
							            };
							            
							            
							            table.getColumn(1).addListener(SWT.Selection, sortListener);
							            table.getColumn(2).addListener(SWT.Selection, sortListener);
							            table.setSortColumn(table.getColumn(1));
							            table.setSortDirection(SWT.TOP);							            
							            table.setRedraw(true);	
										}
									});
//										}
//									});	//sync.exec				        					        					            
								} //second public void run									
							}); //new Thread
							thread.start();
							while (!done && !shell.isDisposed()) {
								if (!display.readAndDispatch())
									display.sleep();
							}
					}
            	}; //first public void run
					BusyIndicator.showWhile(display, longJob);
            } //widgetSelected  
          }); //SelectionAdapter
        
					
					
        
        //Get the checked changelists from the table
        table.addListener(SWT.Selection, new Listener()
        {
            @Override
            public void handleEvent(Event event)
            {
                if(event.detail == SWT.CHECK)
                {
                    TableItem current = (TableItem)event.item;
                    String lineFeed = System.getProperty("line.separator");
                    //String fileFromChangelist = current.getText(3).replace(lineFeed, "") + " #### " + "-c " + current.getText(2) + " -" + current.getText(1).toLowerCase();
                    String fileFromChangelist = "-c " + current.getText(2) + " -" + current.getText(1).toLowerCase();
                    if(current.getChecked())
                    {                    	
                    	changelistNum = changelistNum + fileFromChangelist;
                        //DEBUG:: System.out.println(current.getText(2));
                    } else{
                    	String removeIt = fileFromChangelist; //remove the changelist from the list if it is unchecked
                    	changelistNum = changelistNum.replace(removeIt, "");
                    }
                }
            }
        });
        

        Composite buttonComp = new Composite(shell, SWT.NONE);
        buttonComp.setLayout(new RowLayout());
        
        Button ok = new Button(buttonComp, SWT.PUSH);
        ok.setText("Add files from the selected changelist(s)");
        ok.addSelectionListener(new SelectionAdapter() {
          public void widgetSelected(SelectionEvent event) {
            if (!changelistNum.isEmpty()){
                    
            	populatechangelist(changelistNum);
	            shell.close();	
	            //disconnect from the Perforce server
	            disconnectFromServer(p4d);
	            changelistNum = "";
            }else{
            	shell.close();
            	if (display.isDisposed() || !p4d.isConnected()) return;
                //disconnect from the Perforce server
            	disconnectFromServer(p4d);
            }
          }
        });

        Button cancel = new Button(buttonComp, SWT.PUSH);
        cancel.setText("Cancel");
        cancel.addSelectionListener(new SelectionAdapter() {
          public void widgetSelected(SelectionEvent event) {
            shell.close();
          }
        });
        shell.setDefaultButton(ok);
        
    }
    
    public void disconnectFromServer(IOptionsServer p4d){
        //disconnect from the Perforce server
        try {
        	if (display.isDisposed() || !p4d.isConnected()) return;
			p4d.disconnect();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    
    
    public void populatechangelist(String changeLists){
    	String lineFeed = System.getProperty("line.separator");
        if (Gui.txt.getText().isEmpty()){
            Gui.txt.setText(Gui.txt.getText() + changeLists);
        } else{
            Gui.txt.setText(Gui.txt.getText() + lineFeed +  changeLists + lineFeed + lineFeed);
        }
    }
    

    //public static void cleanList(List<Integer> changeListsArray, List<StringBuilder> fileListArray, List<String> stateArray, List<String> changeListDescriptionsArray, Table table){
    public static void cleanList(List<Integer> changeListsArray, List<StringBuilder> fileListArray, List<String> stateArray, Table table){
    	changeListsArray.removeAll(changeListsArray);
    	fileListArray.removeAll(fileListArray);
    	stateArray.removeAll(stateArray);
    	//changeListDescriptionsArray.removeAll(changeListDescriptionsArray);
        //table.setRedraw(true);
    }
    
}

Open in new window

0
Comment
Question by:Tolgar
  • 4
  • 3
7 Comments
 
LVL 35

Expert Comment

by:mccarl
ID: 39668120
You could try adding lines like the below just after the BusyIndicator.showWhile()method call (line 385). But I'm not sure whether doing this can override what BusyIndicator is doing. Try it and see...
XXXXX.setCursor(display.getSystemCursor(SWT.CURSOR_ARROW));

Open in new window

Where XXXX is the GUI component that you want to have a normal cursor for.
0
 

Author Comment

by:Tolgar
ID: 39668123
I tried but it didn't work.
0
 

Author Comment

by:Tolgar
ID: 39668134
ok. Instead of this, can you please tell me how I can place checkbox button next to the combo in this dialog box (shell)?

Then, I will not need to play with these cursors. I will limit the search by selecting or unselecting this checkbox.

@mccarl: this is the same code you sent me where you used rowlayout to position the combo, table and the two other buttons.

Thanks,
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:Tolgar
ID: 39668138
Actually, I put the checkbox and the label using the following code but I cannot change the spacing between the combo and the new label:

 I put these lines after line 112:

        Label label_includeSubmitted = new Label(workspaceComp, SWT.NONE);
        label_includeSubmitted.setText("Include submitted changelists: ");
        
        Button selection = new Button(workspaceComp, SWT.CHECK);

Open in new window



Can you please tell me how I can put a horizontal spacing?

Thanks,
0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39668149
Ok, change this line of code (I got it from the previous question)...
workspaceComp.setLayout(new RowLayout());

Open in new window

... with this block of code ...
RowLayout workspaceCompLayout = new RowLayout();
workspaceCompLayout.setSpacing(20);     // or whatever value looks good to you
workspaceComp.setLayout(workspaceCompLayout);

Open in new window

Although, this would also put a space between the Label and the Checkbox that you are adding. If you don't like/want this, can you just use the inbuilt "text" of the checkbox, ie. replace code snippet in your previous post with...
Button selection = new Button(workspaceComp, SWT.CHECK);
selection.setText("Include submitted changelists");

Open in new window

It has the added benefit (I am pretty sure) that you can click the actual text to toggle the check box aswell, where as in your code, you have to aim just on the little box to toggle it. Personally, I don't like it when apps make me aim that small, I'm lazy and I just want to click somewhere in the vicinity! ;)
0
 

Author Comment

by:Tolgar
ID: 39668165
ok, I did it. Now the problem is how to detect if the checkbox is selected.

for the check box I have this code:

        final Button includeSubmitted = new Button(comboComp, SWT.CHECK);
        includeSubmitted.setText("Include submitted changelists");

Open in new window


Then this is how I detect the checkbox state: (This code is right after LINE 168)

      boolean includeSubmittedSelected = false;
      includeSubmitted.addListener(SWT.Selection, new Listener() {
          public void handleEvent(Event event) {
        	 if(includeSubmitted.getSelection()){
        		 includeSubmittedSelected = true;  
        	 }
          }
          });

Open in new window


And this is the line I changed: (LINE 202)

} else if(changelistState.equalsIgnoreCase("Submitted") && includeSubmittedSelected){

Open in new window



Now the problem is, LINE 202  (in the initial post) says "change modifier to final". Also LINE 5 in this post says the same thing.

If I do that then the code that listens the checkbox above cannot change the "includeSubmittedSelected" variable.


How can I solve this problem?
0
 
LVL 35

Assisted Solution

by:mccarl
mccarl earned 500 total points
ID: 39668195
Then this is how I detect the checkbox state
That's the wrong way to do it. Remove those 8 lines in that snippet and add the second line of the below in the correct location...
      final String selectedWorkspace = combo_workspaces.getText();
      final boolean includeSubmittedSelected = includeSubmitted.getSelection();

Open in new window

This would be around line 175 of the original code, but I'm guessing that line numbers have changed quite a bit since then. Just find line 1 from the above in your code and add in line 2 just under it.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now