SWT Text Component Horizontal Alignment - java

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

Related

When centering dialog, first appears on topleft corner for some milliseconds

I'm generating a dialog with a lot of content. I want to pack the dialog to the childrens height, and I want to center it on screen, so I'm doing this after adding all the childrens:
shell.open();
shell.layout();
shell.pack(); //for wrap the dialog size to it's content width and height.
//the dialog must be centered after doing shell.pack();
Rectangle parentSize = getParent().getBounds();
Rectangle shellSize = shell.getBounds();
int x = parentSize.x + (parentSize.width - shellSize.width) / 2;
int y = (int) (parentSize.y + (parentSize.height - shellSize.height) / 3.5);
shell.setLocation(new Point(x, y));
The problem is that for some milliseconds the dialog is being visible with a lot of width and on the top left corner of the screen. I tried doing setVisible(false) and (true) to shell to do the trick but it doesn't works.
How can I avoid to see the dialog on the top left corner and with a lot of width for some milliseconds?
This is the full code:
public class SelectTwoMatrixNumbersDialog extends Dialog {
protected ArrayList<Integer> matrixNumbers1;
protected ArrayList<Integer> matrixNumbers2;
protected Shell shell;
private JointBet jointBet;
private boolean result;
NumbersMatrixWidget numbersMatrixWidget1;
NumbersMatrixWidget numbersMatrixWidget2;
/**
* Create the dialog.
* #param parent
* #param style
*/
public SelectTwoMatrixNumbersDialog(Shell parent, int style, JointBet jointBet) {
super(parent, style);
setText("Elegir Números");
this.jointBet = jointBet;
}
/**
* Open the dialog.
* #return the result
*/
public boolean open() {
createContents();
matrixNumbers1 = new ArrayList<Integer>();
matrixNumbers2 = new ArrayList<Integer>();
GridLayout gl_shell = new GridLayout(1, false);
gl_shell.marginWidth = 20;
gl_shell.marginHeight = 20;
shell.setLayout(gl_shell);
Composite contentComposite = new Composite(shell, SWT.NONE);
contentComposite.setLayout(new GridLayout(1, false));
contentComposite.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1));
Label lblNumbers = new Label(contentComposite, SWT.NONE);
lblNumbers.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
lblNumbers.setText("Números:");
Composite numbersContainerComposite = new Composite(contentComposite, SWT.NONE);
numbersContainerComposite.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
//variable values depending of type of game
boolean firstCellEmpty = jointBet.getGameType().getNumbersMatrixArray()[0].isFirstCellEmpty();
int matrix1Rows = jointBet.getGameType().getNumbersMatrixArray()[0].getRows();
int matrix1Columns = jointBet.getGameType().getNumbersMatrixArray()[0].getColumns();
int matrix1MinNumber = jointBet.getGameType().getNumbersMatrixArray()[0].getMinNumber();
int matrix1MaxNumber = jointBet.getGameType().getNumbersMatrixArray()[0].getMaxNumber();
GridLayout gl_numbersContainerComposite = new GridLayout(2, false);
gl_numbersContainerComposite.horizontalSpacing = 15;
numbersContainerComposite.setLayout(gl_numbersContainerComposite);
numbersMatrixWidget1 = new NumbersMatrixWidget(numbersContainerComposite, SWT.BORDER, false, jointBet.getGameType().getNumbersMatrixArray()[0].getNumbers(), matrix1Rows, matrix1Columns, matrix1MinNumber, matrix1MaxNumber, firstCellEmpty);
//variable values depending of type of game
firstCellEmpty = jointBet.getGameType().getNumbersMatrixArray()[1].isFirstCellEmpty();
int matrix2Rows = jointBet.getGameType().getNumbersMatrixArray()[1].getRows();
int matrix2Columns = jointBet.getGameType().getNumbersMatrixArray()[1].getColumns();
int matrix2MinNumber = jointBet.getGameType().getNumbersMatrixArray()[1].getMinNumber();
int matrix2MaxNumber = jointBet.getGameType().getNumbersMatrixArray()[1].getMaxNumber();
numbersMatrixWidget2 = new NumbersMatrixWidget(numbersContainerComposite, SWT.BORDER, false, jointBet.getGameType().getNumbersMatrixArray()[1].getNumbers(), matrix2Rows, matrix2Columns, matrix2MinNumber, matrix2MaxNumber, firstCellEmpty);
numbersMatrixWidget2.setLayoutData(new GridData(SWT.LEFT, SWT.BOTTOM, false, false, 1, 1));
Composite fillNumbersComposite = new Composite(shell, SWT.NONE);
fillNumbersComposite.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
fillNumbersComposite.setLayout(new GridLayout(1, false));
Composite compositeFillMatrix1 = new Composite(fillNumbersComposite, SWT.NONE);
compositeFillMatrix1.setLayout(new GridLayout(4, false));
Label lblFillMatrix1WithMostCommonNumbers1 = new Label(compositeFillMatrix1, SWT.NONE);
lblFillMatrix1WithMostCommonNumbers1.setText("Rellenar Matriz 1 con los");
Spinner matrix1NumbersSpinner = new Spinner(compositeFillMatrix1, SWT.BORDER);
matrix1NumbersSpinner.setMaximum(jointBet.getGameType().getNumbersMatrixArray()[0].getPossibleNumbersCount());
matrix1NumbersSpinner.setMinimum(1);
Label lblFillMatrix1WithMostCommonNumbers2 = new Label(compositeFillMatrix1, SWT.NONE);
lblFillMatrix1WithMostCommonNumbers2.setText("números mas repetidos:");
Button btnFillMatrix1 = new Button(compositeFillMatrix1, SWT.NONE);
btnFillMatrix1.setText("Rellenar");
btnFillMatrix1.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
String gameType = jointBet.getGameType().getType();
int matrix = 1;
int amount = Integer.parseInt(matrix1NumbersSpinner.getText());
numbersMatrixWidget1.setNumbers(StatisticsManager.getInstance().getMostUsedNumberKeys(gameType, matrix, amount));
}
});
Composite compositeFillMatrix2 = new Composite(fillNumbersComposite, SWT.NONE);
compositeFillMatrix2.setLayout(new GridLayout(4, false));
Label lblFillMatrix2WithMostCommonNumbers1 = new Label(compositeFillMatrix2, SWT.NONE);
lblFillMatrix2WithMostCommonNumbers1.setText("Rellenar Matriz 2 con los");
Spinner matrix2NumbersSpinner = new Spinner(compositeFillMatrix2, SWT.BORDER);
matrix2NumbersSpinner.setMaximum(jointBet.getGameType().getNumbersMatrixArray()[1].getPossibleNumbersCount());
matrix2NumbersSpinner.setMinimum(1);
Label lblFillMatrix2WithMostCommonNumbers2 = new Label(compositeFillMatrix2, SWT.NONE);
lblFillMatrix2WithMostCommonNumbers2.setText("números mas repetidos:");
Button btnFillMatrix2 = new Button(compositeFillMatrix2, SWT.NONE);
btnFillMatrix2.setText("Rellenar");
btnFillMatrix2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
String gameType = jointBet.getGameType().getType();
int matrix = 2;
int amount = Integer.parseInt(matrix2NumbersSpinner.getText());
numbersMatrixWidget2.setNumbers(StatisticsManager.getInstance().getMostUsedNumberKeys(gameType, matrix, amount));
}
});
Composite buttonsComposite = new Composite(shell, SWT.NONE);
FillLayout fl_buttonsComposite = new FillLayout(SWT.HORIZONTAL);
fl_buttonsComposite.marginHeight = 10;
fl_buttonsComposite.spacing = 40;
buttonsComposite.setLayout(fl_buttonsComposite);
GridData gd_buttonsComposite = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
gd_buttonsComposite.heightHint = 45;
buttonsComposite.setLayoutData(gd_buttonsComposite);
Button acceptButton = new Button(buttonsComposite, SWT.NONE);
acceptButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//matrix 1
matrixNumbers1.clear();
for (Button b : numbersMatrixWidget1.getButtons()) {
if (b.getSelection()) {
matrixNumbers1.add(Integer.parseInt(b.getText()));
}
}
//matrix 2
matrixNumbers2.clear();
for (Button b : numbersMatrixWidget2.getButtons()) {
if (b.getSelection()) {
matrixNumbers2.add(Integer.parseInt(b.getText()));
}
}
if (matrixNumbers1.size()<jointBet.getGameType().getNumbersMatrixArray()[0].getNumbersPerBet() || matrixNumbers2.size()<jointBet.getGameType().getNumbersMatrixArray()[1].getNumbersPerBet()) {
ErrorDialog dialog = new ErrorDialog(shell, SWT.DIALOG_TRIM | SWT.PRIMARY_MODAL, "El mínimo de números es "+jointBet.getGameType().getNumbersMatrixArray()[0].getNumbersPerBet()+" + "+jointBet.getGameType().getNumbersMatrixArray()[1].getNumbersPerBet());
dialog.open();
}else {
Collections.sort(matrixNumbers1);
Collections.sort(matrixNumbers2);
jointBet.setNumbers(0, matrixNumbers1);
jointBet.setNumbers(1, matrixNumbers2);
DataManager.getInstance().saveData();
result = true;
shell.close();
}
}
});
acceptButton.setBounds(0, 0, 75, 25);
acceptButton.setText("Aceptar");
Button cancelButton = new Button(buttonsComposite, SWT.NONE);
cancelButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
result = false;
shell.close();
}
});
cancelButton.setBounds(0, 0, 75, 25);
cancelButton.setText("Cancelar");
shell.setDefaultButton(acceptButton);
shell.open();
shell.layout();
shell.pack(); //for wrap the dialog size to it's content width and height.
//the dialog must be centered after doing shell.pack();
Rectangle parentSize = getParent().getBounds();
Rectangle shellSize = shell.getBounds();
int x = parentSize.x + (parentSize.width - shellSize.width) / 2;
int y = (int) (parentSize.y + (parentSize.height - shellSize.height) / 3.5);
shell.setLocation(new Point(x, y));
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
}
/**
* Create contents of the dialog.
*/
private void createContents() {
shell = new Shell(getParent(), getStyle());
shell.setText(getText());
}
}
Just move the shell.open() to the end of the size calculations - after the shell.setLocation.

Proper use of thread and display.asyncexe in java swt

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();

StackLayout in WizardDialog and varying multiline Text with fixed height and dynamically showed scrollbar

I am working on a wizard, which should have an error composite showed on the top of controls if an error occurs. This composite contains a Text listing all errors and two Labels: above and below this component. The Label below the error list can be omitted. Dependent on the amount of errors the height of the error list should vary. However it should not exceed the height of the parent composite. If the errors don't fit into the Text with the full height, a scroll bar should be shown.
Here's a minimized snippet of what I reached till now:
package de.dannylo.issues;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
public class TestWizardPage
extends WizardPage
{
private static final String PLUGIN_ID = "de.dannylo.issues.TestPlugin";
private Composite mainComposite;
private Composite stackComposite;
private StackLayout stackLayout;
private Composite defaultMessageComposite;
private Text idText;
private static Wizard wizard;
public TestWizardPage()
{
super("portalAppWizardMavenPage");
setTitle("TestWizard");
setDescription("Testing...");
}
#Override
public void createControl(Composite parent)
{
mainComposite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
mainComposite.setLayout(layout);
layout.numColumns = 1;
layout.verticalSpacing = 15;
// source folder
Composite idComposite = new Composite(mainComposite, SWT.NONE);
idComposite.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
idComposite.setLayout(new GridLayout(2, false));
Label label = new Label(idComposite, SWT.NONE);
label.setText("ID:");
idText = new Text(idComposite, SWT.BORDER | SWT.SINGLE);
idText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
label = new Label(mainComposite, SWT.SEPARATOR | SWT.HORIZONTAL);
label.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
stackComposite = new Composite(mainComposite, SWT.NONE);
GridData layoutData = new GridData(SWT.FILL, SWT.NONE, true, false);
layoutData.heightHint = 250; // For testing purposes in the real GUI
// there are several components filling
// this composite
stackComposite.setLayoutData(layoutData);
stackLayout = new StackLayout();
stackComposite.setLayout(stackLayout);
defaultMessageComposite = new Composite(stackComposite, SWT.NONE);
defaultMessageComposite.setLayout(new GridLayout());
stackLayout.topControl = defaultMessageComposite;
label = new Label(defaultMessageComposite, SWT.NONE);
label.setText("Enter \"1\", \"2\" or \"3\" into the text field above.");
idText.addModifyListener(new ModifyListener()
{
#Override
public void modifyText(ModifyEvent e)
{
if ("1".equals(idText.getText()))
showErrorComposite("You entered id 1", "Nice job!", createTestStatusList(4));
else if ("2".equals(idText.getText()))
showErrorComposite("You entered id 2", "Oops", createTestStatusList(20));
else if ("3".equals(idText.getText()))
showErrorComposite("You entered id 3", null, createTestStatusList(20));
else
{
stackLayout.topControl = defaultMessageComposite;
stackComposite.layout();
}
}
});
setControl(mainComposite);
}
private static List<IStatus> createTestStatusList(int amount)
{
List<IStatus> toRet = new ArrayList<IStatus>();
for (int i = 0; i < amount; i++)
{
toRet.add(new Status(IStatus.ERROR, PLUGIN_ID, "Error message " + i + ": " + toRet.hashCode()));
}
return toRet;
}
private void showErrorComposite(String topMessage, String bottomMessage, List<IStatus> statusList)
{
final Composite errorComposite = new Composite(stackComposite, SWT.BORDER);
final GridLayout layout = new GridLayout();
layout.verticalSpacing = 20;
errorComposite.setLayout(layout);
errorComposite.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
final Label topLabel = new Label(errorComposite, SWT.WRAP | SWT.BORDER);
topLabel.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
topLabel.setText(topMessage);
final Text errorList = new Text(errorComposite, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY | SWT.V_SCROLL
| SWT.BORDER);
final GridData gd_errorList = new GridData(SWT.FILL, SWT.NONE, true, false);
gd_errorList.horizontalIndent = 20;
errorList.setLayoutData(gd_errorList);
for (int i = 0; i < statusList.size(); i++)
{
IStatus status = statusList.get(i);
errorList.append("\u2022 " + status.getMessage());
if (i != statusList.size() - 1)
errorList.append("\n\n");
}
final Label bottomLabel;
if (bottomMessage != null)
{
bottomLabel = new Label(errorComposite, SWT.WRAP | SWT.BORDER);
bottomLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
bottomLabel.setText(bottomMessage);
}
else
bottomLabel = null;
final Listener scrollBarListener = new Listener()
{
#Override
public void handleEvent(Event event)
{
errorList.removeListener(SWT.Resize, this);
int marginHeight = ((GridLayout)errorComposite.getLayout()).marginHeight;
int stackCompositeHeight = stackComposite.getClientArea().height;
int topLabelHeight = topLabel.getSize().y;
int verticalSpacing = layout.verticalSpacing;
int bottomLabelHeight = bottomLabel == null ? 0 : bottomLabel.getSize().y;
int spaceAboveErrorList = marginHeight + topLabelHeight + verticalSpacing;
int spaceBelowErrorList = bottomLabel == null ? marginHeight + 15 : verticalSpacing
+ bottomLabelHeight
+ marginHeight + 15;
int hHint = stackCompositeHeight - spaceAboveErrorList - spaceBelowErrorList;
Rectangle errorListClientArea = errorList.getClientArea();
Point errorListSize = errorList.computeSize(errorListClientArea.x, SWT.DEFAULT, true);
if (stackCompositeHeight < spaceAboveErrorList + errorListSize.y + spaceBelowErrorList)
{
gd_errorList.heightHint = hHint;
errorList.getVerticalBar().setVisible(true);
}
else
{
gd_errorList.heightHint = errorListSize.y;
errorList.getVerticalBar().setVisible(false);
}
errorComposite.layout();
errorList.addListener(SWT.Resize, this);
}
};
errorList.addListener(SWT.Resize, scrollBarListener);
stackLayout.topControl = errorComposite;
stackComposite.layout();
}
public static void main(String[] args)
{
Display.getDefault().syncExec(new Runnable()
{
#Override
public void run()
{
wizard = new Wizard()
{
#Override
public void addPages()
{
addPage(new TestWizardPage());
}
#Override
public boolean performFinish()
{
MessageDialog.openInformation(getShell(), "Bye!", "Thanks for testing!");
return true;
}
};
}
});
new WizardDialog(wizard.getShell(), wizard).open();
}
}
I have a problem with the ID2. In this case the height of the Text is maximum and the bottomLabel should be shown. Unfortunately this label doesn't appear as it's composite appears, but rather it appears only after the width of the window changes. It seems to be some problem with layouting. I already tried to use errorComposite.layout(true, true) (and even getShell().layout(true, true)) to flush the cache and redraw the children but this didn't help. Any ideas on how to fix that issue?
I solved your issue by entirely removing the scrollBarListener and fixing your layout a bit.
The showErrorComposite(...) method now looks like this:
private void showErrorComposite(String topMessage, String bottomMessage, List<IStatus> statusList)
{
final Composite errorComposite = new Composite(stackComposite, SWT.BORDER);
final GridLayout layout = new GridLayout();
layout.verticalSpacing = 20;
errorComposite.setLayout(layout);
errorComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final Label topLabel = new Label(errorComposite, SWT.WRAP | SWT.BORDER);
topLabel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
topLabel.setText(topMessage);
final Text errorList = new Text(errorComposite, SWT.MULTI | SWT.WRAP | SWT.READ_ONLY | SWT.V_SCROLL
| SWT.BORDER);
final GridData gd_errorList = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_errorList.horizontalIndent = 20;
errorList.setLayoutData(gd_errorList);
for (int i = 0; i < statusList.size(); i++)
{
IStatus status = statusList.get(i);
errorList.append("\u2022 " + status.getMessage());
if (i != statusList.size() - 1)
errorList.append("\n\n");
}
errorList.setTopIndex(0);
final Label bottomLabel;
if (bottomMessage != null)
{
bottomLabel = new Label(errorComposite, SWT.WRAP | SWT.BORDER);
bottomLabel.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
bottomLabel.setText(bottomMessage);
}
else
bottomLabel = null;
stackLayout.topControl = errorComposite;
stackComposite.layout();
}
It now looks like this:
UPDATE
Ok, in your particular case, leave your code as it is and just add this line at the end of your showErrorComposite(...) method:
scrollBarListener.handleEvent(null);

SWT table row mousehandler and checkbox detection

When clicking a row a window pops up.
When clicking the cell in the first column nothing happens because a checkbox is located in the first column and a mouselistener detects the cell in the first column.
But selecting the checkbox the window pops up again.
How can i prevent the window popping up when selecting the checkbox?
public class Testtable {
static Display display;
static Shell shell;
static Font small_font;
public Testtable(){}
public static void main(String args[]){
display = new Display();
small_font = new Font(Display.getDefault(), Display.getDefault().getSystemFont().getFontData() );
shell = new Shell(display, SWT.BORDER|SWT.PRIMARY_MODAL|SWT.RESIZE);
shell.setText(" Test table ");
shell.setLayout(new GridLayout(1, true));
final Table table = new Table(shell, SWT.BORDER | SWT.CHECK | SWT.V_SCROLL | SWT.FULL_SELECTION);
table.setHeaderVisible(true);
table.setFont(small_font);
GridData griddata = new GridData(SWT.FILL, SWT.FILL,false,false);
griddata.horizontalSpan=5;
griddata.heightHint = table.getItemHeight()*15;
table.setLayoutData(griddata);
TableColumn checkbox = new TableColumn(table,SWT.NONE,0);
TableColumn column_one = new TableColumn(table,SWT.NONE,1);
column_one.setText("column one");
TableColumn column_two = new TableColumn(table,SWT.NONE,2);
column_two.setText("column_two");
TableColumn column_three = new TableColumn(table,SWT.NONE,3);
column_three.setText("column_three");
TableColumn column_four = new TableColumn(table,SWT.NONE,4);
column_four.setText("column_four");
for(int i=0;i<10;i++){
TableItem item=new TableItem(table,SWT.NONE);
item.setText(new String [] {"column 2 item-"+i,"column 3 item-"+i,"column 4 item-"+i});
}
Label labelfiller=new Label(shell, SWT.SHADOW_OUT); /* Filler */
labelfiller.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_BEGINNING,0, true,true,4,2));
Button close = new Button(shell, SWT.PUSH);
close.setText("Done");
shell.setDefaultButton(close);
close.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
close.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
shell.dispose();
}
});
for(int i=0;i<table.getColumnCount();i++){
table.getColumn(i).pack();
}
table.addListener(SWT.MouseUp,new Listener(){
public void handleEvent(Event e){
if(table.getItem(new Point(e.x, e.y)).getBounds(0).contains(new Point(e.x, e.y))){
//if((e.widget.getStyle()&32) == SWT.CHECK){
System.out.println("returned cause selected column 0, wich is checkbox column.");
return;
}//}
showFrame();
}
});
table.pack();
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!shell.getDisplay().readAndDispatch())
shell.getDisplay().sleep();
}
}
static void showFrame(){
final Shell dialog = new Shell(shell,SWT.BORDER|SWT.PRIMARY_MODAL|SWT.RESIZE);
dialog.setText("Test shell.. ");
dialog.setLayout(new GridLayout(3, true));
Label label = new Label(dialog,SWT.NONE);
label.setText("Row clicked: ");
Button ok = new Button(dialog, SWT.PUSH);
ok.setText("Close");
dialog.setDefaultButton(ok);
ok.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
ok.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
dialog.dispose();
}
});
dialog.pack();
dialog.open();
while (!dialog.isDisposed()) {
if (!dialog.getDisplay().readAndDispatch())
dialog.getDisplay().sleep();
}
}
}
Alright, found a solution.
The problem is, that there is no way (that I'm aware of) which will return the bounds of the checkbox. However, since the checkbox will always be the first thing in the table (if you use a Table with SWT.CHECK), you can simply check if the click event is to the left of the first cell.
I took the liberty to "optimize" some of your other code (my subjective opinion):
public static void main(String args[])
{
Display display = new Display();
final Shell shell = new Shell(display, SWT.BORDER | SWT.PRIMARY_MODAL | SWT.RESIZE);
shell.setText(" Test table ");
shell.setLayout(new GridLayout(1, true));
final Table table = new Table(shell, SWT.BORDER | SWT.CHECK | SWT.V_SCROLL | SWT.FULL_SELECTION);
table.setHeaderVisible(true);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
for(int col = 0; col < 5; col++)
{
new TableColumn(table, SWT.NONE).setText("column " + col);
}
for (int row = 0; row < 10; row++)
{
TableItem item = new TableItem(table, SWT.NONE);
for(int col = 1; col < table.getColumnCount(); col++)
{
item.setText(col, "cell " + row + " " + col);
}
}
for(int col = 0; col < table.getColumnCount(); col++)
{
table.getColumn(col).pack();
}
Button close = new Button(shell, SWT.PUSH);
close.setText("Done");
shell.setDefaultButton(close);
close.setLayoutData(new GridData(SWT.FILL, SWT.END, true, false));
close.addListener(SWT.Selection, new Listener()
{
#Override
public void handleEvent(Event e)
{
shell.dispose();
}
});
table.addListener(SWT.MouseUp, new Listener()
{
public void handleEvent(Event e)
{
if (table.getItemCount() > 0)
{
Rectangle rect = table.getItem(new Point(e.x, e.y)).getBounds(0);
if (rect.contains(new Point(e.x, e.y)) || e.x <= rect.x)
System.out.println("first column or checkbox clicked");
else
System.out.println("other column clicked");
}
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!shell.getDisplay().readAndDispatch())
shell.getDisplay().sleep();
}
}

SWT ExpandListener executes before collapse occurs on Linux

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.

Categories