I'm working on a project for my Java class, we just have to modify code. I had to add a Save and Save As dialog box to a basic text file document. When I do Save As the first time its fine, but then do save as again but hit cancel it resets the file to null. I have made it so at least the title still stays but when you hit the Save button it acts like its a null file and save as dialog box appears again. I want it so when you cancel Save As, it keeps the previous file instead of going back to null. I'm still formatting it, so its funky
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 selectAll, cutMI, copyMI, deleteMI, pasteMI;
MenuItem about;
/**
* 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"));
saveMI.addActionListener(this);
saveAsMI = fileMenu.add(new MenuItem("Save As ..."));
saveAsMI.addActionListener(this);
fileMenu.addSeparator();
exitMI = fileMenu.add(new MenuItem("Exit"));
exitMI.addActionListener(this);
// create edit menu
Menu editMenu = new Menu("Edit");
menubar.add(editMenu);
selectAll = editMenu.add(new MenuItem("Select All"));
selectAll.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);
Menu helpMenu = new Menu("Help");
menubar.add(helpMenu);
about = helpMenu.add(new MenuItem("About"));
about.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 == saveAsMI) {
doSaveAs();
}
else if (source == saveMI) {
doSave();
}
else if(source == exitMI) {
System.exit(0);
}
else if(source == selectAll) {
doSelect();
}
else if(source == cutMI) {
doCopy();
doDelete();
}
else if(source == copyMI) {
doCopy();
}
else if(source == pasteMI) {
doPaste();
}
else if(source == deleteMI) {
doDelete();
}
else if(source == about){
MessageDialog dialog = new MessageDialog(this, "About",
"JavaEdit in Java, Version 2.0, 2017");
dialog.setVisible(true);
return;
}
}
/**
* 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());
}
private void doSaveAs() {
FileDialog fDialog = new FileDialog(this, "Save As ...", FileDialog.SAVE);
fDialog.setVisible(true);
fileName = fDialog.getFile();
String name = fileName.toString();
setTitle("JavaEdit: " + name); // reset frame title
fDialog.setFile(name);
FileWriter fileCharStream = null; // File stream for writing file
try {
fileCharStream = new FileWriter(fileName); // May throw IOException
// Use file output stream
fileCharStream.write(text.getText());
} catch (IOException excpt) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
fileName);
dialog.setVisible(true);
return;
} finally {
closeFileWriter(fileCharStream); // Ensure file is closed!
}
}
private void doSave() {
if(fileName == null )
{
doSaveAs();
}
FileWriter out = null;
try {
out =new FileWriter(fileName);
out.write(text.getText());
}
catch (IOException excpt) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
fileName);
dialog.setVisible(true);
return;
} finally {
closeFileWriter(out); // Ensure file is closed!
}// Ensure file is closed!
}
static void closeFileWriter(FileWriter fileName) {
try {
if (fileName != null) { // Ensure "file" references a valid object
fileName.close(); // close() may throw IOException if fails
}
} catch (IOException closeExcpt) {
closeExcpt.getMessage();
}
return;
}
private void doSelect() {
text.selectAll();
}
/**
* 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);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
}
});
}
// 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);
}
}
Simply check if the returned file is null:
String name = fDialog.getFile();
// if Cancel is pressed we just exit
if (name == null) {
return;
}
// otherwise we save it
fileName = name;
...
Related
I am working on a text editor in Java as a fun side project. When I exported the project, I converted to executable JAR file to ".exe" so that I could set the text editor as the default program to open ".txt" files. I can run the ".exe" and write text and then save the file, and the file saves, but the contents of the file are not saved when I try to open the file with the text editor; however, I can open the same file with notepad, and the contents of the file show. The file saves fine in Eclipse. What do I need to fix so that the file contents are shown when I try to open them with my text editor?
Here is my code:
public class Open extends JFrame implements KeyListener {
JPanel panel = new JPanel();
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
JMenuBar menuBar = new JMenuBar();
JMenu menu;
JMenuItem item;
Font systemFont;
public Open() {
systemFont = new Font("Times New Roman", Font.PLAIN, 20);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(false);
textArea.setFont(systemFont);
panel.setLayout(new BorderLayout());
panel.add(scrollPane);
add(panel);
menu = new JMenu("File");
item = new JMenuItem("Save As");
item.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
menu.add(item);
menuBar.add(menu);
menu = new JMenu("Edit");
item = new JMenuItem("Undo");
menu.add(item);
menu.add(item);
menuBar.add(menu);
add("North", menuBar);
setLookAndFeel();
frameDetails("Text Editor");
}
public void frameDetails(String title) {
setSize(700, 500);
setLocationRelativeTo(null);
setTitle(title);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void setLookAndFeel() {
try {
UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Open editor = new Open();
}
}
Here is the bit of code with the save button:
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser JFC = new JFileChooser();
File fileName = new File("");
BufferedWriter writer = null;
try {
int rVal = JFC.showSaveDialog(Open.this);
if(rVal == JFileChooser.APPROVE_OPTION) {
writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
writer.write(textArea.getText());
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
});
You are never reading the text file. In order to do that, Use something like this
public void loadFile(JTextArea area, String path, String file)
{
try
{
area.read(new FileReader(path + file), "Default");
}
catch(IOException e)
{
e.printStackTrace();
}
}
Note: You don't have to have this in a method. You could just use the try - catch code
To act as a default text editor, your program needs to accept a file name as the argument to main (String[] args). It should verify the file exists, then open it, read its contents, and close it.
Also, when you save a file you should rename the former version to "name.bak" or "name~" before overwriting it with the new version, in case something goes wrong during the save.
My java Web Browser app doesn't show the web pages from Internet like:
http://www.google.com
when entering the correct url and finally it shows the exception provided as
Unable to load page
What is the problem inside my application code?
please help me to find out and fix the problem.
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*;
// The Mini Web Browser.
public class MiniBrowser extends JFrame
implements HyperlinkListener
{
// These are the buttons for iterating through the page list.
private JButton backButton, forwardButton;
// Page location text field.
private JTextField locationTextField;
// Editor pane for displaying pages.
private JEditorPane displayEditorPane;
// Browser's list of pages that have been visited.
private ArrayList pageList = new ArrayList();
// Constructor for Mini Web Browser.
public MiniBrowser()
{
// Set application title.
super("Mini Browser");
// Set window size.
setSize(640, 480);
// Handle closing events.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
actionExit();
}
});
// Set up file menu.
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem fileExitMenuItem = new JMenuItem("Exit",
KeyEvent.VK_X);
fileExitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionExit();
}
});
fileMenu.add(fileExitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Set up button panel.
JPanel buttonPanel = new JPanel();
backButton = new JButton("< Back");
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionBack();
}
});
backButton.setEnabled(false);
buttonPanel.add(backButton);
forwardButton = new JButton("Forward >");
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionForward();
}
});
forwardButton.setEnabled(false);
buttonPanel.add(forwardButton);
locationTextField = new JTextField(35);
locationTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
actionGo();
}
}
});
buttonPanel.add(locationTextField);
JButton goButton = new JButton("GO");
goButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionGo();
}
});
buttonPanel.add(goButton);
// Set up page display.
displayEditorPane = new JEditorPane();
displayEditorPane.setContentType("text/html");
displayEditorPane.setEditable(false);
displayEditorPane.addHyperlinkListener(this);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(buttonPanel, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(displayEditorPane),
BorderLayout.CENTER);
}
// Exit this program.
private void actionExit() {
System.exit(0);
}
// Go back to the page viewed before the current page.
private void actionBack() {
URL currentUrl = displayEditorPane.getPage();
int pageIndex = pageList.indexOf(currentUrl.toString());
try {
showPage(
new URL((String) pageList.get(pageIndex - 1)), false);
}
catch (Exception e) {}
}
// Go forward to the page viewed after the current page.
private void actionForward() {
URL currentUrl = displayEditorPane.getPage();
int pageIndex = pageList.indexOf(currentUrl.toString());
try {
showPage(
new URL((String) pageList.get(pageIndex + 1)), false);
}
catch (Exception e) {}
}
// Load and show the page specified in the location text field.
private void actionGo() {
URL verifiedUrl = verifyUrl(locationTextField.getText());
if (verifiedUrl != null) {
showPage(verifiedUrl, true);
} else {
showError("Invalid URL");
}
}
// Show dialog box with error message.
private void showError(String errorMessage) {
JOptionPane.showMessageDialog(this, errorMessage,
"Error", JOptionPane.ERROR_MESSAGE);
}
// Verify URL format.
private URL verifyUrl(String url) {
// Only allow HTTP URLs.
if (!url.toLowerCase().startsWith("http://"))
return null;
// Verify format of URL.
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (Exception e) {
return null;
}
return verifiedUrl;
}
/* Show the specified page and add it to
the page list if specified. */
private void showPage(URL pageUrl, boolean addToList)
{
// Show hour glass cursor while crawling is under way.
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
// Get URL of page currently being displayed.
URL currentUrl = displayEditorPane.getPage();
// Load and display specified page.
displayEditorPane.setPage(pageUrl);
// Get URL of new page being displayed.
URL newUrl = displayEditorPane.getPage();
// Add page to list if specified.
if (addToList) {
int listSize = pageList.size();
if (listSize > 0) {
int pageIndex =
pageList.indexOf(currentUrl.toString());
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
}
pageList.add(newUrl.toString());
}
// Update location text field with URL of current page.
locationTextField.setText(newUrl.toString());
// Update buttons based on the page being displayed.
updateButtons();
}
catch (Exception e)
{
// Show error messsage.
showError("Unable to load page");
}
finally
{
// Return to default cursor.
setCursor(Cursor.getDefaultCursor());
}
}
/* Update back and forward buttons based on
the page being displayed. */
private void updateButtons() {
if (pageList.size() < 2) {
backButton.setEnabled(false);
forwardButton.setEnabled(false);
} else {
URL currentUrl = displayEditorPane.getPage();
int pageIndex = pageList.indexOf(currentUrl.toString());
backButton.setEnabled(pageIndex > 0);
forwardButton.setEnabled(
pageIndex < (pageList.size() - 1));
}
}
// Handle hyperlink's being clicked.
public void hyperlinkUpdate(HyperlinkEvent event) {
HyperlinkEvent.EventType eventType = event.getEventType();
if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
if (event instanceof HTMLFrameHyperlinkEvent) {
HTMLFrameHyperlinkEvent linkEvent =
(HTMLFrameHyperlinkEvent) event;
HTMLDocument document =
(HTMLDocument) displayEditorPane.getDocument();
document.processHTMLFrameHyperlinkEvent(linkEvent);
} else {
showPage(event.getURL(), true);
}
}
}
// Run the Mini Browser.
public static void main(String[] args) {
MiniBrowser browser = new MiniBrowser();
browser.show();
}
}
It appears that showPage() gets called before a url is entered which causes a NullPointerException to get thrown. So you may want to change when/how showPage() gets called and/or add some additional null checks to showPage(). Just doing the null checks should do the trick:
private void showPage(URL pageUrl, boolean addToList) {
// Show hour glass cursor while crawling is under way.
if (pageUrl == null) {
return;
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
// Get URL of page currently being displayed.
URL currentUrl = displayEditorPane.getPage();
// Load and display specified page.
displayEditorPane.setPage(pageUrl);
// Get URL of new page being displayed.
URL newUrl = displayEditorPane.getPage();
// Add page to list if specified.
if (newUrl != null && addToList) {
int listSize = pageList.size();
if (listSize > 0) {
int pageIndex = pageList.indexOf(currentUrl.toString());
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
}
pageList.add(newUrl.toString());
}
// Update location text field with URL of current page.
if (newUrl != null) {
locationTextField.setText(newUrl.toString());
}
// Update buttons based on the page being displayed.
updateButtons();
} catch (Exception e) {
// Show error messsage.
e.printStackTrace();
showError("Unable to load page");
} finally {
// Return to default cursor.
setCursor(Cursor.getDefaultCursor());
}
}
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.
am writing a swing application that uses JTabbedpane.
Can open a log file in a tab and 'parse it' as required to another tab.
Am having trouble though saving the parsed content to a text file.
Each tab consists of a JTextarea within a JPanel.
<pre>
private void setContentsOfParsedLogFile(JPanel content) {
JTextArea textArea = new JTextArea();
addContentsToTextArea(textArea);
content.add(new JScrollPane(textArea));
content.setLayout(new GridLayout(1, 1));
pane.addTab(parsedTabName(), content);
}
private void addContentsToTextArea(JTextArea textArea) {
if (!parsedFileAlreadyOpen()) {
PortLogParser lp = new PortLogParser();
lp.parseLogFile(new File(activeTabFullName));
ArrayList<String> sb = lp.getParsedMsg();
for (String s : sb) {
textArea.append(s + System.getProperty("line.separator"));
}
}
}
</pre>
Was hoping I could get the text using:
String text = ((JTextArea) pane.getSelectedComponent()).getText();
within actionPerformed:
<pre>
private void createSaveFileMenuItem() {
saveLogFile = new JMenuItem("Save Log File");
saveLogFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.ALT_MASK));
saveLogFile.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
saveContentOfActiveTab();
}
});
}
private void saveContentOfActiveTab() {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
saveContentsToFile(file);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private void saveContentsToFile(File file) throws IOException {
createNewFileIfItDoesntExist(file);
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
//System.out.println(pane.getSelectedIndex());
//System.out.println(pane.getSelectedComponent());
/*
TODO
the component is the container JPanel. How do I select the textarea and it's content??
*/
// String text = ((JTextArea) pane.getSelectedComponent()).getText();
// bw.write(text);
bw.close();
}
private void createNewFileIfItDoesntExist(File file) throws IOException {
if (!file.exists()) {
file.createNewFile();
}
}
</pre>
but the Selected Component is the JPanel.
Is there a way to select the text within the textarea contained in the JPanel?
I haven't uniquely identified each textarea so that may be a problem?
One way to do this is to create a subclass of JPanel with an associated JTextArea:
class LogTextPanel extends JPanel {
private final JTextArea textArea;
public LogTextPanel() {
super(new GridLayout(1, 1));
textArea = new JTextArea();
add(new JScrollPane(textArea));
}
public void append(String text) {
textArea.append(text);
}
public String getText() {
return textArea.getText();
}
}
You can then retrieve the text from the selected panel using:
String text = ((LogTextPanel)pane.getSelectedComponent()).getText();
I am using this mmscomputing library as java applet to scan an image or document.
Using swings,awt i created one scan button which is acquiring scanner by calling scanner.acquire() method of mmscomputing jar..
and then placing that scanned image into jpanel for displaying.
Problem is, first time when i start my applet and hitting my scan button..scanning works fine..Twain states it goes into are: 3,4,5,6,7,5,4,3
then second time,hitting my scan button again ..
Twain states it goes into are: 3,4,5,4,3
It's not going into image transfer ready and transferring state and thus not into below CODE IF loop
if (type.equals(ScannerIOMetadata.ACQUIRED))
so i am not able to see the new scanned image into my jpanel second time...
then third time, hitting my scan button .. again it works fine.. getting into all states.
So i mean, For alternatively turns or restarting the java applet again ..it works.
what would be the issue.. ?
I want, every time when i hit scan button it should get me a new image into Jpanel.. but it's doing alternative times.
can i forcefully explicitly set or change twain states to come into 6th and 7th states..
or is there some twain source initialisation problem occurs second time?
because restarting applet is doing fine every time.. or some way to reinitialise applet objects everytime on clicking scan button..as it would feel like I am restarting applet everytime on clicking scan button...
I am not getting it..
Below is the sample code:
import uk.co.mmscomputing.device.twain.TwainConstants;
import uk.co.mmscomputing.device.twain.TwainIOMetadata;
import uk.co.mmscomputing.device.twain.TwainSource;
import uk.co.mmscomputing.device.twain.TwainSourceManager;
public class XXCrop extends JApplet implements PlugIn, ScannerListener
{
private JToolBar jtoolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);
ImagePanel ipanel;
Image im =null;
BufferedImage imageforCrop;
ImagePlus imp=null;
int imageWidth;
int imageHeight;
private static final long serialVersionUID = 1L;
Container content = null;
private JPanel jContentPane = null;
private JButton jButton = null;
private JButton jButton1 = null;
JCheckBox clipBox = null;
JPanel crpdpanel=null;
JPanel cpanel=null;
private Scanner scanner=null;
private TwainSource ts ;
private boolean is20;
ImagePanel imagePanel,imagePanel2 ;
public static void main(String[] args) {
new XXCrop().setVisible(true);
}
public void run(String arg0) {
new XXCrop().setVisible(false);
repaint();
}
/**
* This is the default constructor
*/
public XXCrop() {
super();
init();
try {
scanner = Scanner.getDevice();
if(scanner!=null)
{
scanner.addListener(this);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* This method initializes this
*
* #return void
*/
public void init()
{
this.setSize(1200, 600);
this.setLayout(null);
//this.revalidate();
this.setContentPane(getJContentPane());
}
private JToolBar getJToolBar()
{
jtoolbar.add(getJButton1());
jtoolbar.add(getJButton());
jtoolbar.setName("My Toolbar");
jtoolbar.addSeparator();
Rectangle r=new Rectangle(0, 0,1024, 30 );
jtoolbar.setBounds(r);
return jtoolbar;
}
private JPanel getJContentPane()
{
if (jContentPane == null)
{
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJToolBar());
}
return jContentPane;
}
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setBounds(new Rectangle(4, 16, 131, 42));
jButton.setText("Select Device");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (scanner.isBusy() == false) {
selectDevice();
}
}
});
}
return jButton;
}
/* Select the twain source! */
public void selectDevice() {
try {
scanner.select();
} catch (ScannerIOException e1) {
IJ.error(e1.toString());
}
}
private JButton getJButton1()
{
if (jButton1 == null) {
jButton1 = new JButton();
jButton1.setBounds(new Rectangle(35,0, 30, 30));
jButton1.setText("Scan");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e)
{//jContentPane.remove(crpdpanel);
//jContentPane.removeAll();
//jContentPane.repaint();
//jContentPane.revalidate();
getScan();
}
});
}
return jButton1;
}
public void getScan()
{
try
{
//scanner = Scanner.getDevice();
//scanner.addListener(this);
scanner.acquire();
}
catch (ScannerIOException e1)
{
IJ.showMessage("Access denied! \nTwain dialog maybe already opened!");
e1.printStackTrace();
}
}
public Image getImage()
{
Image image = imp.getImage();
return image;
}
/*Image cimg;
public Image getCimg()
{
return cimg;
}*/
public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata) {
if (type.equals(ScannerIOMetadata.ACQUIRED))
{
//imagePanel.revalidate();
//imagePanel.repaint();
//imagePanel.invalidate();
//jContentPane.remove(ipanel);
//ipanel.repaint();
if(imp!=null)
{
jContentPane.remove(ipanel);
jContentPane.remove(cpanel);
jContentPane.remove(crpdpanel);
}
imp = new ImagePlus("Scan", metadata.getImage());
//imp.show();
im = imp.getImage();
//imagePanel = new ImagePanel(im,imageWidth,imageHeight);
imagePanel = new ImagePanel(im);
imagePanel.updateUI();
imagePanel.repaint();
imagePanel.revalidate();
ClipMover mover = new ClipMover(imagePanel);
imagePanel.addMouseListener(mover);
imagePanel.addMouseMotionListener(mover);
ipanel = imagePanel.getPanel();
ipanel.setBorder(new LineBorder(Color.blue,1));
ipanel.setBorder(BorderFactory.createTitledBorder("Scanned Image"));
ipanel.setBounds(0, 30,600, 600);
ipanel.repaint();
ipanel.revalidate();
ipanel.updateUI();
jContentPane.add(ipanel);
jContentPane.getRootPane().revalidate();
jContentPane.updateUI();
//jContentPane.repaint();
// cimg=imagePanel.getCimg();
// ImagePanel cpanel = (ImagePanel) imagePanel.getUIPanel();
/*
cpanel.setBounds(700, 30,600, 800);
jContentPane.add(imagePanel.getUIPanel());
*/
cpanel = imagePanel.getUIPanel();
cpanel.setBounds(700, 30,300, 150);
cpanel.repaint();
cpanel.setBorder(new LineBorder(Color.blue,1));
cpanel.setBorder(BorderFactory.createTitledBorder("Cropping Image"));
jContentPane.add(cpanel);
jContentPane.repaint();
jContentPane.revalidate();
metadata.setImage(null);
try {
new uk.co.mmscomputing.concurrent.Semaphore(0, true).tryAcquire(2000, null);
} catch (InterruptedException e) {
IJ.error(e.getMessage());
}
}
else if (type.equals(ScannerIOMetadata.NEGOTIATE)) {
ScannerDevice device = metadata.getDevice();
try {
device.setResolution(100);
} catch (ScannerIOException e) {
IJ.error(e.getMessage());
}
try{
device.setShowUserInterface(false);
// device.setShowProgressBar(true);
// device.setRegionOfInterest(0,0,210.0,300.0);
device.setResolution(100); }catch(Exception e){
e.printStackTrace(); }
}
else if (type.equals(ScannerIOMetadata.STATECHANGE)) {
System.out.println("Scanner State "+metadata.getStateStr());
System.out.println("Scanner State "+metadata.getState());
//switch (metadata.ACQUIRED){};
ts = ((TwainIOMetadata)metadata).getSource();
//ts.setCancel(false);
//ts.getState()
//TwainConstants.STATE_TRANSFERREADY
((TwainIOMetadata)metadata).setState(6);
if ((metadata.getLastState() == 3) && (metadata.getState() == 4)){}
// IJ.error(metadata.getStateStr());
}
else if (type.equals(ScannerIOMetadata.EXCEPTION)) {
IJ.error(metadata.getException().toString());
}
}
public void stop(){ // execute before System.exit
if(scanner!=null){ // make sure user waits for scanner to finish!
scanner.waitToExit();
ts.setCancel(true);
try {
scanner.setCancel(true);
} catch (ScannerIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm not an expert, but when ScannerIOMetadata.STATECHANGE shouldn't you check if the scanning is complete?
And if it is you should initialize the scanner again.
Something like that:
if (metadata.isFinished())
{
twainScanner = (TwainScanner) Scanner.getDevice();
}