I'm doing a program which needed a thread because It's not responding when the GUI start its work. I'd used thread but i don't know if the use of it is correct, also I'd used the display.asyncExeceach of this gives me error
here is the code
btnCopyFolder.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0) {
display.asyncExec(
new Runnable()
{
public void run(){
File srcFolder = new File(txtSource.getText());
File destFolder = new File(txtDestination.getText());
if(!srcFolder.exists()){
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Directory does not exist.");
msgBox.open();
txtSource.setText("");
txtSource.setEnabled(false);
txtDestination.setText("");
}else{
if(txtDestination.getText().isEmpty())
{
MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
msgBox.setText("WARNING");
msgBox.setMessage("Invalid Path...");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
btnCopyFolder.setEnabled(true);
btnCopyFile.setEnabled(true);
}
else
{
try {
tc.copyFolder(srcFolder,destFolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtDetails.append("Finished Copying.....\n");
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Done Copying...");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
btnCopyFolder.setEnabled(true);
btnCopyFile.setEnabled(true);
tc1 = new threadclass();
tc = new threadclass();
tc1.start();
tc.start();
}
}
}
});
}
});
Error
java.lang.NullPointerException
at org.eclipse.wb.swt.FortryApplication$5.widgetSelected(FortryApplication.java:303)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at org.eclipse.wb.swt.FortryApplication.open(FortryApplication.java:63)
at org.eclipse.wb.swt.FortryApplication.main(FortryApplication.java:486)
for Thread i tried these
btnCopyFile.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0)
{
new Thread(){
public void run()
{
File srcFolder = new File(txtSource.getText());
File destFolder = new File(txtDestination.getText());
if(!srcFolder.exists()){
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Directory does not exist.");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
}else{
if(txtDestination.getText().isEmpty())
{
MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
msgBox.setText("Warning");
msgBox.setMessage("Invalid Path..");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
btnCopyFolder.setEnabled(true);
btnCopyFile.setEnabled(true);
}
else
{
try {
tc.copyFolder1(srcFolder,destFolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtDetails.append("Finished Copying.....\n");
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Done Copying...");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
btnCopyFolder.setEnabled(true);
btnCopyFile.setEnabled(true);
// tc1 = new threadclass();
// tc = new threadclass();
// tc1.start();
// tc.start();
}
}
}
}.start();
}
});
Error shows:
Exception in thread "Thread-2" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.SWT.error(Unknown Source)
at org.eclipse.swt.widgets.Widget.error(Unknown Source)
at org.eclipse.swt.widgets.Widget.checkWidget(Unknown Source)
at org.eclipse.swt.widgets.Text.getText(Unknown Source)
at org.eclipse.wb.swt.FortryApplication$4$1.run(FortryApplication.java:239)
EDIT
Full Code:
ublic class FortryApplication implements Runnable {
static Display display;
static Shell shell;
static Color color;
private static Text txtSource;
private static Text txtDestination;
private static Text txtDetails;
static DateTime dateFrom;
static DateTime dateTo;
Button btnSourceFile, btnSelectFolder;
Button btnBrowseFile;
Button btnCopyFolder;
Button btnCopyFile;
Button btnCancel;
static String text = "" ;
static String text2 = "" ;
threadclass tc = new threadclass();
threadclass tc1 = new threadclass();
// pos x, pos y, width, height
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected void createContents()
{
shell = new Shell();
shell.setSize(600,530);
shell.setText("SWT Shell Demonstration");
shell.setLayout(new GridLayout());
final Group grpInput = new Group(shell, SWT.NONE);
grpInput.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
grpInput.setText("Input File");
GridLayout gl_grpInput = new GridLayout();
gl_grpInput.numColumns = 3;
grpInput.setLayout(gl_grpInput);
GridData gd_grpInput = new GridData(GridData.FILL_HORIZONTAL);
gd_grpInput.widthHint = 419;
gd_grpInput.verticalAlignment = SWT.CENTER;
gd_grpInput.heightHint = 57;
grpInput.setLayoutData(gd_grpInput);
btnSourceFile = new Button(grpInput, SWT.PUSH);
btnSourceFile.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0) {
FileDialog fd = new FileDialog(shell, SWT.MULTI);
// Collection files = new ArrayList();
String firstFile = fd.open();
if (firstFile != null) {
txtSource.setText("");
String[] selectedFiles = fd.getFileNames();
File file = new File(firstFile);
for (int ii = 0; ii < selectedFiles.length; ii++ )
{
if (file.isFile())
{
tc.displayFiles(new String[] { file.toString()});
}
else
tc.displayFiles(file.list());
}
}
btnCopyFolder.setEnabled(false);
btnCopyFile.setEnabled(true);
btnCancel.setEnabled(true);
}
});
btnSourceFile.setText("Select File");
btnSelectFolder = new Button(grpInput, SWT.NONE);
btnSelectFolder.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0) {
DirectoryDialog dlg = new DirectoryDialog(shell);
dlg.setFilterPath(txtSource.getText());
dlg.setMessage("Select a source file to transfer");
String dir = dlg.open();
if (dir != null) {
txtSource.setText(dir);
btnCopyFile.setEnabled(false);
btnCopyFolder.setEnabled(true);
btnCancel.setEnabled(true);
// txtDetails.setText("Progress " + "\n");
}
}
});
btnSelectFolder.setText("Select Folder");
new Label(grpInput, SWT.NONE);
txtSource = new Text(grpInput, SWT.BORDER);
txtSource.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
new Label(grpInput, SWT.NONE);
Group grpDestnationFile = new Group(shell, SWT.NONE);
grpDestnationFile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
grpDestnationFile.setText("Destnation File");
grpDestnationFile.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
GridLayout gl_grpDestnationFile = new GridLayout();
gl_grpDestnationFile.numColumns = 2;
grpDestnationFile.setLayout(gl_grpDestnationFile);
btnBrowseFile = new Button(grpDestnationFile, SWT.NONE);
btnBrowseFile.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0) {
DirectoryDialog dialog = new DirectoryDialog(shell, SWT.SAVE);
dialog.setFilterPath(txtDestination.getText());
String dir = dialog.open();
if(dir != null){
txtDestination.setText(dir);
}
}
});
btnBrowseFile.setText("Browse File");
new Label(grpDestnationFile, SWT.NONE);
txtDestination = new Text(grpDestnationFile, SWT.BORDER);
GridData gd_txtDestination = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
gd_txtDestination.widthHint = 429;
txtDestination.setLayoutData(gd_txtDestination);
new Label(grpDestnationFile, SWT.NONE);
Label label = new Label(grpDestnationFile, SWT.NONE);
GridData gd_label = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
gd_label.heightHint = -5;
label.setLayoutData(gd_label);
Group grpDateRange = new Group(shell, SWT.NONE);
grpDateRange.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
GridData gd_grpDateRange = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
gd_grpDateRange.heightHint = 63;
gd_grpDateRange.widthHint = 78;
grpDateRange.setLayoutData(gd_grpDateRange);
grpDateRange.setText("Date Range");
DateTime dateFrom = new DateTime(grpDateRange, SWT.BORDER);
dateFrom.setBounds(111, 40, 122, 24);
Label lblFrom = new Label(grpDateRange, SWT.NONE);
lblFrom.setBounds(153, 19, 55, 15);
lblFrom.setText("From");
DateTime dateTo = new DateTime(grpDateRange, SWT.BORDER);
dateTo.setBounds(352, 40, 122, 24);
Label lblTo = new Label(grpDateRange, SWT.NONE);
lblTo.setText("To");
lblTo.setBounds(397, 19, 55, 15);
Label label_1 = new Label(grpDateRange, SWT.NONE);
label_1.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
label_1.setBounds(293, 40, 20, 24);
label_1.setText(":");
Group grpDetails = new Group(shell, SWT.NONE);
grpDetails.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
grpDetails.setText("Details");
grpDetails.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
GridLayout gl_grpDetails = new GridLayout();
gl_grpDetails.numColumns = 2;
grpDetails.setLayout(gl_grpDetails);
txtDetails = new Text(grpDetails, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
GridData gd_txtDetails = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
gd_txtDetails.widthHint = 460;
gd_txtDetails.heightHint = 66;
txtDetails.setLayoutData(gd_txtDetails);
new Label(grpDetails, SWT.NONE);
Label label_2 = new Label(grpDetails, SWT.NONE);
GridData gd_label_2 = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
gd_label_2.heightHint = -3;
label_2.setLayoutData(gd_label_2);
Group grpCopyOptions = new Group(shell, SWT.NONE);
grpCopyOptions.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
GridData gd_grpCopyOptions = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
gd_grpCopyOptions.heightHint = 70;
gd_grpCopyOptions.widthHint = 492;
grpCopyOptions.setLayoutData(gd_grpCopyOptions);
grpCopyOptions.setText("Copy Options");
btnCopyFile = new Button(grpCopyOptions, SWT.NONE);
btnCopyFile.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0)
{
Display.getDefault().asyncExec(
new Runnable()
{
public void run()
{
File srcFolder = new File(txtSource.getText());
File destFolder = new File(txtDestination.getText());
if(!srcFolder.exists()){
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Directory does not exist.");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
}else{
if(txtDestination.getText().isEmpty())
{
MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
msgBox.setText("Warning");
msgBox.setMessage("Invalid Path..");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
btnCopyFolder.setEnabled(true);
btnCopyFile.setEnabled(true);
}
else
{
try {
tc.copyFolder1(srcFolder,destFolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtDetails.append("Finished Copying.....\n");
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Done Copying...");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
btnCopyFolder.setEnabled(true);
btnCopyFile.setEnabled(true);
tc1 = new threadclass();
tc = new threadclass();
tc1.start();
tc.start();
}
}
}
});
}
});
btnCopyFile.setBounds(128, 23, 166, 25);
btnCopyFile.setText("Copy File");
btnCopyFolder = new Button(grpCopyOptions, SWT.NONE);
btnCopyFolder.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0) {
Display.getDefault().asyncExec(
new Runnable()
{
public void run(){
File srcFolder = new File(txtSource.getText());
File destFolder = new File(txtDestination.getText());
if(!srcFolder.exists()){
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Directory does not exist.");
msgBox.open();
txtSource.setText("");
txtSource.setEnabled(false);
txtDestination.setText("");
}else{
if(txtDestination.getText().isEmpty())
{
MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
msgBox.setText("WARNING");
msgBox.setMessage("Invalid Path...");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
btnCopyFolder.setEnabled(true);
btnCopyFile.setEnabled(true);
}
else
{
try {
tc.copyFolder(srcFolder,destFolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
txtDetails.append("Finished Copying.....\n");
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Done Copying...");
msgBox.open();
txtSource.setText("");
txtSource.setEditable(false);
txtDestination.setText("");
btnCopyFolder.setEnabled(true);
btnCopyFile.setEnabled(true);
tc1 = new threadclass();
tc = new threadclass();
tc1.start();
tc.start();
}
}
}
});
}
});
btnCopyFolder.setText("Copy Folder");
btnCopyFolder.setBounds(300, 23, 166, 25);
btnCancel = new Button(grpCopyOptions, SWT.NONE);
btnCancel.setBounds(247, 54, 96, 25);
btnCancel.setText("Cancel");
}
class threadclass extends Thread
{
public void cancel(boolean b) {
tc.interrupt();
}
public void displayFiles(String[] files) {
for (int i = 0; files != null && i < files.length; i++) {
txtSource.append(files[i]);
txtSource.setEditable(false);
}
}
public void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
if (!dest.exists())
{
dest.mkdir();
txtDetails.append("Directory created : " + dest + "\n");
}
final String files[] = src.list();
for (String file : files)
{
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//Recursive function call
copyFolder(srcFile, destFile);
}
}
else{
// btnCancel.setEnabled(true);
txtDetails.append("");
Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
txtDetails.append(text + "Copying " + src.getAbsolutePath() + "\n");
//
}
}
public void copyFolder1(File src, File dest)
throws IOException{
// String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new DateTime(ddFrom, 0));
if(src.isDirectory()){
if (!dest.exists())
{
dest.mkdir();
txtDetails.append("Directory created : " + dest + "\n");
}
String files[] = src.list();
for (String file : files)
{
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//Recursive function call
copyFolder1(srcFile, destFile);
}
}
else{
if(dest.isDirectory())
{
// btnCancel.setEnabled(true);
copyFile(src, new File (dest, src.getName()));
txtDetails.append(text + "Copying " + src.getAbsolutePath() + "\n");
}
else
{
copyFile(src, dest);
}
// }
}
}
public void copyFile(File src, File dest) throws IOException
{
InputStream oInStream = new FileInputStream(src);
OutputStream oOutStream = new FileOutputStream(dest);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
while ((nLength = oBuffInputStream.read(oBytes)) > 0)
{
oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();
}
public void fileCopy(File sourceDir , File destDir) throws IOException{
// File sDir = new File(sourceDir);
if (!sourceDir.isDirectory()){
// throw error
}
// File dDir = new File(destDir);
if (!destDir.exists()){
destDir.mkdir();
}
File[] files = sourceDir.listFiles();
for (int i = 0; i < files.length; i++) {
File destFile = new File(destDir.getAbsolutePath()+File.separator+files[i].getName().replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "")
.replace(" ", ""));
// destFile.createNewFile();
Files.copy(files[i].toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
txtDetails.append(text + " Copying " + files[i].getAbsolutePath() + "\n");
}
}
}
public static void main(String[] args) {
try {
FortryApplication window = new FortryApplication();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
You do not use asyncExec to run a background task, asyncExec always runs code in the UI thread.
You use asyncExec inside a background Thread every time you want to do a UI operation. You must use a background Thread to do long running tasks.
So when you want to run a long running task you do something like:
Thread background = new Thread() {
#Override
public void run() {
... long running background code
Display.getDefault().asyncExec(new Runnable() {
#Override
public void run() {
.. code accessing user interface objects
}
});
.... more code
}
};
background.start();
Related
I want to disable button btnCopyFolder when i clicked the btnSearchFile
here is my code:
package org.eclipse.wb.swt;
import java.nio.file.Path;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.MessageBox;
public class MainUI {
private Text txtSource;
private static Text txtDestination;
protected Shell shell;
private static Text text1;
static DateTime ddFrom;
static Button btnCopyFolder;
static String text = "" ;
static String text2 = "" ;
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(450, 400);
shell.setText("Connection Manager");
final DateTime ddFrom = new DateTime (shell, SWT.DROP_DOWN | SWT.BORDER);
final DateTime ddTo = new DateTime (shell, SWT.DROP_DOWN | SWT.BORDER);
text = String.format("%02d/%02d/%04d",ddFrom.getDay(),ddFrom.getMonth() + 1,ddFrom.getYear());
text2 = String.format("%04d%02d%02d",ddTo.getYear(), ddTo.getMonth() + 1, ddTo.getDay());
// final DateTime time = new DateTime (shell,SWT.TIME | SWT.SHORT);
Label lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
lblNewLabel.setBounds(10, 0, 107, 25);
lblNewLabel.setText("Source File ");
Button btnSearchFile = new Button(shell, SWT.NONE);
btnSearchFile.setBounds(103, 30, 107, 25);
btnSearchFile.setText("Search File");
btnSearchFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog fd = new FileDialog(shell, SWT.MULTI);
String firstFile = fd.open();
btnCopyFolder.setVisible(false);
if (firstFile != null) {
String[] selectedFiles = fd.getFileNames();
File file = new File(firstFile);
for (int ii = 0; ii < selectedFiles.length; ii++ )
{
if (file.isFile())
{
displayFiles(new String[] { file.toString()});
}
else
displayFiles(file.list());
}
}
}
});
txtSource = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL );
txtSource.setBounds(10, 61, 414, 34);
Label lblNewLabel_1 = new Label(shell, SWT.NONE);
lblNewLabel_1.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL));
lblNewLabel_1.setBounds(10, 96, 107, 18);
lblNewLabel_1.setText("Destination File");
final Button btnSearchDirectory = new Button(shell, SWT.NONE);
btnSearchDirectory.setText("Search Directory");
btnSearchDirectory.setBounds(216, 31, 107, 25);
btnSearchDirectory.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DirectoryDialog dlg = new DirectoryDialog(shell);
dlg.setFilterPath(txtSource.getText());
dlg.setMessage("Select a source file to transfer");
String dir = dlg.open();
if (dir != null) {
txtSource.setText(dir);
}
}
});
Button btnSearchDestination = new Button(shell, SWT.NONE);
btnSearchDestination.setBounds(10, 120, 75, 25);
btnSearchDestination.setText("Search");
btnSearchDestination.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DirectoryDialog dialog = new DirectoryDialog(shell, SWT.SAVE);
dialog.setFilterPath(txtDestination.getText());
String dir = dialog.open();
if(dir != null){
txtDestination.setText(dir);
}
}
});
txtDestination = new Text(shell, SWT.BORDER);
txtDestination.setBounds(10, 151, 414, 25);
txtDestination.setText("");
Label lblNewLabel_2 = new Label(shell, SWT.NONE);
lblNewLabel_2.setBounds(10, 182, 81, 15);
lblNewLabel_2.setText("Date Range:");
Button btnCopyFile = new Button(shell, SWT.NONE);
btnCopyFile.setBounds(86, 253, 75, 25);
btnCopyFile.setText("Copy File");
btnCopyFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
File srcFolder = new File(txtSource.getText());
File destFolder = new File(txtDestination.getText());
if(!srcFolder.exists()){
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Directory does not exist.");
msgBox.open();
txtSource.setText("");
txtDestination.setText("");
}else{
if(txtDestination.getText().isEmpty())
{
MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
msgBox.setText("Warning");
msgBox.setMessage("Invalid Path..");
msgBox.open();
txtSource.setText("");
txtDestination.setText("");
}
else
{
try {
copyFolder1(srcFolder,destFolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
text1.append("Finished Copying.....\n");
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Done Copying...");
msgBox.open();
}
text1.append("");
}
}
});
Button btnCancel = new Button(shell, SWT.NONE);
btnCancel.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0)
{
text = String.format("%02d/%02d/%04d",ddFrom.getDay(),ddFrom.getMonth() + 1,ddFrom.getYear());
text2 = String.format("%04d%02d%02d",ddTo.getYear(), ddTo.getMonth() + 1, ddTo.getDay());
String txt = ("Date Range is: " + " From "+ text + " : " + " To " + text2 + "\n");
text1.append(txt);
txtSource.setText("");
txtDestination.setText("");
}
});
btnCancel.setBounds(167, 253, 75, 25);
btnCancel.setText("Cancel");
Label label = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
label.setBounds(0, 288, 434, 13);
Label lblFrom = new Label(shell, SWT.NONE);
lblFrom.setBounds(50, 203, 55, 15);
lblFrom.setText("From");
//DateTime ddFrom = new DateTime(shell, SWT.DROP_DOWN);
ddFrom.setBounds(50, 224, 119, 23);
Label label_1 = new Label(shell, SWT.NONE);
label_1.setFont(SWTResourceManager.getFont("Segoe UI", 13, SWT.NORMAL));
label_1.setBounds(199, 222, 22, 25);
label_1.setText(":");
//DateTime ddTo = new DateTime(shell, SWT.NONE);
ddTo.setBounds(233, 224, 119, 23);
Label lblTo = new Label(shell, SWT.NONE);
lblTo.setText("To");
lblTo.setBounds(233, 203, 55, 15);
text1 = new Text(shell, SWT.BORDER | SWT.READ_ONLY | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI);
text1.setText("Progress\n");
text1.setEnabled(true);
text1.setBounds(0, 302, 434, 59);
Button btnCopyFolder = new Button(shell, SWT.NONE);
btnCopyFolder.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent arg0) {
File srcFolder = new File(txtSource.getText());
File destFolder = new File(txtDestination.getText());
if(!srcFolder.exists()){
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Directory does not exist.");
msgBox.open();
txtSource.setText("");
txtDestination.setText("");
}else{
if(txtDestination.getText().isEmpty())
{
MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
msgBox.setText("WARNING");
msgBox.setMessage("Invalid Path...");
msgBox.open();
txtSource.setText("");
txtDestination.setText("");
}
else
{
try {
copyFolder(srcFolder,destFolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
text1.append("Finished Copying.....\n");
MessageBox msgBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
msgBox.setText("Information");
msgBox.setMessage("Done Copying...");
msgBox.open();
}
}
}
});
btnCopyFolder.setText("Copy Folder");
btnCopyFolder.setBounds(248, 253, 75, 25);
}
public void displayFiles(String[] files) {
for (int i = 0; files != null && i < files.length; i++) {
txtSource.setText(files[i]);
txtSource.setEditable(true);
}
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
if (!dest.exists())
{
dest.mkdir();
text1.append("Directory created : " + dest + "\n");
}
final String files[] = src.list();
for (String file : files)
{
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//Recursive function call
copyFolder(srcFile, destFile);
}
}
else{
text1.append("");
Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
text1.append(text + " Copying " + src.getAbsolutePath() + "\n");
//
}
}
public static void copyFolder1(File src, File dest)
throws IOException{
// String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new DateTime(ddFrom, 0));
if(src.isDirectory()){
if (!dest.exists())
{
dest.mkdir();
text1.append("Directory created : " + dest + "\n");
}
String files[] = src.list();
for (String file : files)
{
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//Recursive function call
copyFolder1(srcFile, destFile);
}
}
else{
if(dest.isDirectory())
{
copyFile(src, new File (dest, src.getName()));
text1.append(text + " Copying " + src.getAbsolutePath() + "\n");
}
else
{
copyFile(src, dest);
}
// }
}
}
public static void copyFile(File src, File dest) throws IOException
{
InputStream oInStream = new FileInputStream(src);
OutputStream oOutStream = new FileOutputStream(dest);
// Transfer bytes from in to out
byte[] oBytes = new byte[1024];
int nLength;
BufferedInputStream oBuffInputStream = new BufferedInputStream( oInStream );
while ((nLength = oBuffInputStream.read(oBytes)) > 0)
{
oOutStream.write(oBytes, 0, nLength);
}
oInStream.close();
oOutStream.close();
}
/**
* Launch the application.
* #param args
*/
public static void main(String[] args) {
try {
MainUI window = new MainUI();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and this is the error
java.lang.NullPointerException
at org.eclipse.wb.swt.MainUI$1.widgetSelected(MainUI.java:87)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at org.eclipse.wb.swt.MainUI.open(MainUI.java:56)
at org.eclipse.wb.swt.MainUI.main(MainUI.java:370)
this is the line where the error came from
btnCopyFolder.setVisible(false); //line 100
You are shadowing the field btnCopyFolder with this code
Button btnCopyFolder = new Button(shell, SWT.NONE);
change to
btnCopyFolder = new Button(shell, SWT.NONE);
I am new in GEF & RCP. Now I want to Save my ViewPart on exit for that i have implemented savestate and init method. But I am using a tableItem to fill data in My viewpart. When I try to get text from my table and store them in my savestate nothing is happening. How can I save my data stored in TableItem from savestate and initialize when i start up my graphical editor
public class Theartview extends ViewPart implements Serializable {
private static final long serialVersionUID = -3033215443267698138L;
public static String ID = "TutoGEF.theartview_id";
public Text text;
public Text text_1;
private Table table;
private IMemento memento;
#SuppressWarnings("unused")
private Node node;
private static Node sourceNode;
private static Node targetNode;
private static int connectionType;
TableItem[] items = null;
#Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
this.memento = memento;
super.init(site, memento);
System.out.println("hi there");
}
#Override
public void saveState(IMemento memento) {
super.saveState(memento);
System.out.println("hello there");
}
#SuppressWarnings("static-access")
public void getDataOfConnection(Node sourceNode, Node targetNode,
int connectionType1) {
this.sourceNode = sourceNode;
this.targetNode = targetNode;
this.connectionType = connectionType1;
}
public Theartview() {
}
#Override
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(10, false));
table = new Table(parent, SWT.BORDER | SWT.FULL_SELECTION);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 10, 1));
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tblclmnTheartName = new TableColumn(table, SWT.NONE);// 1
tblclmnTheartName.setWidth(100);
tblclmnTheartName.setText("Theart Name");
TableColumn tblclmnCategory = new TableColumn(table, SWT.NONE);// 2
tblclmnCategory.setWidth(100);
tblclmnCategory.setText("Category");
TableColumn tblclmnCombo = new TableColumn(table, SWT.NONE);// 3
tblclmnCombo.setWidth(100);
tblclmnCombo.setText("Satus");
TableColumn tblclmnCombo_1 = new TableColumn(table, SWT.NONE);// 4
tblclmnCombo_1.setWidth(100);
tblclmnCombo_1.setText("Priority");
TableColumn tblclmnDescription = new TableColumn(table, SWT.NONE);// 5
tblclmnDescription.setWidth(162);
tblclmnDescription.setText("Description");
TableColumn tblclmnJustification = new TableColumn(table, SWT.NONE);// 6
tblclmnJustification.setWidth(212);
tblclmnJustification.setText("Justification");
// getfillTableRoWData();
if (memento != null) {
restoreState(memento);
}
memento = null;
}
void restoreState(IMemento memento) {
}
public void fillTableRoWData() {
try {
if (Connection.Number_Of_Connection != 0) {
TableItem item = new TableItem(table, SWT.NONE);
String tempConType = null;
String sourceNodeName = null;
String targetNodeName = null;
String settingString = null;
for (int s = 1; s <= Connection.Number_Of_Connection; s++) {
if (connectionType == Connection.CONNECTION_DESIGN) {
tempConType = "Deliver Design";
} else if (connectionType == Connection.CONNECTION_RESOURCES) {
tempConType = "Deliver Resource";
} else if (connectionType == Connection.CONNECTION_WORKPACKAGES) {
tempConType = "Distributed Work Packages";
}
// for source
if (Service.class.isInstance(sourceNode)) {
sourceNodeName = "Service-";
} else if (Circle.class.isInstance(sourceNode)) {
sourceNodeName = "Circle-";
}
// for targets
if (Service.class.isInstance(targetNode)) {
targetNodeName = "Service ";
} else if (Circle.class.isInstance(targetNode)) {
targetNodeName = "Circle ";
}
if (sourceNodeName.equals(targetNodeName)) {
settingString = sourceNodeName + tempConType;
} else if (!(sourceNodeName.equals(targetNodeName))) {
settingString = sourceNodeName + targetNodeName
+ tempConType;
}
for (int j = 0; j < 6; j++) {
TableEditor editor = new TableEditor(table);
Text text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 0);
text.setText(settingString);
editor = new TableEditor(table);
text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 1);
text.setText(settingString);
editor = new TableEditor(table);
Combo Status_Combo = new Combo(table, SWT.NONE);
Status_Combo.add("Mitigated");
Status_Combo.add("Not Applicable");
Status_Combo.add("Not Started");
Status_Combo.add("Needs Investigation");
Status_Combo.setText("Not Started");
editor.grabHorizontal = true;
editor.setEditor(Status_Combo, item, 2);
editor = new TableEditor(table);
Combo priority_Combo = new Combo(table, SWT.NONE);
priority_Combo.add("High");
priority_Combo.add("Medium");
priority_Combo.add("Low");
priority_Combo.setText("High");
editor.grabHorizontal = true;
editor.setEditor(priority_Combo, item, 3);
editor = new TableEditor(table);
text = new Text(table, SWT.NONE);
editor.grabHorizontal = true;
editor.setEditor(text, item, 4);
text.setText(settingString);
editor = new TableEditor(table);
text = new Text(table, SWT.MULTI | SWT.BORDER
| SWT.WRAP | SWT.V_SCROLL);
editor.grabHorizontal = true;
editor.setEditor(text, item, 5);
// text.setText(settingString);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void setFocus() {
}
Your saveState() implementation should store the data you need in order to maintain the state.
See this short tutorial for code example.
I need the textarea of Directory and the proceeding button towards right of the group,but i couldn't get it...any help on this would be great for me....
I still get some space in right end(i.e) after the browserbutton....I need to get rid of this space,don't know where i am going wrong....
Code :
Label label = new Label(DGroup, SWT.NONE);
final GridData gd_Label = new GridData();
gd_Label.horizontalIndent = 20;
label .setLayoutData(gd_Label);
label.setText("Directory:");
label.setToolTipText("The directory to write files to");
directoryText = new StyledText(DGroup, SWT.BORDER );
directoryText.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
enableDisableControls();
}
});
GridData gd_DirectoryText = new GridData();
gd_DirectoryText.horizontalAlignment = SWT.FILL;
gd_DirectoryText.grabExcessHorizontalSpace = true;
gd_DirectoryText.horizontalSpan = 1;
directoryText.setLayoutData(gd_DirectoryText);
directoryText .setLayoutData(gd_DirectoryText );
final Button browseDirectoryButton = new Button(DGroup, SWT.NONE);
browseDirectoryButton.setToolTipText("Select the directory the connector will write files to.");
final GridData gd_browseDirectoryButton = new GridData();
browseDirectoryButton.setLayoutData(gd_browseDirectoryButton );
browseDirectoryButton.setText("...");
Entire Block:
protected void setControls(Composite parent)
{
OptionGroup = new Group(this, SWT.None);
OptionGroup.setLayout(new GridLayout(1,false));
GridData gridData=new GridData(GridData.FILL_HORIZONTAL);
gridData.heightHint=400;
OptionGroup.setLayoutData(gridData);
ScrolledComposite scrolledPane=new ScrolledComposite(OptionGroup,SWT.V_SCROLL);
scrolledPane.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite projectPane=new Composite(scrolledPane,SWT.NONE);
projectPane.setLayout(new GridLayout(2,false));
DGroup = new Group(projectPane, SWT.None);
DGroup.setLayout(new GridLayout(3,true));
GridData gData=new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
DGroup.setLayoutData(gData);
Label label = new Label(DGroup, SWT.NONE);
final GridData gd_Label = new GridData();
gd_Label.horizontalIndent = 20;
label .setLayoutData(gd_Label);
label.setText("Directory:");
label.setToolTipText("The directory to write files to");
directoryText = new StyledText(DGroup, SWT.BORDER );
directoryText.addModifyListener(modifyListener);
try
{
directoryNameProposal = new ParameterProposals(directoryText);
}
catch (Exception e1)
{
}
directoryText.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
enableDisableControls();
}
});
GridData gd_DirectoryText = new GridData();
gd_DirectoryText.horizontalAlignment = SWT.FILL;
gd_DirectoryText.grabExcessHorizontalSpace = true;
gd_DirectoryText.horizontalSpan = 1;
directoryText.setLayoutData(gd_DirectoryText);
directoryText .setLayoutData(gd_DirectoryText );
final Button browseDirectoryButton = new Button(DGroup, SWT.NONE);
browseDirectoryButton.setToolTipText("Select the directory the connector will write files to.");
final GridData gd_browseDirectoryButton = new GridData();
browseDirectoryButton.setLayoutData(gd_browseDirectoryButton );
browseDirectoryButton.setText("...");
browseDirectoryButton.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
String dir = doBrowse(browseDirectoryButton.getToolTipText(), "Select Directory");
if (dir != null)
{
directoryText.setText(dir);
}
}
});
createDirectory = new Button(projectPane, SWT.CHECK);
createDirectory.setToolTipText("Indicates whether directoty will be created if it does not exist.");
createDirectory.setText("Create Directory");
createDirectory.setSelection(false);
createDirectory.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
enableDisableControls();
}
});
label = new Label(projectPane, SWT.NULL);
label.setText("File Name:");
label.setToolTipText("The name of the file to write to");
fileNameText = new StyledText(projectPane, SWT.BORDER | SWT.SINGLE);
fileNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
fileNameText.addModifyListener(modifyListener);
try
{
fileNameProposal = new ParameterProposals(fileNameText);
}
catch (Exception e1)
{
}
new Label(this, SWT.NONE);
label = new Label(projectPane, SWT.NULL);
label.setText("Username:");
fileUsername = new StyledText(projectPane, SWT.BORDER | SWT.SINGLE);
fileUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
fileUsername.addModifyListener(modifyListener);
fileUsername.setToolTipText("The username to access the file.");
new Label(this, SWT.NONE);
label = new Label(projectPane, SWT.NULL);
label.setText("Encoding:");
encodingCombo = new CharsetCombo(projectPane, SWT.READ_ONLY);
encodingCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
encodingCombo.addModifyListener(modifyListener);
encodingCombo.setToolTipText("The character set used to encode data.");
new Label(this, SWT.NONE);
appendButton = new Button(projectPane, SWT.CHECK);
appendButton.setToolTipText("Indicates whether data is to be appended to the file. If the file exists, and Append is false, the file is overwritten. If the file exists and Append is true, the data is appended to the file. Otherwise, a new file is created.");
appendButton.setText("Append to file");
appendButton.setSelection(false);
appendButton.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
if (appendButton.getSelection() && useTempFileButton.getSelection())
{
useTempFileButton.setSelection(false);
}
enableDisableControls();
}
});
new Label(this, SWT.NONE);
new Label(this, SWT.NONE);
fileOptionGroup = new Group(projectPane, SWT.NONE);
fileOptionGroup.setText("If the file exists");
fileOptionGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
fileOptionGroup.setLayout(new GridLayout());
final GridLayout gl_fileOptionGroup = new GridLayout();
gl_fileOptionGroup.numColumns = 3;
fileOptionGroup.setLayout(gl_fileOptionGroup);
btnOverwrite = new Button(fileOptionGroup, SWT.RADIO);
btnOverwrite.setLayoutData(new GridData());
btnOverwrite.setToolTipText("Overwirte to an existing file");
btnOverwrite.setText("Overwrite");
btnOverwrite.setSelection(true);
btnSkip = new Button(fileOptionGroup, SWT.RADIO);
btnSkip.setLayoutData(new GridData());
btnSkip.setToolTipText("Skip to save the file");
btnSkip.setText("Skip");
btnSkip.setSelection(false);
btnRetry = new Button(fileOptionGroup, SWT.RADIO);
btnRetry.setLayoutData(new GridData());
btnRetry.setToolTipText("Retry to get the file");
btnRetry.setText("Retry");
btnRetry.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
enableDisableControls();
}
});
retryOptionGroup = new Group(projectPane, SWT.NONE);
retryOptionGroup.setText("Retry options");
final GridData gd_retryOptionGroup = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1);
retryOptionGroup.setLayoutData(gd_retryOptionGroup);
retryOptionGroup.setLayout(new GridLayout());
final GridLayout gl_retryOptionGroup = new GridLayout();
gl_retryOptionGroup.numColumns = 2;
retryOptionGroup.setLayout(gl_retryOptionGroup);
sendRetriesLabel = new Label(retryOptionGroup, SWT.NULL);
final GridData gd_sendRetriesLabel = new GridData();
gd_sendRetriesLabel.horizontalIndent = 20;
gd_sendRetriesLabel.horizontalAlignment = SWT.FILL;
sendRetriesLabel.setLayoutData(gd_sendRetriesLabel);
sendRetriesLabel.setText("Send Attempts:");
sendRetriesSpin = new Spinner(retryOptionGroup, SWT.BORDER | SWT.SINGLE);
sendRetriesSpin.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
sendRetriesSpin.setToolTipText("The number of times to attempt to send a message to the external resource before failing with an error.");
sendRetriesSpin.setValues(5, 1, Spinner.LIMIT, 0, 1, 10);
retryIntervalLabel = new Label(retryOptionGroup, SWT.NULL);
retryIntervalLabel.setText("Interval between Attempts (ms):");
final GridData gd_retryIntervalText = new GridData();
gd_retryIntervalText.horizontalIndent = 20;
gd_retryIntervalText.horizontalAlignment = SWT.FILL;
retryIntervalLabel.setLayoutData(gd_retryIntervalText);
sendRetryIntervalText = new StyledText(retryOptionGroup, SWT.BORDER | SWT.SINGLE);
sendRetryIntervalText.setToolTipText("The time interval in milliseconds the connector waits between message send attempts.");
sendRetryIntervalText.setText("10000");
sendRetryIntervalText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
new Label(this, SWT.NONE);
useTempFileButton = new Button(projectPane, SWT.CHECK);
useTempFileButton.setToolTipText("Indicates if the data is to be gathered in a temporary file first and renamed when writing is complete.");
useTempFileButton.setText("Use temporary file");
useTempFileButton.setSelection(false);
useTempFileButton.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
enableDisableControls();
}
});
new Label(this, SWT.NONE);
useTemporaryFileGroup = new Group(projectPane, SWT.NONE);
final GridData gd_useTemporaryFileGroup = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1);
useTemporaryFileGroup.setLayoutData(gd_useTemporaryFileGroup);
useTemporaryFileGroup.setLayout(new GridLayout());
final GridLayout gl_useTemporaryFileGroup = new GridLayout();
gl_useTemporaryFileGroup.numColumns = 2;
useTemporaryFileGroup.setLayout(gl_useTemporaryFileGroup);
tempFilePrefixLabel = new Label(useTemporaryFileGroup, SWT.NULL);
final GridData gd_tempFilePrefixLabel = new GridData();
gd_tempFilePrefixLabel.horizontalIndent = 20;
gd_tempFilePrefixLabel.horizontalAlignment = SWT.FILL;
tempFilePrefixLabel.setLayoutData(gd_tempFilePrefixLabel);
tempFilePrefixLabel.setText("Temp file prefix:");
tempFilePrefixText = new StyledText(useTemporaryFileGroup, SWT.BORDER | SWT.SINGLE);
tempFilePrefixText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
tempFilePrefixText.addModifyListener(modifyListener);
tempFilePrefixText.setToolTipText("The prefix string to be used in generating the temp file's name; must be at least three characters long");
tempFilePrefixText.setText(IFileConnectorProfileConstants.DEFAULT_TEMPFILE_PREFIX);
try
{
tempFilePrefixProposal = new ParameterProposals(tempFilePrefixText);
}
catch (Exception e1)
{
}
tempFileSuffixLabel = new Label(useTemporaryFileGroup, SWT.NULL);
tempFileSuffixLabel.setText("Temp file suffix:");
final GridData gd_tempFileSuffixLabel = new GridData();
gd_tempFileSuffixLabel.horizontalIndent = 20;
gd_tempFileSuffixLabel.horizontalAlignment = SWT.FILL;
tempFileSuffixLabel.setLayoutData(gd_tempFileSuffixLabel);
tempFileSuffixText = new StyledText(useTemporaryFileGroup, SWT.BORDER | SWT.SINGLE);
tempFileSuffixText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
tempFileSuffixText.addModifyListener(modifyListener);
tempFileSuffixText.setToolTipText("The suffix string to be used in generating the temp file's name");
tempFileSuffixText.setText(IFileConnectorProfileConstants.DEFAULT_TEMPFILE_SUFFIX);
try
{
tempFileSuffixProposal = new ParameterProposals(tempFileSuffixText);
}
catch (Exception e1)
{
}
new Label(this, SWT.NONE);
fileContentsLabel = new Label(projectPane, SWT.NULL);
fileContentsLabel.setText("Replace an empty message with:");
fileContentsLabel.setLayoutData(new GridData());
fileContentsText = new StyledText(projectPane, SWT.BORDER | SWT.SINGLE);
fileContentsText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
fileContentsText.setToolTipText("The default contents to be used when receiving contents is null");
final Group archiveModeGroup = new Group(projectPane, SWT.NONE);
archiveModeGroup.setText("Archive Selection");
final GridData gd_archiveModeGroup = new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1);
gd_archiveModeGroup.heightHint = 141;
archiveModeGroup.setLayoutData(gd_archiveModeGroup);
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
archiveModeGroup.setLayout(gridLayout);
noneButton = new Button(archiveModeGroup, SWT.RADIO);
noneButton.setSelection(true);
noneButton.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
enableDisableControls();
}
});
noneButton.setToolTipText("Only use this mode to test the configuration. This is not suitable for production operation.");
final GridData gd_noneButton = new GridData();
gd_noneButton.horizontalIndent = 10;
noneButton.setLayoutData(gd_noneButton);
noneButton.setText("None");
new Label(archiveModeGroup, SWT.NONE);
new Label(archiveModeGroup, SWT.NONE);
deleteButton = new Button(archiveModeGroup, SWT.RADIO);
deleteButton.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
enableDisableControls();
}
});
deleteButton.setToolTipText("Delete a file after it is processed.");
final GridData gd_deleteButton = new GridData();
gd_deleteButton.horizontalIndent = 10;
deleteButton.setLayoutData(gd_deleteButton);
deleteButton.setText("Delete");
new Label(archiveModeGroup, SWT.NONE);
new Label(archiveModeGroup, SWT.NONE);
backupButton = new Button(archiveModeGroup, SWT.RADIO);
backupButton.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
enableDisableControls();
handleValidationListeners(null);
}
});
backupButton.setToolTipText("Move a file to the Archive directory after it is processed.");
final GridData gd_backupButton = new GridData();
gd_backupButton.horizontalIndent = 10;
backupButton.setLayoutData(gd_backupButton);
backupButton.setText("Backup");
new Label(archiveModeGroup, SWT.NONE);
new Label(archiveModeGroup, SWT.NONE);
archiveDirectoryLabel = new Label(archiveModeGroup, SWT.NONE);
final GridData gd_archiveDirectoryLabel = new GridData();
gd_archiveDirectoryLabel.horizontalIndent = 20;
archiveDirectoryLabel.setLayoutData(gd_archiveDirectoryLabel);
archiveDirectoryLabel.setText("Archive Directory:");
archiveDirectoryText = new StyledText(archiveModeGroup, SWT.BORDER);
archiveDirectoryText.addModifyListener(modifyListener);
try
{
archiveDirectoryProposal = new ParameterProposals(archiveDirectoryText);
}
catch (Exception e1)
{
}
archiveDirectoryText.setToolTipText("The directory to move files to after they are processed.");
final GridData gd_archiveDirectoryText = new GridData(SWT.FILL, SWT.CENTER, true, false);
archiveDirectoryText.setLayoutData(gd_archiveDirectoryText);
browseArchiveDirectoryButton = new Button(archiveModeGroup, SWT.NONE);
browseArchiveDirectoryButton.setToolTipText("Select the directory the listener will move files to after they are processed.");
final GridData gd_browseArchiveDirectoryButton = new GridData();
browseArchiveDirectoryButton.setLayoutData(gd_browseArchiveDirectoryButton);
browseArchiveDirectoryButton.setText("...");
new Label(this, SWT.NONE);
browseArchiveDirectoryButton.addSelectionListener(new SelectionAdapter()
{
#Override
public void widgetSelected(final SelectionEvent e)
{
String dir = doBrowse(browseArchiveDirectoryButton.getToolTipText(), "Select Archive Directory");
if (dir != null)
{
archiveDirectoryText.setText(dir);
}
}
});
archiveFileNameLabel = new Label(archiveModeGroup, SWT.NULL);
archiveFileNameLabel.setText("Archieve FileName:");
archiveFileNameLabel.setToolTipText("The name of the file to write to");
archivefileNameText = new StyledText(archiveModeGroup, SWT.BORDER | SWT.SINGLE);
archivefileNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
archivefileNameText.addModifyListener(modifyListener);
try
{
archivefileNameProposal = new ParameterProposals(archivefileNameText);
}
catch (Exception e1)
{
}
enableDisableControls();
new Label(this, SWT.NONE);
recordDelimiterLabel = new Label(projectPane, SWT.NONE);
recordDelimiterLabel.setText("Record Delimiter:");
recordDelimiterLabel.setLayoutData(new GridData());
recordDelimiterText = new Text(projectPane, SWT.BORDER | SWT.SINGLE);
// recordDelimiterText.setText("<CR><LF>");
recordDelimiterText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
recordDelimiterText.setToolTipText("Put delimiter if needed, <CR><LF> for carriage return.");
new Label(this, SWT.NONE);
recordLengthLabel = new Label(projectPane, SWT.NONE);
recordLengthLabel.setText("Record Length:");
recordLengthLabel.setLayoutData(new GridData());
recordLengthSpinner = new Spinner(projectPane, SWT.BORDER);
recordLengthSpinner.setMaximum(Integer.MAX_VALUE);
recordLengthSpinner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
recordLengthSpinner.setToolTipText("Delimited by a specified length");
new Label(this, SWT.NONE);
scrolledPane.setContent(projectPane);
scrolledPane.setExpandVertical(true);
scrolledPane.setExpandHorizontal(true);
scrolledPane.setMinSize(projectPane.computeSize(SWT.DEFAULT,SWT.DEFAULT));
enableDisableControls();
}
thanks
I am new to SWT development and am trying to build an extremely simple GUI window (going by the online tutorials and examples). My little GUI takes a string and parses it (using a parsing lib) and displays the parsed data in fields in a group.
Thus far, it works for ONE PASS. I enter a string, hit "Parse It", and the string is parsed correctly, and the corresponding data fields are shown in the grouping below the entry text box and buttons. I have a "Clear All" button which clears these fields. If I hit "Parse It" again, the parsing logic does execute (as is evident from console output) BUT the UI does not display the fields. (So far I have only implemented for the fixed width radio option until I get around this).
The behavior is perplexing to me. I have tried multiple things such as putting the group re-creation code in the mouseUp on the clear button, as opposed to only disposing the group. I have tried putting the group re-creation in the parse it button action code. (I also had tried creating subclasses of MouseListener for each, passing in references as necessary, but for simplicity's sake have just put everything back into an anon inner class).
I use group.layout() and not redraw. What is this SWT newbie missing? Surely it must be something super simple. MTIA! (Apologies if the code is messy - been playing with it a lot.)
Code:
package com.mycompany.common.utility.messageparser.ui;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.beanutils.PropertyUtils;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;
import com.mycompany.common.utility.MessageDefinitionFactory;
import com.mycompany.common.utility.FixedWidthMessageParserUtility;
import com.mycompany.messageutils.*;
public class MainWindow
{
private static Text messageInput;
public static Display display = null;
public static Shell windowShell = null;
public static Group group = null;
public static void main(String[] args)
{
Display display = Display.getDefault();
Shell shlMultiMessageParser= new Shell();
shlMultiMessageParser.setSize(460, 388);
shlMultiMessageParser.setText("Message Parser Utility");
shlMultiMessageParser.setLayout(new FormLayout());
final Composite composite = new Composite(shlMultiMessageParser, SWT.NONE);
FormData fd_composite = new FormData();
fd_composite.bottom = new FormAttachment(0, 351);
fd_composite.right = new FormAttachment(0, 442);
fd_composite.top = new FormAttachment(0, 10);
fd_composite.left = new FormAttachment(0, 10);
composite.setLayoutData(fd_composite);
composite.setLayout(new FormLayout());
group = new Group(composite, SWT.NONE);
FormData fd_group = new FormData();
fd_group.bottom = new FormAttachment(0, 331);
fd_group.right = new FormAttachment(0, 405);
fd_group.top = new FormAttachment(0, 79);
fd_group.left = new FormAttachment(0, 10);
group.setLayoutData(fd_group);
group.setLayout(new GridLayout(2, false));
Button btnFixedWidth= new Button(composite, SWT.RADIO);
FormData fd_btnFixedWidth= new FormData();
btnFixedWidth.setLayoutData(fd_btnFixedWidth);
btnFixedWidth.setText("FixedWidth");
Button btnDelimited = new Button(composite, SWT.RADIO);
fd_btnFixedWidth.top = new FormAttachment(btnDelimited, 0, SWT.TOP);
fd_btnFixedWidth.left = new FormAttachment(btnDelimited, 23);
FormData fd_btnDelimited = new FormData();
btnDelimited.setLayoutData(fd_btnDelimited);
btnDelimited.setText("DELIM");
Button btnGeneric = new Button(composite, SWT.RADIO);
fd_btnDelimited.left = new FormAttachment(btnGeneric, 17);
btnGeneric.setText("GENERIC");
btnGeneric.setLayoutData(new FormData());
messageInput = new Text(composite, SWT.BORDER);
messageInput.setSize(128, 12);
FormData fd_messageInput = new FormData();
fd_messageInput.top = new FormAttachment(0, 40);
fd_messageInput.left = new FormAttachment(0, 10);
messageInput.setLayoutData(fd_messageInput);
Button btnParseIt = new Button(composite, SWT.NONE);
fd_messageInput.right = new FormAttachment(btnParseIt, -6);
FormData fd_btnParseIt = new FormData();
fd_btnParseIt.top = new FormAttachment(0, 38);
fd_btnParseIt.right = new FormAttachment(100, -29);
fd_btnParseIt.left = new FormAttachment(0, 335);
btnParseIt.setLayoutData(fd_btnParseIt);
btnParseIt.setText("Parse it");
// btnParseIt.addMouseListener (new ParseItButtonAction(messageInput,
// group, btnFixedWidth, btnDelimited, btnGeneric));
// PARSE IT BUTTON ACTION
btnParseIt.addMouseListener(new MouseListener()
{
public void mouseUp(MouseEvent arg0)
{
String messageString = messageInput.getText();
if (null == messageString || messageString.isEmpty())
return;
// PARSE THE MESSAGE AND BUILD THE FORM!
String messageId = messageString.substring(0, 3);
MessageDefinition messageDefinition = null;
try
{
// Will need to pull the type from the radio buttons
messageDefinition = (MessageDefinition) (MessageDefinitionFactory.getMessageDefinition("FixedWidth", messageId)).newInstance();
}
catch (Exception e2)
{
System.out.println("CAUGHT " + e2.getClass().getName() + ": " + e2.getMessage());
e2.printStackTrace();
}
ArrayList<FieldDefinition> fields = messageDefinition.getFields();
Object messageBean = null;
// List of ALL the name value pairs to be displayed.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
messageBean = MessageHelper.getObjectFromDefinition(messageString, messageDefinition, ClientMessageType.FixedWidth);
/**
* Get the properties of the bean and display their names
* and values
*/
nameValuePairs = getNameValuePairs(messageBean, fields, nameValuePairs);
for (NameValuePair nameValuePair : nameValuePairs)
{
Label lblNewLabel = new Label(group, SWT.NONE);
lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblNewLabel.setText(nameValuePair.name);
Text textField = new Text(group, SWT.BORDER);
textField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textField.setText(nameValuePair.value);
}
/**
* End iterate thru bean properties
*/
group.layout(true);
//windowShell.layout(true);
}
catch (MessageParsingException e1)
{
System.out.println("CAUGHT " + e1.getClass().getName() + ": " + e1.getMessage());
e1.printStackTrace();
}
}
#Override
public void mouseDown(MouseEvent arg0)
{
}
#Override
public void mouseDoubleClick(MouseEvent arg0)
{
}
public List getNameValuePairs(Object messageBean, List<FieldDefinition> fields, List<NameValuePair> list)
{
Object property = null;
if (fields == null)
{
Method[] objectMethods = messageBean.getClass().getDeclaredMethods();
String fieldName = "";
Object fieldValue = null;
for (Method thisMethod : objectMethods)
{
if (thisMethod.getName().contains("get"))
{
fieldName = thisMethod.getName().substring(3, thisMethod.getName().length());
System.out.println("ATTEMPTING TO INVOKE get" + fieldName + "() on " + messageBean.getClass().getName());
try
{
fieldValue = thisMethod.invoke(messageBean);
}
catch (Exception e)
{
System.out.println("CAUGHT TRYING TO GET " + fieldName + " From " + messageBean.getClass().getName() + "::" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
list.add(new NameValuePair(fieldName, String.valueOf(fieldValue)));
}
}
}
else
{
for (FieldDefinition f : fields)
{
try
{
property = PropertyUtils.getProperty(messageBean, f.getPropertyName());
}
catch (Exception e)
{
System.out.println("CAUGHT " + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
if (property instanceof java.lang.String)
{
list.add(new NameValuePair(f.getPropertyName(), (String) property));
}
else if (property instanceof java.util.GregorianCalendar)
{
java.util.GregorianCalendar date = (java.util.GregorianCalendar) property;
Calendar cal = date;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String value = dateFormat.format(cal.getTime());
list.add(new NameValuePair(f.getPropertyName(), value));
}
else if (property instanceof java.util.List)
{
for (Object thePropertyObject : (List) property)
{
System.out.println("Class type of property is " + thePropertyObject.getClass().getName());
list = getNameValuePairs(thePropertyObject, null, list);
}
}
else
// could be Integer or Long.
{
list.add(new NameValuePair(f.getPropertyName(), String.valueOf(property)));
}
}
} // END else fields not null
return list;
}
}); // END OF PARSE IT BUTTON MOUSE LISTENER
// CLEAR ALL BUTTON
Button btnClearAll = new Button(composite, SWT.NONE);
btnClearAll.addMouseListener(new MouseListener()
{
#Override
public void mouseUp(MouseEvent arg0)
{
System.out.println("CLEAR ALL MOUSE UP");
if ((group != null) && (! group.isDisposed()))
{
group.dispose();
}
// REFRESH THE GROUP
group = new Group(composite, SWT.NONE);
FormData fd_group = new FormData();
fd_group.bottom = new FormAttachment(0, 331);
fd_group.right = new FormAttachment(0, 405);
fd_group.top = new FormAttachment(0, 79);
fd_group.left = new FormAttachment(0, 10);
group.setLayoutData(fd_group);
group.setLayout(new GridLayout(2, false));
group.layout(true); }
#Override
public void mouseDown(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
#Override
public void mouseDoubleClick(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
});
Label lblNewLabel = new Label(composite, SWT.NONE);
FormData fd_lblNewLabel = new FormData();
fd_lblNewLabel.right = new FormAttachment(0, 167);
fd_lblNewLabel.top = new FormAttachment(0, 20);
fd_lblNewLabel.left = new FormAttachment(0, 10);
lblNewLabel.setLayoutData(fd_lblNewLabel);
lblNewLabel.setText("Paste message below:");
btnClearAll.setToolTipText("Click here to clear ALL fields.");
btnClearAll.setText("Clear All");
FormData fd_btnClearAll = new FormData();
fd_btnClearAll.right = new FormAttachment(btnParseIt, 68);
fd_btnClearAll.bottom = new FormAttachment(lblNewLabel, 0, SWT.BOTTOM);
fd_btnClearAll.left = new FormAttachment(btnParseIt, 0, SWT.LEFT);
btnClearAll.setLayoutData(fd_btnClearAll);
shlMultiMessageParser.open();
shlMultiMessageParser.layout();
while (!shlMultiMessageParser.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
}
}
class NameValuePair
{
public String name = "";
public String value = "";
public NameValuePair(String name, String value)
{
this.name = name;
this.value = value;
}
}
class ClearAllButtonAction extends MouseAdapter
{
Group group = null;
Composite composite = null;
public ClearAllButtonAction(Group group, Composite composite)
{
System.out.println("CLEAR ALL BUTTON CTOR");
this.group = group;
this.composite = composite;
}
public void mouseUp(MouseEvent e)
{
System.out.println("CLEAR ALL MOUSE UP");
group.dispose();
/*
* group = new Group(composite, SWT.NONE); FormData fd_group = new
* FormData(); fd_group.bottom = new FormAttachment(0, 331);
* fd_group.right = new FormAttachment(0, 405); fd_group.top = new
* FormAttachment(0, 79); fd_group.left = new FormAttachment(0, 10);
* group.setLayoutData(fd_group); group.setLayout(new GridLayout(2,
* false)); group.layout(true);
*/}
}
class ParseItButtonAction extends MouseAdapter
{
private Text messageInput = null;
private Group group = null;
private Button btnFixedWidth = null, btnDELIM = null;
public ParseItButtonAction(Text messageInput, Group group, Button btnFixedWidth, Button btnDELIM, Button btnGeneric)
{
this.messageInput = messageInput;
this.group = group;
this.btnFixedWidth = btnFixedWidth;
this.btnDELIM = btnDELIM;
}
public void mouseUp(MouseEvent e)
{
// PARSE THE MESSAGE AND BUILD THE FORM!
String messageString = messageInput.getText();
String messageId = messageString.substring(0, 3);
MessageDefinition messageDefinition = null;
try
{
// Will need to pull the type from the radio buttons
messageDefinition = (MessageDefinition) (MessageDefinitionFactory.getMessageDefinition("FixedWidth", messageId)).newInstance();
}
catch (Exception e2)
{
System.out.println("CAUGHT " + e2.getClass().getName() + ": " + e2.getMessage());
e2.printStackTrace();
}
ArrayList<FieldDefinition> fields = messageDefinition.getFields();
// If this were DELIM, it would be handling a BaseMessageBean type.
Object messageBean = null;
// List of ALL the name value pairs to be displayed.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
messageBean = MessageHelper.getObjectFromDefinition(messageString, messageDefinition, ClientMessageType.FixedWidth);
/**
* Get the properties of the bean and display their names and values
*/
nameValuePairs = getNameValuePairs(messageBean, fields, nameValuePairs);
for (NameValuePair nameValuePair : nameValuePairs)
{
Label lblNewLabel = new Label(group, SWT.NONE);
lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblNewLabel.setText(nameValuePair.name);
Text textField = new Text(group, SWT.BORDER);
textField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
textField.setText(nameValuePair.value);
}
/**
* End iterate thru bean properties
*/
group.layout();
}
catch (MessageParsingException e1)
{
System.out.println("CAUGHT " + e1.getClass().getName() + ": " + e1.getMessage());
e1.printStackTrace();
}
}
// The Object type should be converted into a type of messageBean superclass
public List getNameValuePairs(Object messageBean, List<FieldDefinition> fields, List<NameValuePair> list)
{
Object property = null;
// BECAUSE FixedWidth/GENERIC DO NOT SPECIFY TYPES FOR MESSAGE SUBSECTIONS
if (fields == null)
{
Method[] objectMethods = messageBean.getClass().getDeclaredMethods();
String fieldName = "";
Object fieldValue = null;
for (Method thisMethod : objectMethods)
{
if (thisMethod.getName().contains("get"))
{
fieldName = thisMethod.getName().substring(3, thisMethod.getName().length());
System.out.println("ATTEMPTING TO INVOKE get" + fieldName + "() on " + messageBean.getClass().getName());
try
{
fieldValue = thisMethod.invoke(messageBean);
}
catch (IllegalArgumentException e)
{
System.out.println("CAUGHT TRYING TO GET " + fieldName + " From " + messageBean.getClass().getName() + "::" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
catch (IllegalAccessException e)
{
System.out.println("CAUGHT TRYING TO GET " + fieldName + " From " + messageBean.getClass().getName() + "::" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
catch (InvocationTargetException e)
{
System.out.println("CAUGHT TRYING TO GET " + fieldName + " From " + messageBean.getClass().getName() + "::" + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
list.add(new NameValuePair(fieldName, String.valueOf(fieldValue)));
}
}
}
else
{
for (FieldDefinition f : fields)
{
try
{
property = PropertyUtils.getProperty(messageBean, f.getPropertyName());
}
catch (Exception e)
{
System.out.println("CAUGHT " + e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
if (property instanceof java.lang.String)
{
list.add(new NameValuePair(f.getPropertyName(), (String) property));
}
else if (property instanceof java.util.GregorianCalendar)
{
java.util.GregorianCalendar date = (java.util.GregorianCalendar) property;
Calendar cal = date;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String value = dateFormat.format(cal.getTime());
list.add(new NameValuePair(f.getPropertyName(), value));
}
else if (property instanceof java.util.List)
{
for (Object thePropertyObject : (List) property)
{
System.out.println("Class type of property is " + thePropertyObject.getClass().getName());
// Need to use the factory to get the message bean type
// for the subsections, but cannot
// DO THIS for SUBSECTIONS FOR FixedWidth/GENERIC, ONLY DELIM.
// ARGH.
// Add these types to the message factory, then do the
// lookup. for now just print the types.
list = getNameValuePairs(thePropertyObject, null, list);
}
}
else
// could be Integer or Long.
{
list.add(new NameValuePair(f.getPropertyName(), String.valueOf(property)));
}
}
} // END else fields not null
return list;
}
}
I genericized the code to show it below.
Found it. I need to dispose the children of the group, and not the group itself.
if ((group != null) && (! group.isDisposed()))
{
for (Control childWidget: group.getChildren())
{
childWidget.dispose();
}
}
messageInput.setText("");
This is a simple executable snippet that shows the issue.
When using the ExpandBar the desired outcome is to resize the window when there is a collapse or expand. It works properly on Mac but does not on Linux.
It looks like the ExpandListener is called before the collapse/expand actually occurs and therefore the pack() resizes incorrectly.
The async execution is merely a bandage to have it work on Mac but this does not work on Linux.
import org.eclipse.swt.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.ExpandEvent;
import org.eclipse.swt.events.ExpandListener;
public class ExpandBarExample {
public static void main(String[] args) {
Shell shell = new Shell(SWT.DIALOG_TRIM | SWT.MIN
| SWT.APPLICATION_MODAL);
shell.setLayout(new FormLayout());
shell.setText("Expand Bar");
final ExpandBar bar = new ExpandBar(shell, SWT.NONE);
FormData fd = new FormData();
fd.top = new FormAttachment(0);
fd.left = new FormAttachment(0);
fd.right = new FormAttachment(100);
fd.bottom = new FormAttachment(100);
bar.setLayoutData(fd);
bar.addExpandListener(new ExpandListener() {
public void itemCollapsed(ExpandEvent arg0) {
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
bar.getShell().pack();
}
});
}
public void itemExpanded(ExpandEvent arg0) {
bar.getShell().pack();
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
bar.getShell().pack();
}
});
}
});
Composite composite = new Composite(bar, SWT.NONE);
fd = new FormData();
fd.left = new FormAttachment(0);
fd.right = new FormAttachment(100);
composite.setLayoutData(fd);
FormLayout layout = new FormLayout();
layout.marginLeft = layout.marginTop = layout.marginRight = layout.marginBottom = 8;
composite.setLayout(layout);
Label label = new Label(composite, SWT.NONE);
label.setText("This is Bar 1");
ExpandItem item1 = new ExpandItem(bar, SWT.NONE, 0);
item1.setText("Bar 1");
item1.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
item1.setControl(composite);
item1.setExpanded(true);
composite = new Composite(bar, SWT.NONE);
fd = new FormData();
fd.left = new FormAttachment(0);
fd.right = new FormAttachment(100);
composite.setLayoutData(fd);
layout = new FormLayout();
layout.marginLeft = layout.marginTop = layout.marginRight = layout.marginBottom = 8;
composite.setLayout(layout);
label = new Label(composite, SWT.NONE);
label.setText("This is Bar2");
ExpandItem item2 = new ExpandItem(bar, SWT.NONE, 1);
item2.setText("Bar 2");
item2.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
item2.setControl(composite);
item2.setExpanded(true);
composite = new Composite(bar, SWT.NONE);
fd = new FormData();
fd.left = new FormAttachment(0);
fd.right = new FormAttachment(100);
composite.setLayoutData(fd);
layout = new FormLayout();
layout.marginLeft = layout.marginTop = layout.marginRight = layout.marginBottom = 8;
composite.setLayout(layout);
label = new Label(composite, SWT.NONE);
label.setText("This is Bar3");
ExpandItem item3 = new ExpandItem(bar, SWT.NONE, 2);
item3.setText("Bar 3");
item3.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
item3.setControl(composite);
item3.setExpanded(true);
bar.setSpacing(6);
shell.pack();
shell.open();
Display display = shell.getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
I am unhappy with this solution but it works.
Definitely a XXX solution
Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken.
- java.sun.com
without further ado
import org.eclipse.swt.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.ExpandEvent;
import org.eclipse.swt.events.ExpandListener;
public class ExpandBarExample {
public static void main(String[] args) {
Shell shell = new Shell(SWT.DIALOG_TRIM | SWT.MIN
| SWT.APPLICATION_MODAL);
shell.setLayout(new FormLayout());
shell.setText("Expand Bar");
final ExpandBar bar = new ExpandBar(shell, SWT.NONE);
FormData fd = new FormData();
fd.top = new FormAttachment(0);
fd.left = new FormAttachment(0);
fd.right = new FormAttachment(100);
fd.bottom = new FormAttachment(100);
bar.setLayoutData(fd);
bar.addExpandListener(new ExpandListener() {
private void resize(final ExpandEvent event, final boolean expand){
final Display display = Display.getCurrent();
new Thread(new Runnable() {
public void run() {
final int[] orgSize = new int[1];
final int[] currentSize = new int[1];
final Object lock = new Object();
if (display.isDisposed() || bar.isDisposed()){
return;
}
display.syncExec(new Runnable() {
public void run() {
if (bar.isDisposed() || bar.getShell().isDisposed()){
return;
}
synchronized(lock){
bar.getShell().pack(true);
orgSize[0] = bar.getShell().getSize().y;
currentSize[0] = orgSize[0];
}
}
});
while (currentSize[0] == orgSize[0]){
if (display.isDisposed() || bar.isDisposed()){
return;
}
display.syncExec(new Runnable() {
public void run() {
synchronized(lock){
if (bar.isDisposed() || bar.getShell().isDisposed()){
return;
}
currentSize[0] = bar.getShell().getSize().y;
if (currentSize[0] != orgSize[0]){
return;
}
else{
bar.getShell().layout(true);
bar.getShell().pack(true);
}
}
}
});
}
}
}).start();
}
public void itemCollapsed(ExpandEvent event) {
resize(event, false);
}
public void itemExpanded(ExpandEvent event) {
resize(event, true);
}
});
Composite composite = new Composite(bar, SWT.NONE);
fd = new FormData();
fd.left = new FormAttachment(0);
fd.right = new FormAttachment(100);
composite.setLayoutData(fd);
FormLayout layout = new FormLayout();
layout.marginLeft = layout.marginTop = layout.marginRight = layout.marginBottom = 8;
composite.setLayout(layout);
Label label = new Label(composite, SWT.NONE);
label.setText("This is Bar 1");
ExpandItem item1 = new ExpandItem(bar, SWT.NONE, 0);
item1.setText("Bar 1");
item1.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
item1.setControl(composite);
item1.setExpanded(true);
composite = new Composite(bar, SWT.NONE);
fd = new FormData();
fd.left = new FormAttachment(0);
fd.right = new FormAttachment(100);
composite.setLayoutData(fd);
layout = new FormLayout();
layout.marginLeft = layout.marginTop = layout.marginRight = layout.marginBottom = 8;
composite.setLayout(layout);
label = new Label(composite, SWT.NONE);
label.setText("This is Bar2");
ExpandItem item2 = new ExpandItem(bar, SWT.NONE, 1);
item2.setText("Bar 2");
item2.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
item2.setControl(composite);
item2.setExpanded(true);
composite = new Composite(bar, SWT.NONE);
fd = new FormData();
fd.left = new FormAttachment(0);
fd.right = new FormAttachment(100);
composite.setLayoutData(fd);
layout = new FormLayout();
layout.marginLeft = layout.marginTop = layout.marginRight = layout.marginBottom = 8;
composite.setLayout(layout);
label = new Label(composite, SWT.NONE);
label.setText("This is Bar3");
ExpandItem item3 = new ExpandItem(bar, SWT.NONE, 2);
item3.setText("Bar 3");
item3.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
item3.setControl(composite);
item3.setExpanded(true);
bar.setSpacing(6);
shell.pack();
shell.open();
Display display = shell.getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
If anyone wants to know what this is doing and doesn't want to look at the code.
Basically the ExpandListener looks at the original height of the shell, and issues syncExec's to pack() the shell until the shell actually changes size. A very busy waiting approach.
This is an old post but I recently had this problem, and found this solution helphul.
However, I find that it is only necessary to call shell.pack() from another thread (via syncExec of course). I never have to go through loop. So I ctreated this little subroutine:
private void async_shell_pack(final Display display, final ExpandBar bar) {
new Thread(new Runnable(){
public void run(){
display.syncExec(new Runnable() {
public void run() {
bar.getShell().pack(true);
}
});
}}).start();
}
This seems to work fine. For my purposes, better still, was to simply grow the height of the shell by the height of the expanded item using the following listener.
public void itemExpanded(ExpandEvent e) {
if (e.item instanceof ExpandItem){
ExpandItem item = (ExpandItem)e.item;
shell.setSize(shell.getSize().x, shell.getSize().y+item.getHeight());
} else {
System.out.println("Boom");
}
}
This means no messing about with threads.