disabling button from another button - java

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

Related

No items are displayed in the Palette in Eclipse oxygen

I am using Eclipse for RCP and RAP Developers (Oxygen). Upon opening palette it is empty. Even though I have my code in edit mode in the source tab.
In the below image palette is empty
As Suggested added the code below.
On opening the Design tab, the palette is empty.
package com.jcg.rca.main;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.widgets.Button;
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.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
//import org.eclipse.wb.swt.SWTResourceManager;
public class MainWindow {
protected Shell shlLogin;
private Text userNameTxt;
private Text passwordTxt;
private String userName = null;
private String password = null;
/**
* Launch the application.
*
* #param args
*/
public static void main(String[] args) {
try {
MainWindow window = new MainWindow();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shlLogin.open();
shlLogin.layout();
while (!shlLogin.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shlLogin = new Shell(SWT.CLOSE | SWT.TITLE | SWT.MIN);
shlLogin.setSize(450, 300);
shlLogin.setText("Login");
CLabel label = new CLabel(shlLogin, SWT.NONE);
//label.setImage(SWTResourceManager.getImage(MainWindow.class, "/com/jcg/rca/main/eclipse_logo.png"));
label.setBounds(176, 10, 106, 70);
label.setText("");
Label lblUsername = new Label(shlLogin, SWT.NONE);
lblUsername.setBounds(125, 115, 55, 15);
lblUsername.setText("Username");
Label lblPassword = new Label(shlLogin, SWT.NONE);
lblPassword.setBounds(125, 144, 55, 15);
lblPassword.setText("Password");
userNameTxt = new Text(shlLogin, SWT.BORDER);
userNameTxt.setBounds(206, 109, 173, 21);
passwordTxt = new Text(shlLogin, SWT.BORDER | SWT.PASSWORD);
passwordTxt.setBounds(206, 144, 173, 21);
Button btnLogin = new Button(shlLogin, SWT.NONE);
btnLogin.setBounds(206, 185, 75, 25);
btnLogin.setText("Login");
btnLogin.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
userName = userNameTxt.getText();
password = passwordTxt.getText();
if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
String errorMsg = null;
MessageBox messageBox = new MessageBox(shlLogin, SWT.OK | SWT.ICON_ERROR);
messageBox.setText("Alert");
if (userName == null || userName.isEmpty()) {
errorMsg = "Please enter username";
} else if (password == null || password.isEmpty()) {
errorMsg = "Please enter password";
}
if (errorMsg != null) {
messageBox.setMessage(errorMsg);
messageBox.open();
}
} else {
MessageBox messageBox = new MessageBox(shlLogin, SWT.OK | SWT.ICON_WORKING);
messageBox.setText("Info");
messageBox.setMessage("Valid");
messageBox.open();
}
}
});
}}
.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
JUST CREATE A SIMPLE JAVA PROJECT.
Then I used the Swing > JFrame for the class.
DONT create the project from the one under WindowsBuilder.
Right click on palette box
Then select restore default palette

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

how to restrict Joptionpane message dialog box prompting once for the Condition?

This is my code below that have to be generated in GUI form(Using Swing awt)
My code work is to read text files from a folder and get repeated words count and saving those selected files to a user specified folder.
if(tmp.isSelected()) {
String filepathNName = tf.getText() +"\\"+ tmp.getText();
//filepathNName = System.getProperty("path.separator");
String filename = tmp.getText();
System.out.println("filename = " + filename);
System.out.println("filepaname = " + filepathNName);
System.out.println("outputDir = " + outputDir);
boolean success = latestex1.exlCreator(filepathNName, outputDir, filename);
if(success) {
JOptionPane.showMessageDialog(null, "Successfully Completed. Pls refer to the path " + outputDir + " for output files");
} else {
JOptionPane.showMessageDialog(null, "OOPS. Some Error!!!");
}
In this code snippet The variable "success " does the file saving action by calling the properties from another program.
After saving saving several files say(100) My message dialog box should show the prompt only once.
But for each and every save file action it prompts again and again.
If I save 100 Files the message box appears 100 times.*(IF and else).
I need to make appear it only once after all saving the files.!
Any suggestions welcomed!
Thanks in advance.
full code below:
package latestprojectswing;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
public class latestswingpgm3 extends Thread implements ActionListener
{
JFrame frame;
JPanel panel;
JTextField tf,text,tf1;
JTextArea ta,text1;
JLabel lab1;
String str;
JScrollBar scrol;
JScrollPane scrollPane;
File fl;
private JCheckBox chckbxSelectAll;
private JCheckBox chckbxf1;
private JTextField textField;
private JLabel lblSourceFolderfiles;
private JButton btnChoosedirectoryfrom;
private JButton btnDisplay;
private JLabel lblListFilesBelow;
private JScrollPane jScrollPane1;
ArrayList<JCheckBox> aL = new ArrayList<JCheckBox>();
int selectedCounter = 0;
int y=100;
JPanel contentPane;
String outputDir;
latestswingpgm3()
{
frame = new JFrame( "Search box" );
frame.getContentPane().setLayout( null );
frame.setSize( 820, 700 );
panel = new JPanel();
panel.setBounds( 25, 90, 750, 400 );
//panel.setLayout(null);
//panel.setBounds( 25, 90, 750, 400 );
scrollPane = new JScrollPane( panel );
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//scrollPane.setBounds( 25, 90, 750, 300 );
scrollPane.setPreferredSize(new Dimension(500, 300));
//panel.setVisible(true);
scrollPane.setVisible(true);
frame.add(panel);
frame.add(scrollPane);
tf = new JTextField();
tf.setBounds( 25, 50, 750, 40 );
tf.setFont( new Font( "Latha", Font.BOLD, 20 ) );
tf.setHorizontalAlignment( JTextField.CENTER );
frame.getContentPane().add( tf );
chckbxSelectAll = new JCheckBox("Select All");
chckbxSelectAll.setBounds(25, 557, 97, 23);
frame.getContentPane().add(chckbxSelectAll);
chckbxSelectAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Iterator<JCheckBox> i = aL.iterator();
while(i.hasNext()) {
JCheckBox tmp = i.next();
if(chckbxSelectAll.isSelected()) {
tmp.doClick();
} else {
tmp.setSelected(false);
selectedCounter -= 1;
if(selectedCounter < 0) {
selectedCounter = 0;
}
textField.setText(Integer.toString(selectedCounter));
}
}
}
});
JButton btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Iterator<JCheckBox> i = aL.iterator();
while(i.hasNext()) {
JCheckBox tmp = i.next();
//scroll adder
jScrollPane1 = new JScrollPane(frame);
jScrollPane1.add(tmp);
jScrollPane1.revalidate();
if(tmp.isSelected()) {
String filepathNName = tf.getText() +"\\"+ tmp.getText();
//filepathNName = System.getProperty("path.separator");
String filename = tmp.getText();
System.out.println("filename = " + filename);
System.out.println("filepaname = " + filepathNName);
System.out.println("outputDir = " + outputDir);
boolean success = latestex1.exlCreator(filepathNName, outputDir, filename);
if(success) {
JOptionPane.showMessageDialog(null, "Successfully Completed. Pls refer to the path " + outputDir + " for output files");
} else {
JOptionPane.showMessageDialog(null, "OOPS. Some Error!!!");
}
}
}
}
});
btnGenerate.setBounds(316, 604, 89, 23);
frame.getContentPane().add(btnGenerate);
textField = new JTextField();
textField.setBounds(268, 558, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNoOfFiles = new JLabel("NO of Files Selected");
lblNoOfFiles.setBounds(141, 561, 139, 14);
frame.getContentPane().add(lblNoOfFiles);
JLabel lblDestinationFolderTo = new JLabel("Destination PathTo Generate Files");
lblDestinationFolderTo.setBounds(553, 561, 226, 14);
frame.getContentPane().add(lblDestinationFolderTo);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int returnVal = chooser.showOpenDialog(frame);
if(returnVal == JFileChooser.APPROVE_OPTION) {
str = chooser.getSelectedFile().getAbsolutePath();
}
if ( str != null && !str.trim().equals( "" ) )
{
tf1.setText( str );
outputDir = str;
// Enable the search button
//btnDisplay.setEnabled( true );
}
else
{
//btnDisplay.setEnabled( false );
}
}
});
btnBrowse.setBounds(553, 583, 89, 23);
frame.getContentPane().add(btnBrowse);
tf1 = new JTextField();
tf1.setBounds( 553, 620, 400, 30 );
tf1.setFont( new Font( "Latha", Font.BOLD, 20 ) );
frame.getContentPane().add( tf1 );
lblSourceFolderfiles = new JLabel("Source Folder/ Files");
lblSourceFolderfiles.setBounds(6, 17, 138, 14);
frame.getContentPane().add(lblSourceFolderfiles);
btnChoosedirectoryfrom = new JButton("ChooseDirectory From");
btnChoosedirectoryfrom.addActionListener(this);
btnChoosedirectoryfrom.setBounds(141, 9, 170, 30);
frame.getContentPane().add(btnChoosedirectoryfrom);
btnDisplay = new JButton("Select To Display");
btnDisplay.setEnabled(false);
btnDisplay.setBounds(534, 9, 180, 30);
btnDisplay.addActionListener( this );
frame.getContentPane().add(btnDisplay);
lblListFilesBelow = new JLabel("List files Below to choose ");
lblListFilesBelow.setBounds(344, 17, 180, 14);
frame.getContentPane().add(lblListFilesBelow);
frame.setVisible( true );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public void actionPerformed( ActionEvent ae )
{
if ( ae.getActionCommand().equals( "ChooseDirectory From" ) )
{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int returnVal = chooser.showOpenDialog(frame);
if(returnVal == JFileChooser.APPROVE_OPTION) {
str = chooser.getSelectedFile().getAbsolutePath();
}
if ( str != null && !str.trim().equals( "" ) )
{
tf.setText( str );
// Enable the search button
btnDisplay.setEnabled( true );
}
else
{
btnDisplay.setEnabled( false );
}
}
if ( ae.getActionCommand().equals( "Select To Display" ) )
{
if(aL!=null) {
Iterator<JCheckBox> i = aL.iterator();
while(i.hasNext()) {
panel.remove(i.next());
}
selectedCounter = 0;
textField.setText(Integer.toString(selectedCounter));
}
fl = new File( str );
File[] flist = fl.listFiles();
for ( int i = 0; i < flist.length; i++ )
{
if ( flist[i].isFile() )
{
final JCheckBox cb1 = new JCheckBox(flist[i].getName());
scrollPane.add(cb1);
panel.add(cb1);
cb1.setBounds(25, y, 200, 25);
cb1.setFont(new Font( "Latha", Font.BOLD, 20 ));
cb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if(cb1.isSelected()) {
selectedCounter += 1;
} else {
selectedCounter -= 1;
if(selectedCounter < 0) {
selectedCounter = 0;
}
}
textField.setText(Integer.toString(selectedCounter));
}
});
aL.add(cb1);
panel.add(cb1);
y+=30;
}
}
}
}
public static void main( String args[] )
{
new latestswingpgm3();
}
}
Change this
if(success) { JOptionPane.showMessageDialog(null, "Successfully Completed. Pls refer to the path " + outputDir + " for output files"); }else { JOptionPane.showMessageDialog(null, "OOPS. Some Error!!!"); }
To
if(success&&!once) { JOptionPane.showMessageDialog(null, "Successfully Completed. Pls refer to the path " + outputDir + " for output files");once=true; }else if(once! =true) { JOptionPane.showMessageDialog(null, "OOPS. Some Error!!!"); }
Declare once as boolean once=false outside if..
Edit
Since you posted the full source code.. Now it's clear.. You have to declare once variable outside the while loop..

SWT NullPointerException

I have a client and server. Server sends some questions to the Client. In client side I want to display these questions on a SWT application window.
I use one thread to show the window and main thread contacts with the Server. After client receives the questions, NullPointerException is thrown in text widget. (writeQuestions method below). I think "q1Txt" is not null because it is initiated in "createContets" method. Besides the arraylist that have question is not null too because I checked it.
Can you help me about it?
My code is below.
public class Client {
protected static Shell shell;
private static Text q1txt;
private static Text q2txt;
private static Text q3txt;
private static Text q4txt;
private static Text q5txt;
private static Text ans1txt;
private static Text ans2txt;
private static Text ans3txt;
private static Button ans5YesBtn;
private static Button ans4NoBtn;
private static Button ans4YesBtn;
private static Button ans5NoBtn;
private static ArrayList<Integer> ansList = new ArrayList<Integer>();
private static boolean isAnswered = false;
static String name;
static int socketNum;
static Socket socket;
public static int l = 4;
public static void main(String[] args) throws InterruptedException {
new Screen().start();
try {
socket = new Socket("", 9898);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeObject("8080");
ArrayList<String> questions = (ArrayList<String>) objIn.readObject();
writeQuestions(questions);
while(!isAnswered)
Thread.sleep(2000);
socket.close();
} catch (UnknownHostException e) {
System.err.println("There is not like this company!");
} catch (IOException e) {
System.err.println("Company does not answer!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void writeQuestions(ArrayList<String> questions){
q1txt.setText(questions.get(0)); // The exception point is here
q2txt.setText(questions.get(1));
q3txt.setText(questions.get(2));
q4txt.setText(questions.get(3));
q5txt.setText(questions.get(4));
}
private static class Screen extends Thread {
public void run() {
open();
}
}
public static void open(){
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
protected static void createContents() {
shell = new Shell();
shell.setSize(499, 369);
shell.setText("SWT Application");
shell.setLayout(null);
Composite questionsComp = new Composite(shell, SWT.NONE);
questionsComp.setBounds(10, 10, 373, 298);
q1txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q1txt.setBounds(0, 0, 259, 21);
q2txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q2txt.setBounds(0, 51, 259, 21);
q3txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q3txt.setBounds(0, 95, 259, 21);
q4txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q4txt.setBounds(0, 140, 259, 21);
q5txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q5txt.setBounds(0, 189, 259, 21);
ans1txt = new Text(questionsComp, SWT.BORDER);
ans1txt.setBounds(272, 0, 58, 21);
ans2txt = new Text(questionsComp, SWT.BORDER);
ans2txt.setBounds(272, 51, 58, 21);
ans3txt = new Text(questionsComp, SWT.BORDER);
ans3txt.setBounds(272, 95, 58, 21);
Group ans4group = new Group(questionsComp, SWT.NONE);
ans4group.setBounds(265, 121, 97, 47);
ans4group.setLayout(null);
ans4YesBtn = new Button(ans4group, SWT.RADIO);
ans4YesBtn.setBounds(10, 20, 39, 16);
ans4YesBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4YesBtn.setText("Yes");
ans4NoBtn = new Button(ans4group, SWT.RADIO);
ans4NoBtn.setBounds(55, 20, 39, 16);
ans4NoBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4NoBtn.setText("No");
Group ans5Group = new Group(questionsComp, SWT.NONE);
ans5Group.setBounds(265, 176, 97, 47);
ans5NoBtn = new Button(ans5Group, SWT.RADIO);
ans5NoBtn.setBounds(55, 21, 39, 16);
ans5NoBtn.setText("No");
ans5YesBtn = new Button(ans5Group, SWT.RADIO);
ans5YesBtn.setBounds(10, 21, 39, 16);
ans5YesBtn.setText("Yes");
Button btnGainCalculation = new Button(questionsComp, SWT.NONE);
btnGainCalculation.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//controls all answers
if(ans1txt.getText().equals("") || ans2txt.getText().equals("") || ans3txt.getText().equals("")){
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
}else if((!ans4NoBtn.getSelection() && !ans4YesBtn.getSelection()) || (!ans5NoBtn.getSelection() && !ans5YesBtn.getSelection())){
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
}else if(!isNumeric(ans1txt.getText()) || !isNumeric(ans2txt.getText()) || !isNumeric(ans3txt.getText()) ){
MessageDialog.openWarning(shell, "Warning", "Please answer correctly.");
}else
isAnswered = true;
}
}
);
btnGainCalculation.setBounds(0, 236, 97, 25);
btnGainCalculation.setText("Gain Calculation");
}
public static boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
}
I'm pretty sure the problem is the later execution for the "createContent".
We need to ensure that component will use after it creation
Try this:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.eclipse.jface.dialogs.MessageDialog;
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.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Client{
protected static Shell shell;
private static Text q1txt;
private static Text q2txt;
private static Text q3txt;
private static Text q4txt;
private static Text q5txt;
private static Text ans1txt;
private static Text ans2txt;
private static Text ans3txt;
private static Button ans5YesBtn;
private static Button ans4NoBtn;
private static Button ans4YesBtn;
private static Button ans5NoBtn;
private static ArrayList<Integer> ansList = new ArrayList<Integer>();
private static boolean isAnswered = false;
static String name;
static int socketNum;
static Socket socket;
public static int l = 4;
public static void main(String[] args) throws InterruptedException {
Screen screen = new Screen();
screen.setCreationComplete(new CreationCompleteAction());
}
private static class Screen extends Thread {
Runnable creationCompleteAction;
public void setCreationComplete(Runnable action){
this.creationCompleteAction = action;
}
public void run() {
Display display = Display.getDefault();
createContents();
if(creationCompleteAction != null){
creationCompleteAction.run();
}
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
public static class CreationCompleteAction implements Runnable {
#Override
public void run() {
try {
socket = new Socket("", 9898);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
objOut.writeObject("8080");
ArrayList<String> questions = (ArrayList<String>) objIn.readObject();
writeQuestions(questions);
while (!isAnswered)
Thread.sleep(2000);
socket.close();
} catch (UnknownHostException e) {
System.err.println("There is not like this company!");
} catch (IOException e) {
System.err.println("Company does not answer!");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void writeQuestions(ArrayList<String> questions) {
q1txt.setText(questions.get(0)); // The exception point is here
q2txt.setText(questions.get(1));
q3txt.setText(questions.get(2));
q4txt.setText(questions.get(3));
q5txt.setText(questions.get(4));
}
private static class Screen extends Thread {
public void run() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
protected static void createContents() {
shell = new Shell();
shell.setSize(499, 369);
shell.setText("SWT Application");
shell.setLayout(null);
Composite questionsComp = new Composite(shell, SWT.NONE);
questionsComp.setBounds(10, 10, 373, 298);
q1txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q1txt.setBounds(0, 0, 259, 21);
q2txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q2txt.setBounds(0, 51, 259, 21);
q3txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q3txt.setBounds(0, 95, 259, 21);
q4txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q4txt.setBounds(0, 140, 259, 21);
q5txt = new Text(questionsComp, SWT.BORDER | SWT.READ_ONLY);
q5txt.setBounds(0, 189, 259, 21);
ans1txt = new Text(questionsComp, SWT.BORDER);
ans1txt.setBounds(272, 0, 58, 21);
ans2txt = new Text(questionsComp, SWT.BORDER);
ans2txt.setBounds(272, 51, 58, 21);
ans3txt = new Text(questionsComp, SWT.BORDER);
ans3txt.setBounds(272, 95, 58, 21);
Group ans4group = new Group(questionsComp, SWT.NONE);
ans4group.setBounds(265, 121, 97, 47);
ans4group.setLayout(null);
ans4YesBtn = new Button(ans4group, SWT.RADIO);
ans4YesBtn.setBounds(10, 20, 39, 16);
ans4YesBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4YesBtn.setText("Yes");
ans4NoBtn = new Button(ans4group, SWT.RADIO);
ans4NoBtn.setBounds(55, 20, 39, 16);
ans4NoBtn.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
ans4NoBtn.setText("No");
Group ans5Group = new Group(questionsComp, SWT.NONE);
ans5Group.setBounds(265, 176, 97, 47);
ans5NoBtn = new Button(ans5Group, SWT.RADIO);
ans5NoBtn.setBounds(55, 21, 39, 16);
ans5NoBtn.setText("No");
ans5YesBtn = new Button(ans5Group, SWT.RADIO);
ans5YesBtn.setBounds(10, 21, 39, 16);
ans5YesBtn.setText("Yes");
Button btnGainCalculation = new Button(questionsComp, SWT.NONE);
btnGainCalculation.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
//controls all answers
if (ans1txt.getText().equals("") || ans2txt.getText().equals("") || ans3txt.getText().equals("")) {
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
} else if ((!ans4NoBtn.getSelection() && !ans4YesBtn.getSelection()) || (!ans5NoBtn.getSelection() && !ans5YesBtn.getSelection())) {
MessageDialog.openWarning(shell, "Warning", "Please answer all questions.");
} else if (!isNumeric(ans1txt.getText()) || !isNumeric(ans2txt.getText()) || !isNumeric(ans3txt.getText())) {
MessageDialog.openWarning(shell, "Warning", "Please answer correctly.");
} else
isAnswered = true;
}
});
btnGainCalculation.setBounds(0, 236, 97, 25);
btnGainCalculation.setText("Gain Calculation");
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); //match a number with optional '-' and decimal.
}
}

FileDialog and Composite

I am trying to create a browse button with FileDialog and composite in Java SWT. (Composite because, I am use CTabFolder and CTabItem. I felt to add components to CTabItem composite is good enough)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.custom.CBanner;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.wb.swt.SWTResourceManager;
public class DemoShell extends Shell {
protected Composite composite;
private Text filename;
private Table table;
protected Shell shell;
public static void main(String args[]) {
try {
Display display = Display.getDefault();
DemoShell shell = new DemoShell(display);
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean parseFile(Table table, String filename) {
try {
BufferedReader br = new BufferedReader( new FileReader(filename) );
String line = "";
StringTokenizer token = null, subtoken = null;
int tokenNum = 1;
while((line = br.readLine()) != null) {
// lineNum++;
// break comma separated file line by line
token = new StringTokenizer(line, ";");
String sno = null;
while(token.hasMoreTokens()) {
subtoken = new StringTokenizer(token.nextToken().toString(), ",");
sno = "";
sno = Integer.toString(tokenNum);
TableItem item = new TableItem (table, SWT.NONE);
item.setText (0, sno );
item.setText (1, subtoken.nextToken());
item.setText (2, subtoken.nextToken());
item.setText (3, subtoken.nextToken());
item.setText (4, subtoken.nextToken());
item.setText (5, subtoken.nextToken());
tokenNum++;
System.out.println("S.No # " + tokenNum + token.nextToken());
}
tokenNum = 0;
}
br.close();
return true;
} catch(Exception e) {
System.err.println("Parse Error: " + e.getMessage());
return false;
}
}
public void displayFiles(String[] files) {
for (int i = 0; files != null && i < files.length; i++) {
filename.setText(files[i]);
filename.setEditable(false);
}
}
/**
* Create the shell.
* #param display
*/
public DemoShell(Display display) {
super(display, SWT.SHELL_TRIM);
TabFolder tabFolder = new TabFolder(this, SWT.NONE);
tabFolder.setBounds(10, 10, 462, 268);
TabItem re_item = new TabItem(tabFolder, SWT.NONE);
re_item.setText("Road Network");
TabItem ttable_item = new TabItem(tabFolder, SWT.NONE);
ttable_item.setText("Time Table");
createContents_tt(tabFolder, ttable_item );
}
/**
* Create contents of the shell.
*/
protected void createContents_tt(TabFolder tabFolder, TabItem ttable_item) {
setText("SWT Application");
setSize(530, 326);
//Table declaration
table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
table.setBounds(10, 153, 450, 107);
table.setHeaderVisible(true);
table.setLinesVisible(true);
String[] titles = {"S.No", "Route", "Transport #", "Cross Point", "Start Time", "End Time"};
for (int i=0; i<titles.length; i++) {
TableColumn column = new TableColumn (table, SWT.NONE);
column.setText (titles [i]);
}
for (int i=0; i<titles.length; i++) {
table.getColumn (i).pack ();
}
Composite composite = new Composite(tabFolder, SWT.NONE);
composite.setLayout(new FillLayout());
Group group_1 = new Group(shell, SWT.NONE);
group_1.setBounds(10, 10, 450, 127);
filename = new Text(group_1, SWT.BORDER);
filename.setBounds(31, 95, 377, 21);
filename.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
Group group = new Group(group_1, SWT.NONE);
group.setBounds(81, 46, 245, 43);
Label lblEitherBrowseFor = new Label(group_1, SWT.NONE);
lblEitherBrowseFor.setBounds(10, 19, 430, 21);
lblEitherBrowseFor.setText("Either Browse for a file or Try to upload the time table data through Manual entry");
Button btnManual = new Button(group, SWT.NONE);
btnManual.setBounds(162, 10, 75, 25);
btnManual.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
}
});
btnManual.setText("Manual");
Button btnBrowser = new Button(group, SWT.NONE);
btnBrowser.setBounds(27, 10, 75, 25);
btnBrowser.setText("Browse");
btnBrowser.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(composite, SWT.NULL);
String path = dialog.open();
if (path != null) {
File file = new File(path);
if (file.isFile())
{
displayFiles(new String[] { file.getAbsolutePath().toString()});
DemoShell.parseFile(table, file.toString());
}
else
displayFiles(file.list());
}
}
});
ttable_item.setControl(composite);
}
#Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
}
I am getting the following error when trying to add in the above manner.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor FileDialog(Composite, int) is undefined
Cannot refer to a non-final variable composite inside an inner class defined in a different method
I request for suggestions/help to clear the bug or re-do with any other way.
You are trying to access composite from within the Listener you define (SelectionAdapter). The notation you use to create the listener implicitly creates a new class. So you are effectively trying to access the variable composite from an inner class, which can only be done if composite is a static field of your outer class or if you make the composite final.
So just do the following:
final Composite composite = new Composite(tabFolder, SWT.NONE);
and it will work.
Moreover, as the error states, there is no constructor that takes a Composite. You have to use a Shell. So just do the following:
FileDialog dialog = new FileDialog(composite.getShell(), SWT.NULL);
This however will give you another exception, since you use the field shell somewhere above that line which is null. Since your class is a Shell, replace all occurences of shell with this and it will work.

Categories