SWT FileDialog error: constructor FileDialog is undefined - java

I'm just starting with Java basic and having this issue with SWT FileDialog. Eclipse always returns this error: The constructor FileDialog(Shell, int) is undefined
Below is the full code, could you please help to advise?
public class FormObject2 {
protected Shell shell;
private Text txtComboBoxItem;
private final FormToolkit formToolkit = new FormToolkit(Display.getDefault());
private Text taOne;
/**
* Launch the application.
* #param args
*/
public static void main(String[] args) {
try {
FormObject2 window = new FormObject2();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 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(481, 364);
shell.setText("SWT Application");
Menu menu = new Menu(shell, SWT.BAR);
shell.setMenuBar(menu);
MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE);
mntmFile.setText("File");
Menu menu_1 = new Menu(mntmFile);
mntmFile.setMenu(menu_1);
MenuItem mntmOpen = new MenuItem(menu_1, SWT.NONE);
mntmOpen.setAccelerator(1);
mntmOpen.setText("Open");
mntmOpen.setAccelerator(SWT.MOD1+ 'O');
MenuItem mntmSave = new MenuItem(menu_1, SWT.NONE);
mntmSave.setAccelerator(1);
mntmSave.setText("Save");
MenuItem mntmEdit = new MenuItem(menu, SWT.CASCADE);
mntmEdit.setText("Edit");
Menu menu_2 = new Menu(mntmEdit);
mntmEdit.setMenu(menu_2);
MenuItem mntmExit = new MenuItem(menu_2, SWT.NONE);
mntmExit.setText("Exit");
mntmOpen.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(shell, SWT.MULTI);
dialog.setFilterPath("C:\\Logs");
dialog.setFilterExtensions(new String[]{"*.txt", "*.pdf", "*.*"});
dialog.setFilterNames(new String[]{ "Rich Text Format", "HTML Document", "Any"});
dialog.open();
}
});
}

Your are probably importing the wrong FileDialog class - you need to be importing org.eclipse.swt.widgets.FileDialog not java.awt.FileDialog

Related

How to reopen a dialog programatically

I have a JFace dialog and a toggle button( whose text is either "freeze" or "unfreeze") in the button bar.
Initially i select an object and click on a menu item to open the dialog.
From then on, whenever I click on toggle button(when text on it is "unfreeze") the dialog should close and reopen.
How do i achieve this ?
This should give you an idea how to do it (quick hack):
private static MyDialog dialog;
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Button openDialog = new Button(shell, SWT.TOGGLE);
openDialog.setText("Toggle dialog");
openDialog.addListener(SWT.Selection, new Listener()
{
#Override
public void handleEvent(Event arg0)
{
if (openDialog.getSelection())
{
if (dialog == null)
{
dialog = new MyDialog(new Shell(display));
dialog.open();
}
if(dialog.getShell() != null && !dialog.getShell().isDisposed())
dialog.getShell().setVisible(openDialog.getSelection());
}
else
{
if (dialog != null && dialog.getShell() != null && !dialog.getShell().isDisposed())
dialog.getShell().setVisible(openDialog.getSelection());
}
}
});
shell.open();
shell.pack();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
private static class MyDialog extends Dialog
{
public MyDialog(Shell parentShell)
{
super(parentShell);
setShellStyle(SWT.CLOSE | SWT.MODELESS | SWT.BORDER | SWT.TITLE);
}
#Override
protected Control createDialogArea(Composite parent)
{
Composite container = (Composite) super.createDialogArea(parent);
Text text = new Text(container, SWT.BORDER);
return container;
}
#Override
protected void configureShell(Shell newShell)
{
super.configureShell(newShell);
newShell.setText("Some dialog");
}
#Override
protected Point getInitialSize()
{
return new Point(450, 300);
}
}
It will create and open the dialog on first press of the button and hide/unhide in on consequent press events (using Shell#setVisible(boolean)).
If this is not what you had in mind, please update your question or post a comment.

Show Page loading no browser until page is fully loaded

I want to hide the content of html page until its fully loaded. The idea is I want to get the content of html page do some processing and set the content back again. For doing so I am able to retrieve the text and do some processing on it. But the problem is , till the time processing is not complete, I want to hide the original html page and instead wanna show some dummy page.
I want to hover a shell on browser window and remove it when the loading is complete. I tried to hide the browser widget but that is not working as per the expectations.
Here is the snippet for the same.
package browserapp;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.extended.LocationEvent;
import org.eclipse.swt.browser.extended.LocationListener;
import org.eclipse.swt.browser.extended.ProgressEvent;
import org.eclipse.swt.browser.extended.ProgressListener;
import org.eclipse.swt.browser.extended.Browser;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class MyBrowser_1 {
/**
* Runs the application
*/
Display display = new Display();
protected boolean done;
public void run() {
final Shell shell = new Shell(display);
shell.setText("Simple Browser");
createContents(shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the main window's contents
*
* #param shell the main window
*/
private void createContents(final Shell shell) {
shell.setLayout(new FormLayout());
// Create the composite to hold the buttons and text field
Composite controls = new Composite(shell, SWT.NONE);
FormData data = new FormData();
data.top = new FormAttachment(0, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
controls.setLayoutData(data);
// Create the web browser
final Browser browser = new Browser(shell, SWT.NONE);
browser.addLocationListener(new LocationListener() {
#Override
public void changing(LocationEvent event) {
// TODO Auto-generated method stub
//browser.setVisible(false);
Image image = new Image(display,
"C:\\Documents and Settings\\My
Documents\\Pictures\\loadingAnimation.gif");
///shell.setBackgroundImage(image);
}
#Override
public void changed(LocationEvent event) {
// TODO Auto-generated method stub
}
});
browser.addProgressListener(new ProgressListener()
{
public void completed(ProgressEvent event)
{
}
public void changed(ProgressEvent event)
{
int progressWorked=0;
if (event.total == 0)
return;
done = (event.current == event.total);
int percentProgress = event.current * 100 / event.total;
System.out.println("Loading...");
if (done)
{
progressWorked = 0;
System.out.println("Loading completed...");
//browser.setVisible(true);
//maskPage(browser, maskedMap);
} else if (progressWorked == 0)
{
progressWorked = percentProgress;
} else
{
progressWorked = event.current;
}
}
});
data = new FormData();
data.top = new FormAttachment(controls);
data.bottom = new FormAttachment(100, 0);
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0);
browser.setLayoutData(data);
// Create the controls and wire them to the browser
controls.setLayout(new GridLayout(7, false));
// Create the back button
Button button = new Button(controls, SWT.PUSH);
button.setText("Back");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.back();
}
});
// Create the forward button
button = new Button(controls, SWT.PUSH);
button.setText("Forward");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.forward();
}
});
// Create the refresh button
button = new Button(controls, SWT.PUSH);
button.setText("Refresh");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.refresh();
}
});
// Create the stop button
button = new Button(controls, SWT.PUSH);
button.setText("Stop");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.stop();
}
});
// Create the address entry field and set focus to it
final Text url = new Text(controls, SWT.BORDER);
url.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
url.setText("https://netbanking.hdfcbank.com/netbanking/");
url.setFocus();
// Create the go button
button = new Button(controls, SWT.PUSH);
button.setText("Go");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
browser.setUrl(url.getText());
}
});
GridData gridData2 = new GridData(SWT.FILL, SWT.FILL, true, false);
Label status = new Label(controls, SWT.BORDER);
status.setLayoutData(gridData2);
// Allow users to hit enter to go to the typed URL
shell.setDefaultButton(button);
}
/**
* The application entry point
*
* #param args the command line arguments
*/
public static void main(String[] args) {
MyBrowser_1 browser=new MyBrowser_1();
browser.run();
}
}

How to show dots when the text exceeds the size of the Text?

When the content of a the Text exceeds the width of the Text, I want to show dots (...) at the end of the text field.
I have tried to using a ModifyListener without success. Any help regarding this would be much appreciated.
#Override
public void modifyText(ModifyEvent e) {
// TODO Auto-generated method stub
if (wakeupPatternText.getText().length()>=12) {
String wakeuppattern=wakeupPatternText.getText(0, 11);
String dot="...";
String wakeup=wakeuppattern+dot;
wakeupPatternText.setText(wakeup);
}
}
});
This should do what you want:
private static String textContent = "";
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout(SWT.VERTICAL));
Text text = new Text(shell, SWT.BORDER);
text.addListener(SWT.FocusOut, new Listener()
{
#Override
public void handleEvent(Event e)
{
Text text = (Text) e.widget;
textContent = text.getText();
text.setText(textContent.substring(0, Math.min(10, textContent.length())) + "...");
}
});
text.addListener(SWT.FocusIn, new Listener()
{
#Override
public void handleEvent(Event e)
{
Text text = (Text) e.widget;
text.setText(textContent);
}
});
Button button = new Button(shell, SWT.PUSH);
button.setText("Lose focus");
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
It listens to focus events and truncates the visible String if it is too long.
This is how it looks:
With focus:
Without focus:
The reason why your code isn't working is the following: When you call wakeupPatternText.setText(wakeup); from within the VerifyListener the listener itself is called again recursively.

Create a save/save as dialog box in java that save a newly created file or an edited file

Java Beginner: Please help been working on this for days and my brain is dead.
I have created a java program (in eclipse) that has 3 menu: FILE, EDIT, HELP
once file is clicked it display 4menuBar: 'new, open,save,save as & exit.
On the HELP menu there is a menuBar that says "About javaEdit" All my menu bars work except save, save as and the "About javaEdit" I need some code or a clear step by step explanation for dummy on how to have my save and save as working.
Save should save newly created file or edited file & finally i could like the "About JavaEdit to display a message like "thank you, this is java" once clicked. I could like something like
private void doSave(){code here}
and
private void doSaveAs (){
because I have those item in the if else if statement.
How to create a save/save as dialog box in java that save a newly created file or an edited file?
Below is my entire code:
import java.awt.*;
import java.awt.event
import java.io.*;
public class JavaEdit extends Frame implements ActionListener {
String clipBoard;
String fileName;
TextArea text;
MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem selectAllMI, cutMI, copyMI, deleteMI, pasteMI;
MenuItem aboutJavaEditMI;
/**
* Constructor
*/
public JavaEdit() {
super("JavaEdit"); // set frame title
setLayout(new BorderLayout()); // set layout
// create menu bar
MenuBar menubar = new MenuBar();
setMenuBar(menubar);
// create file menu
Menu fileMenu = new Menu("File");
menubar.add(fileMenu);
newMI = fileMenu.add(new MenuItem("New"));
newMI.addActionListener(this);
openMI = fileMenu.add(new MenuItem("Open"));
openMI.addActionListener(this);
fileMenu.addSeparator();
saveMI = fileMenu.add(new MenuItem("Save"));
saveAsMI = fileMenu.add(new MenuItem("Save As ..."));
fileMenu.addSeparator();
exitMI = fileMenu.add(new MenuItem("Exit"));
exitMI.addActionListener(this);
// create edit menu
Menu editMenu = new Menu("Edit");
menubar.add(editMenu);
selectAllMI = editMenu.add(new MenuItem("Select all"));
selectAllMI.addActionListener(this);
cutMI = editMenu.add(new MenuItem("Cut"));
cutMI.addActionListener(this);
copyMI = editMenu.add(new MenuItem("Copy"));
copyMI.addActionListener(this);
pasteMI = editMenu.add(new MenuItem("Paste"));
pasteMI.addActionListener(this);
deleteMI = editMenu.add(new MenuItem("Delete"));
deleteMI.addActionListener(this);
// create help menu
Menu helpMenu = new Menu("Help");
menubar.add(helpMenu);
aboutJavaEditMI = helpMenu.add(new MenuItem("About JavaEdit"));
aboutJavaEditMI.addActionListener(this);
// create text editing area
text = new TextArea();
add(text, BorderLayout.CENTER);
}
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == newMI) {
clearText();
fileName = null;
setTitle("JavaEdit"); // reset frame title
}
else if(source == openMI) {
doOpen();
}
else if(source == saveMI) {
doSave();
}
else if(source == saveAsMI){
doSaveAs();
}
else if(source == exitMI) {
System.exit(0);
}
else if(source == cutMI) {
doCopy();
doDelete();
}
else if(source == copyMI) {
doCopy();
}
else if(source == pasteMI) {
doPaste();
}
else if(source == deleteMI) {
doDelete();
}
}
/**
* method to specify and open a file
*/
private void doOpen() {
// display file selection dialog
FileDialog fDialog = new FileDialog(this, "Open ...", FileDialog.LOAD);
fDialog.setVisible(true);
// Get the file name chosen by the user
String name = fDialog.getFile();
// If user canceled file selection, return without doing anything.
if(name == null)
return;
fileName = fDialog.getDirectory() + name;
// Try to create a file reader from the chosen file.
FileReader reader=null;
try {
reader = new FileReader(fileName);
} catch (FileNotFoundException ex) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
"File Not Found: "+fileName);
dialog.setVisible(true);
return;
}
BufferedReader bReader = new BufferedReader(reader);
// Try to read from the file one line at a time.
StringBuffer textBuffer = new StringBuffer();
try {
String textLine = bReader.readLine();
while (textLine != null) {
textBuffer.append(textLine + '\n');
textLine = bReader.readLine();
}
bReader.close();
reader.close();
} catch (IOException ioe) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
"Error reading file: "+ioe.toString());
dialog.setVisible(true);
return;
}
setTitle("JavaEdit: " +name); // reset frame title
text.setText(textBuffer.toString());
}
/**
* method to clear text editing area
*/
private void clearText() {
text.setText("");
}
/**
* method to copy selected text to the clipBoard
*/
private void doCopy() {
clipBoard = new String(text.getSelectedText());
}
/**
* method to delete selected text
*/
private void doDelete() {
text.replaceRange("", text.getSelectionStart(), text.getSelectionEnd());
}
/**
* method to replace current selection with the contents of the clipBoard
*/
private void doPaste() {
if(clipBoard != null) {
text.replaceRange(clipBoard, text.getSelectionStart(),
text.getSelectionEnd());
}
}
/**
* class for message dialog
*/
class MessageDialog extends Dialog implements ActionListener {
private Label message;
private Button okButton;
// Constructor
public MessageDialog(Frame parent, String title, String messageString) {
super(parent, title, true);
setSize(400, 100);
setLocation(150, 150);
setLayout(new BorderLayout());
message = new Label(messageString, Label.CENTER);
add(message, BorderLayout.CENTER);
Panel panel = new Panel(new FlowLayout(FlowLayout.CENTER));
add(panel, BorderLayout.SOUTH);
okButton = new Button(" OK ");
okButton.addActionListener(this);
panel.add(okButton);
}
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
setVisible(false);
dispose();
}
}
/**
* the main method
*/
public static void main(String[] argv) {
// create frame
JavaEdit frame = new JavaEdit();
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(size.width-80, size.height-80);
frame.setLocation(20, 20);
// add window closing listener
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// show the frame
frame.setVisible(true);
}
}
Even an AWT program can use Action to encapsulate functionality and prevent (rather than suppress) leaking this in constructor. For example,
private static JavaEdit frame;
...
public JavaEdit() {
...
saveMI = fileMenu.add(new MenuItem("Save"));
saveMI.addActionListener(new SaveAction());
...
}
private static class SaveAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
FileDialog fDialog = new FileDialog(frame, "Save", FileDialog.SAVE);
fDialog.setVisible(true);
String path = fDialog.getDirectory() + fDialog.getFile();
File f = new File(path);
// f.createNewFile(); etc.
}
public static void main(String[] argv) {
// create frame
frame = new JavaEdit();
...
// show the frame
frame.pack();
frame.setVisible(true);
}
See HTMLDocumentEditor, cited here, for example implementations of related actions.

JFace dialog stays open after pressing the OK button

I am working with SWT JFace dialog.
I added a listener to the OK button, I want to display a message box once the user clicks on the OK button.
The problem in this step is that when I once click on the OK button the shell gets disposed. How I can prevent this behavior?
The following code will prevent the dialog from beeing closed via the "OK" button. Just don't call this.close() in the okPressed() method:
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new OptionsDialog(shell).open();
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private static class OptionsDialog extends Dialog {
private Composite composite;
public OptionsDialog(Shell parentShell)
{
super(parentShell);
setShellStyle(parentShell.getStyle() | SWT.CLOSE | SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL);
setBlockOnOpen(true);
}
protected Control createDialogArea(Composite parent) {
this.composite = (Composite) super.createDialogArea(parent);
GridLayout layout = new GridLayout(1, false);
layout.marginHeight = 5;
layout.marginWidth = 10;
composite.setLayout(layout);
createContent();
return composite;
}
private void createContent()
{
/* add your widgets */
}
protected void configureShell(Shell newShell)
{
super.configureShell(newShell);
newShell.setText("Shell name");
}
public void okPressed()
{
/* DO NOTHING HERE!!! */
//this.close();
}
}

Categories