Retrieving content of Textarea within a JTabbedpane - java

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

Related

Java FileDialog Save as

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

Java program not saving contents of ".txt" file

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.

how to prevent jscrollpane from scrolling to the bottom?

I have JTextPane (log) inside JScrollPane (logScrollPane) element. Log's content is set to "text/html".
I created a method that appends this log which looks like this:
public void appendLog(String someHTMLText)
{
HTMLDocument doc = (HTMLDocument) log.getDocument();
HTMLEditorKit editorKit = (HTMLEditorKit) log.getEditorKit();
try
{
editorKit.insertHTML(doc, doc.getLength(), someHTMLText, 0, 0, null);
}
catch (BadLocationException | IOException ex)
{
// handle exceptions
}
}
I want to improve this method and force logScrollPane's VerticalScrollBar to move_to_the_bottom/stay_at_it's_position depending on additional boolean argument.
Final method should look like this:
public void appendLog(String someHTMLText, boolean scroll)
{
if(scroll)
{
/*
* append log and set VerticalScrollBar to the bottom by
* log.setCaretPosition(log.getDocument().getLength());
*/
}
else
{
// append log BUT make VerticalScrollBar stay at it's previous position
}
}
Any suggestions? :)
Here is something similar to what I did when I wanted to achieve this. The key is to alter the behavior of scrollRectToVisible.
public class Docker extends JFrame {
boolean dockScrollbar = true;
MYTextPane textPane = new MYTextPane();
JScrollPane sp = new JScrollPane(textPane);
Docker() {
JCheckBox scrollbarDockCB = new JCheckBox("Dock scrollbar");
scrollbarDockCB.addItemListener(new DockScrollbarListener());
scrollbarDockCB.setSelected(true);
JButton insertText = new JButton("Insert text");
insertText.addActionListener(new TextInserter());
getContentPane().add(insertText, BorderLayout.PAGE_START);
getContentPane().add(sp);
getContentPane().add(scrollbarDockCB, BorderLayout.PAGE_END);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
class MYTextPane extends JTextPane {
MYTextPane() {
setEditorKit(new HTMLEditorKit());
}
#Override
public void scrollRectToVisible(Rectangle aRect) {
if (dockScrollbar)
super.scrollRectToVisible(aRect);
}
void insertText(String msg) {
HTMLEditorKit kit = (HTMLEditorKit) getEditorKit();
HTMLDocument doc = (HTMLDocument) getDocument();
try {
kit.insertHTML(doc, doc.getLength(), msg, 0, 0, null);
} catch (BadLocationException | IOException e1) {
e1.printStackTrace();
}
setCaretPosition(doc.getLength());
}
}
class TextInserter implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
textPane.insertText("AAA\n");
}
}
class DockScrollbarListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
dockScrollbar = true;
JScrollBar sb = sp.getVerticalScrollBar();
sb.setValue(sb.getMaximum());
}
else if (e.getStateChange() == ItemEvent.DESELECTED)
dockScrollbar = false;
}
}
public static void main(String[] args) {
new Docker();
}
}
Notes:
I made the docking set to false when you manually scroll in my code, you can add it here too. by adding a mouse listener to the vertical scrollbar.
I have boolean dockScrollbar as a field of the text pane because I have more than one.
I don't have a field for the JScrollPane, I get it through the text pane.
I've never tried it on a JEditorPane but you should be able to use the caret update policy to control this.
Check out Text Area Scrolling for more information.

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.

Java cant write in a .txt

hello i desperately need your help,well i have a jframe with a jcombobox and 3 textfields i want anything i write in the textfields and the choice i make in the combobox to be written in a .txt i tried so many things but nothing , the file is being created as Orders.txt but remains blank :S this is my code i appreciate any help Thanks :)
public class addSalesMan extends JFrame {
private JComboBox namesJComboBox;
private JTextField text1;//gia to poso
private JTextField text2;//thn perigrafh
private JTextField text3;//kai to numero ths paragelias kai ola auta tha egrafontai sto Orders.txt
private JButton okJbutton;
private String names[] = {"Basilis Komnhnos", "Iwanna Papadhmhtriou"};
public String amount,name,description,number;
public addSalesMan() {
super("Προσθήκη παραγγελιών");
setLayout(new FlowLayout());//dialegoume to flowlayout
// TextFieldHandler handler = new TextFieldHandler(); writer.write(string);
//ftiaxonoume to combobox gia tn epilogi tou onomatos
namesJComboBox = new JComboBox(names);//orizmos JCOMBO BOX
namesJComboBox.setMaximumRowCount(2);//na emfanizei 2 grammes
add(namesJComboBox);
namesJComboBox.addItemListener(new ItemListener() {
//xeirozome to simvan edw dhladh tn kataxwrisei ston fakelo
public void itemStateChanged(ItemEvent event) {
//prosdiorizoyme an eina epilegmeno to plaisio elegxou
if (event.getStateChange() == ItemEvent.SELECTED) {
name = (names[namesJComboBox.getSelectedIndex()]);
// writer.newLine();
setVisible(true);
}
}
}); //telos touComboBOx
//dimioutgw pediou keimenou me 10 sthles gia thn kathe epilogh kai veveonomaste oti tha mporoume na ta epe3ergasoume kanontas ta editable
text1 = new JTextField("Amount",10);
add(text1);
text2 = new JTextField("Description",10);
add(text2);
text3 = new JTextField("Order Number",10);
add(text3);
TextFieldHandler handler = new TextFieldHandler();
text1.addActionListener(handler);
text2.addActionListener(handler);
text3.addActionListener(handler);
//private eswterikh clash gia ton xeirismo twn events twn text
//button kataxwrisis
okJbutton=new JButton("Καταχώρηση");
add(okJbutton);
ButtonHandler bhandler=new ButtonHandler();
okJbutton.addActionListener(bhandler);
Order order=new Order(name,amount,description,number);
Order.addOrders(name,amount,description,number);
}
private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent bevent ){
JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",bevent.getActionCommand()));
}
}
private class TextFieldHandler implements ActionListener {
//epe3ergasia twn simvantwn me kathe enter t xrhsth
public void actionPerformed(ActionEvent evt) {
String amount,description,number;
amount=text1.getText();
description=text2.getText();
number=text3.getText();
text1.selectAll();
text2.selectAll();
text3.selectAll();
}
if(evt.getSource()==text1 && evt.getSource()==text2 && evt.getSource()==text3){
JOptionPane.showMessageDialog(addSalesMan.this,String.format("Η Καταχωρηση ήταν επιτυχής",evt.getActionCommand()));
}
}
//actionperformed telos
//ean o xrhsths patisei enter sthn kathe epilogh antistixi kataxwrisi sto
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new addSalesMan().setVisible(true);
}
});
}
}
The writers are in another class. Here is the relevant code:
public static void addOrders(String name,String amount,String description,String o_number){
FileOutputStream fout;
try {
FileWriter fstream = new FileWriter("Orders.txt");
if(name!=null){
BufferedWriter out = new BufferedWriter(fstream);
out.write(name);
out.write(amount);
out.write(description);
out.write(o_number);
out.write("\t\n");
out.close();
}
} catch (IOException e) {
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
It looks like the main problem is that you are calling Order.addOrders() in your constructor. Instead, you should call it when a user chooses to save it's selection. I assume you would like this to happen when the user presses the button. So the code should be added in the button's ActionListener.
What you might need to try is flushing and closing the writer when a user closes your frame.
Add the following to the constructor of your frame:
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
writer.flush();
writer.close();
}
});
The above code will flush and close the writer when a user closes the frame.
Your code is unclear, so I'm not sure where the writer variable is declared, I'm just assuming it is a class level variable.
Also, you need to open your file in 'append' mode if you want to add lines to the file instead of overwriting it every time. This can be achieved through the following:
new FileWriter(yourFilePath, true); // set append to true

Categories