Help! Using GUI button to update text file
Desperately needing help on the following:
As you will see, I have created two classes - one for reading and writing to a text file on my hard drive, and one for the GUI with two buttons - Display and Update. The Display button works perfectly in that it displays text from a file path. The Update button, however, does not work correctly. I seek for the Update button to update any edits to the same exact text file I view using the Display button.
Any help would be greatly appreciated. Thanks!
Class TextFile
import java.io.*;
public class TextFile
public String read(String fileIn) throws IOException
FileReader fr = new FileReader(fileIn);
BufferedReader br = new BufferedReader(fr);
String line;
StringBuffer text = new StringBuffer();
while((line = br.readLine()) != null)
text.append(line+'\n');
return text.toString();
} //end read()
public void write(String fileOut, String text, boolean append)
throws IOException
File file = new File(fileOut);
FileWriter fw = new FileWriter(file, append);
PrintWriter pw = new PrintWriter(fw);
pw.println(text);
fw.close();
} // end write()
} // end class TextFileClass TextFileGUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class TextFileGUI implements ActionListener
TextFile tf = new TextFile();
JTextField filenameField = new JTextField (30);
JTextArea fileTextArea = new JTextArea (10, 30);
JButton displayButton = new JButton ("Display");
JButton updateButton = new JButton ("Update");
JPanel panel = new JPanel();
JFrame frame = new JFrame("Text File GUI");
public TextFileGUI()
panel.add(new JLabel("Filename"));
panel.add(filenameField);
panel.add(fileTextArea);
fileTextArea.setLineWrap(true);
panel.add(displayButton);
displayButton.addActionListener(this);
panel.add(updateButton);
updateButton.addActionListener(this);
frame.setContentPane(panel);
frame.setSize(400,400);
frame.setVisible(true);
} //end TextFileGUI()
public void actionPerformed(ActionEvent e)
if(e.getSource() == displayButton)
String t;
try
t = tf.read(filenameField.getText());
fileTextArea.setText(t);
catch(Exception ex)
fileTextArea.setText("Exception: "+ex);
} //end try-catch
} //end if
else if(e.getSource() == updateButton)
try
tf.write(filenameField.getText());
catch(IOException ex)
fileTextArea.setText("Exception: "+ex);
} //end try-catch
} //end else if
} //end actionPerformed()
} //end TextFileGUI
Here's your working example.
In my opinion u do not have to append \n when u reading the file
Look the source, if u have some problem, please, ask me.
Regards
public class TextFileGUI implements ActionListener
TextFile tf = new TextFile();
JTextField filenameField = new JTextField(30);
JScrollPane scrollPane = new JScrollPane();
JTextArea fileTextArea = new JTextArea();
JButton displayButton = new JButton("Display");
JButton updateButton = new JButton("Update");
JPanel panel = new JPanel();
JFrame frame = new JFrame("Text File GUI");
public static void main(String args[])
new TextFileGUI();
public TextFileGUI()
panel.setLayout(new BorderLayout());
JPanel vName = new JPanel();
vName.setLayout(new BorderLayout());
vName.add(new JLabel("Filename"), BorderLayout.WEST);
vName.add(filenameField, BorderLayout.CENTER);
panel.add(vName, BorderLayout.NORTH);
scrollPane.setViewportView(fileTextArea);
panel.add(scrollPane, BorderLayout.CENTER);
fileTextArea.setLineWrap(true);
JPanel vBtn = new JPanel();
vBtn.setLayout(new FlowLayout());
vBtn.add(displayButton);
displayButton.addActionListener(this);
vBtn.add(updateButton);
updateButton.addActionListener(this);
panel.add(vBtn, BorderLayout.SOUTH);
frame.setContentPane(panel);
frame.setSize(400, 400);
frame.setVisible(true);
} // end TextFileGUI()
public void actionPerformed(ActionEvent e)
if (e.getSource() == displayButton)
String t;
try
t = tf.read(filenameField.getText());
fileTextArea.setText(t);
catch (Exception ex)
ex.printStackTrace();
else if (e.getSource() == updateButton)
try
tf.write(filenameField.getText(), fileTextArea.getText(), false);
catch (IOException ex)
ex.printStackTrace();
} // end try-catch
} // end else if
} // end actionPerformed()
} // end TextFileGUI
class TextFile
public String read(String fileIn) throws IOException
String line;
StringBuffer text = new StringBuffer();
FileInputStream vFis = new FileInputStream(fileIn);
byte[] vByte = new byte[1024];
int vPos = -1;
while ((vPos = vFis.read(vByte)) > 0)
text.append(new String(vByte, 0, vPos));
vFis.close();
return text.toString();
} // end read()
public void write(String fileOut, String text, boolean append) throws IOException
File file = new File(fileOut);
FileWriter fw = new FileWriter(file, append);
PrintWriter pw = new PrintWriter(fw);
pw.println(text);
fw.close();
} // end write()
} // end class TextFile
Similar Messages
-
Using java to call a text file
I am new to java and was wondering if there is a way of using java to call a text file on my server and use it to create a webpage using a template. Namely to click a link to a poem, and have the java automatically create a page from a text file of the poetry. I need to know if this is even possible, what I would need to look into, (IE: which software or applet to look for), and if there are any sites that anyone knows about that I could learn how to do this. currently I am having to create a page for every poem posted on my site, which takes a great deal of time, and I would like to speed the process up a bit if it is possible. Any suggestions would be greatly appreciated.
Why a text file? I don't think it is a best practice of doing that. Just use a database, keep your poem collections there, and set up a jsp page that seek the database, and then display it on another jsp page. I guess you can find similar application in the sample projects provided by JSC.
-
Using AppleScript to create a text file, based on an OCR'd file's content
Hey guys, I've got an interesting situation.
I was wondering if there would be anyway to use something like AppleScript (or the like) to create a text document and fill it with information based on what is found in an already OCR'd file?
For example: I have a paycheck stub. The stub contains the words "Gross Pay" and the value "$xxxx.xx" on one line. Using Hazel to identify paychecks (based upon filenames), could I then use something like AppleScript, to create a new text file, and then pull the text from the line that contains the word's "Gross Pay" and insert it into the text file's next line?
Ex:
March 26,2012
Gross Pay $xxxx.xx
April 6,2012
Gross Pay $xxxx.xx
Kind of how TurboTax's iPhone app pulls text from an image, then uses the values to insert it into the app's appropriate fields?
I know this may be a lot to ask, but any help is appreciated. Thanks!StevenD: FYI, I did NOT give you the one star rating. I would never do that!
StevenD wrote:
Ow. Someone is grumpy today.
Well, this is an assignment, so it is probably homework.
Why else would anyone give HIM such an assigment, after all he has no LabVIEW experience and the tutorials are too hard for him?
This would make no sense unless all of it was just covered in class!
This is not a free homework service with instant gratification.
OK! Let's do it step by step. I assume you already have a VI with the digital indicators.
"...but have no idea where to begin".
open notepad.
decide on a format, possibly one line per indicator.
type the document.
close notepad.
open LabVIEW.
Open the existing VI with all the indicators.
(are you still following?)
look at the diagram.
Who made the program?
Does the code make sense so far?
Is it a statemachine or just a bunch of crisscrossed wires?
Where do you want to add the file read?
How should the file be read (after pressing a read button, at the start of the program ,etc.)
See how far you get!
Message Edited by altenbach on 06-24-2008 11:23 AM
LabVIEW Champion . Do more with less code and in less time . -
Submit button to update csv file.
Hello,
I have designed a number of forms for my company which are quite basic but i want to be able to create a Radio (Submit) button to automatically update a CSV file.
I know there is a feature for being able to merge multiple documents into a file but i would for a button to be able to do this automatically
Is there a way with javascript?
Thanks
BlakeI would look at using a button.
Radio buttons are for making a single selection from a group of options.
You cannot export a CSV file from a PDF only a tab delimited text file.
Merging multiple PDFs into one PDF is problematic with PDFs. -
Trying to Scan in a List of Names Using a Delimiter from a Text File
Hello everyone,
I tried posting this question onto [Codecall Forums|http://forum.codecall.net/java-help/16064-trying-scan-list-names-using-delimiter-text-file.html] for an answer, but nobody really helped to solve this problem, so I'm reposting it here.
I'm trying to solve this problem on the Euler Project for practice. For the first part of the problem, I am supposed to scan in names in the following format: "name1","name2","name3". To solve this, I wrote the following code:
import java.io.*;
import java.util.*;
public class AlphabeticalSort
public static void main(String args[]) throws IOException
//import the file
Scanner input = new Scanner(new File("names.txt"));
input.useDelimiter("[\",]");
System.out.println(input.delimiter());
//scan it for the length of the array
int n = 0;
while (input.hasNext())
input.next();
n++;
System.out.println(n);
//import the names into the array
Scanner input2 = new Scanner(new File("names.txt"));
input2.useDelimiter("[\",]");
String[] names = new String[n];
for (int i=0; i<n; i++)
names[i] = input2.next();
System.out.println(names);
}However, when I tested this with a file containing "BOB","STEVE","MARK", n equaled 7 and my output was the names each separated by two empty lines. There are other methods I can use to solve this problem, but I would really like to know why my delimiters are not working so I can use them in the future.
Thanks,
helixed
Edited by: helixed on May 14, 2009 10:52 PMTake a look at [Quantifiers in Java regex|http://java.sun.com/docs/books/tutorial/essential/regex/quant.html].
I believe "[\",]+"{code} will get you the results you need.
Edited by: nogoodatcoding on May 15, 2009 11:54 AM -
Use splitter to create multiple text file
Hello I have one view as source and would like to create multiple target text files based on different condition. What I am doing is that I am using SPLITTER which contain one INGRP1 and three OUTGRP( nameley TR1, TR2 and TR3) and one default REMAINING_ROWS ( what is the purpose of the REMAINING_ROWS?). So I mapped view to INGRP1 of the splitter and then added the different SPLITT condition in the condition wizard, for example :
for TR1
COMMISSION_TYPE='P' and
rownum <= 65000
for TR2
COMMISSION_TYPE='P' and
rownum > 65000
and for TR3
COMMISSION_TYPE='A'
After this since I have to create 3 comma delimted text files, I have used 3 expression for each individual splitt condition. In the expression what I am doing is that I am just concating all the fileds and then output of each expression goes to three different text files.
When I am deploying the mapping, it is coming up several errors such as :
1): PLS-00201: identifier 'COMMISSION_TYPE' must be declared
(2): PL/SQL: Statement ignored
(3): PLS-00201: identifier 'COMMISSION_TYPE' must be declared
(4): PL/SQL: Statement ignored
(5): PLS-00201: identifier 'COMMISSION_TYPE' must be declared
(6): PL/SQL: Statement ignored
(7): PLS-00201: identifier 'START_INDEX' must be declared
(8): PL/SQL: Statement ignored
(9): PLS-00201: identifier 'T_EXPR_ASSET_1_OUTPUT_ASSET$0' must be declared
(10): PL/SQL: Item ignored
(11): PLS-00201: identifier 'T_ROWKEY_SPLIT_2' must be declared
(12): PL/SQL: Item ignored
(13): PLS-00201: identifier 'T_CPPASSET_0_OUTPUT_ASSET$0' must be declared
(14): PL/SQL: Item ignored
(15): PLS-00801: internal error [21076]
(16): PL/SQL: Item ignored
(17): PLS-00801: internal error [21076]
(18): PL/SQL: Item ignored
(19): PLS-00801: internal error [21076]
(20): PL/SQL: Item ignored
Why I am getting these errors, why OWB generated code could not identify COMMISSION_TYPE filed?
Please help me.
SuhailI am really very very sorry, its my fault. I was not mapping COMMISSION_TYPE from view to splitter.
-
Help needed regarding reading in a text file and tokenizing strings.
Hello, I require help with a task I've been set, which asks me to read in a text file, and check the contents for errors. The text file contains lines as follows.
surname:forename:1234:01-02-06
I can read in the file, but dont know how to split the strings so each token can be tested (ie numbers in the name tokens)
However, I am not allowed to use regex functions, only those found in java.io.*
I think i should be putting the tokens into an array, but have had no luck so far in doing so. Any help would be appreciated.public class Validator {
public static void main(String args[]) {
String string = "Suname:Forename:1234:01_02-06";
String stringArray[] = string.split(":");
System.out.println (validateLetters(stringArray[0]));//returns true
System.out.println (validateNumbers(stringArray[3]));//returns false
static boolean validateLetters(String s) {
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z')) {
return false; //return false if one of characters is other than a-z A-Z
}//end if
}//end for
return true;
}//end validateLetters
static boolean validateNumbers(String s) {
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c < '0' || c > '9') && (c != '-')) {
return false; //return false if one of characters is other than 0-9 or -
}//end if
}//end for
return true;
}//end validateNumbers
} -
Using servlets to read from text file and insert data
Hi,
Can I use a servlet to read from a space delimited text file on the client computer and use that data to insert into a table in my database? I want to make it easy for my users to upload their data without having to have them use SQL*Loader. If so can someone give me a hint as how to get started? I appreciate it.
Thanks,
ColbyCreate a page for the user to upload the file to your webserver and send a message (containing the file location) to a server app that will open the file, parse it, and insert it into your database. Make sure you secure the page.
or
Have the user paste the file into a simple web form that submits to a servlet that parses the data and inserts it into your db. -
Need Help: UTL_FILE Reading and Writing to Text File
Hello I am using version 11gR2 using the UTL_FILE function to read from a text file then write the lines where it begins with word 'foo' and end my writing to the text file where the line with the word 'ZEN' is found. Now, I have several lines that begin with 'foo' and 'ZEN' Which make for one full paragraph, and in this paragraph there's a line that begins with 'DE4.2'. Therefore,
I need to write all paragraphs that include the line 'DE4.2' in their beginning and ending lines 'foo' and 'ZEN'
FOR EXAMPLE:
FOO/234E53LLID
THIS IS MY SECOND LINE
THIS IS MY THIRD LINE
DE4.2 THIS IS MY FOURTH LINE
THIS IS MY FIFTH LINE
ZEN/DING3434343
FOO/234E53LLID
THIS IS MY SECOND LINE
THIS IS MY THIRD LINE
THIS IS MY FIFTH LINE
ZEN/DING3434343
I am only interested in writing the first paragraph tha includes line DE4.2 in one of ther lines Not the Second paragraph that does not include the 'DE4.2'
Here's my code thus far:
CREATE OR REPLACE PROCEDURE my_app2 IS
infile utl_file.file_type;
outfile utl_file.file_type;
buffer VARCHAR2(30000);
b_paragraph_started BOOLEAN := FALSE; -- flag to indicate that required paragraph is started
BEGIN
-- open a file to read
infile := utl_file.fopen('TEST_DIR', 'mytst.txt', 'r');
-- open a file to write
outfile := utl_file.fopen('TEST_DIR', 'out.txt', 'w');
-- check file is opened
IF utl_file.is_open(infile)
THEN
-- loop lines in the file
LOOP
BEGIN
utl_file.get_line(infile, buffer);
--BEGINPOINT APPLICATION
IF buffer LIKE 'foo%' THEN
b_paragraph_started := TRUE;
END IF;
--LOOK FOR GRADS APPS
IF b_paragraph_started AND buffer LIKE '%DE4%' THEN
utl_file.put_line(outfile,buffer, FALSE);
END IF;
--ENDPOINT APPLICATION
IF buffer LIKE 'ZEN%' THEN
b_paragraph_started := FALSE;
END IF;
utl_file.fflush(outfile);
EXCEPTION
WHEN no_data_found THEN
EXIT;
END;
END LOOP;
END IF;
utl_file.fclose(infile);
utl_file.fclose(outfile);
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20099, 'Unknown UTL_FILE Error');
END my_app2;
When I run this code I only get one line: DE4.2 I AM MISSING THE ENTIRE PARAGRAPH
PLEASE ADVISE...Hi,
Look at where you're calling utl_file.put_line. The only time you're writing anything is immediately after you find the the key word 'DE4', and then you're writing just that line.
You need to store the entire paragraph, and when you reach the end of the paragraph, write the whole thing only if you found the key word, like this:
CREATE OR REPLACE PROCEDURE my_app2 IS
TYPE line_collection
IS TABLE OF VARCHAR2 (30000)
INDEX BY BINARY_INTEGER;
infile utl_file.file_type;
outfile utl_file.file_type;
input_paragraph line_collection;
input_paragraph_cnt PLS_INTEGER := 0; -- Number of lines stored in input_paragraph
b_paragraph_started BOOLEAN := FALSE; -- flag to indicate that required paragraph is started
found_key_word BOOLEAN := FALSE; -- Does this paragraph contain the magic word?
BEGIN
-- open a file to read
infile := utl_file.fopen('TEST_DIR', 'mytst.txt', 'r');
-- open a file to write
outfile := utl_file.fopen('TEST_DIR', 'out.txt', 'w');
-- check file is opened
IF utl_file.is_open(infile)
THEN
-- loop lines in the file
LOOP
BEGIN
input_paragraph_cnt := input_paragraph_cnt + 1;
utl_file.get_line (infile, input_paragraph (input_paragraph_cnt));
--BEGINPOINT APPLICATION
IF LOWER (input_paragraph (input_paragraph_cnt)) LIKE 'foo%' THEN
b_paragraph_started := TRUE;
END IF;
--LOOK FOR GRADS APPS
IF b_paragraph_started
THEN
IF input_paragraph (input_paragraph_cnt) LIKE '%DE4%'
THEN
found_key_word := TRUE;
END IF;
--ENDPOINT APPLICATION
IF input_paragraph (input_paragraph_cnt) LIKE 'ZEN%' THEN
b_paragraph_started := FALSE;
IF found_key_word
THEN
FOR j IN 1 .. input_paragraph_cnt
LOOP
utl_file.put_line (outfile, input_paragraph (j), FALSE);
END LOOP;
END IF;
found_key_word := FALSE;
input_paragraph_cnt := 0;
END IF;
ELSE -- paragraph is not started
input_paragraph_cnt := 0;
END IF;
EXCEPTION
WHEN no_data_found THEN
EXIT;
END;
END LOOP;
END IF;
utl_file.fclose (infile);
utl_file.fclose (outfile);
--EXCEPTION
-- WHEN OTHERS THEN
-- raise_application_error(-20099, 'Unknown UTL_FILE Error');
END my_app2;
SHOW ERRORSIf you don't have an EXCEPTION section, the default error handling will print an error message, spcifying exactly what the error was, and which line of your code caused the error. By using your own EXCEPTION section, you're hiding all that information. I admit, the error messages aren't always as informative as we'd like, but they're never less informative than "Unknown UTL_FILE Error'. Don't use your own EXCEPTION handling unless you can improve on the default.
Remember that anything inside quotes is case-sensitive. If your file contains upper-case 'FOO', then it won't be "LIKE 'foo%' ".
Edited by: Frank Kulash on Dec 7, 2011 1:35 PM
You may have noticed that this site normally doesn't display multiple spaces in a row.
Whenever you post formatted text (such as your code) on this site, type these 6 characters:
\{code}
(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing. -
Font Used For Quick Look Plain Text Files?
Hi,
Does anyone know what font Leopard uses when you Quick Look a plain text file? It's one that isn't anti-aliased. I can't seem to find it anywhere in my Font Book.You could override that with code in userContent.css, either for all websites or for specific websites.
*http://kb.mozillazine.org/userContent.css
<pre><nowiki> pre{font-family:monospace!important}
@-moz-document domain(svn.uni-konstanz.de){
pre{font-family:monospace!important}
}</nowiki></pre> -
Please, I need help - How can I generate a text file with Word format?
Hello friends at www.oracle.com ,
is it possible for me to create a text file - that is, with TEXT_IO.fopen, and so on - that's already formatted as a Word document?
We have a Forms program here, where it's needed to generate a text file with .RTF format, 8 centimeters margin, Times New Roman font, with size 7.
Best regards,
Franklin Goncalves Jr.Hello Shay,
sincere thanks for your answer. And, to answer your last question, I'm using client-server model.
Since I couldn't create this .RTF file by using built-ins like TEXT_IO, I tried to generate an .RTF file using Reports, passing the parameters DESTYPE, DESNAME and DESFORMAT, as shown below.
add_parameter (pl_id, 'DESTYPE', text_parameter, 'FILE');
add_parameter (pl_id, 'DESNAME', text_parameter, 'c:\franklin.rtf');
add_parameter (pl_id, 'DESFORMAT', text_parameter, 'RTF');
However, the just generated .RTF file is uncomprehensible. After opening the file at Microsoft Word, I can see the following message at the top of file:
This file was created by Oracle Reports. Please view this document in Page Layout mode.
... and informations doesn't appear as desired.
If I can't generate such text format by using TEXT_IO, and if generating an .RTF file through Reports shows me an incomprehensible result, how can I export the selected result to an .RTF file?
When Reports is opened, choosing Generate to file -> RTF doesn't export anything.
Thanks, and best regards,
Franklin Goncalves Jr. -
Applescript wont use a value from a text file as a number
I want to perform math operations on a value (0.0092926025390625) that is stored in a text file, i have no problem getting it into the applescript but it says "applescript error cant make "0.0092926025390625" into a number" i know that i am inputting the correct value but it still wont work.
This is just an example code but it does the same thing.
set csv to choose file with prompt "select a file"
read csv
set csv to result
set var1 to word 1 of paragraph 2 of csv
set var1 to var1+1
I get the error on the last lineSure...
set var1 to word 1 of paragraph 2 of csv
by definition, 'words' are string/text objects.
set var1 to var1+1
You can't add integers to strings. Sure, you see the string as being a series of digits, but they could just as easily be letters, symbols, or any other characters. How would you add 1 to "hello", for example?
All is not lost, though. You just need to give AppleScript a hint:
set var1 to (word 1 of paragraph 2 of csv) as number
Now it will read the text and attempt to coerce it to a number. Once it's a number you can add 1 to it. -
Can anyone help me with flash buttons? I am trying to build
my first website, and my five flash buttons (inside a 5 col. table)
for page navigation work fine in testing all 5 web pages with
mozilla firefox, and they look the same on the index page when
testing with IE-7. However when I begin navigating to other pages
in IE-7, the flash buttons disappear, and the 5 cols in the table
where each flash button was placed now are not equal sizes anymore
like they are on the index page. In my files area on the right, I
notice 3 out of the five buttons I created have about 15 to 20
"generations" shown there, with numbers 1 through 15 or even more
to qualify them tacked on to the end of the names. Where do these
come from, and why are 2 out of the five only have 1 "generation"
each? I never expected this, and I think it has something to do
with the problem, but maybe not. Please help me if you can!If you want to use Flash for navigation, consider this -
1. Some people don't have Flash installed - what do they do?
2. Search engines don't parse Flash links - your site will
not be spidered
3. Screen assistive devices don't parse Flash links - what
will those users
do?
4. DW cannot maintain links within a Flash movie, so if you
move or rename
a linked file, your navigation will break - what will you do?
It's usually a very bad idea for these reasons...
Your problem is caused by navigating away from the previewed
page. In
general, this is not a good thing to do, since root relative
links will not
work as expected when you do that (locally).
Murray --- ICQ 71997575
Adobe Community Expert
(If you *MUST* email me, don't LAUGH when you do so!)
==================
http://www.dreamweavermx-templates.com
- Template Triage!
http://www.projectseven.com/go
- DW FAQs, Tutorials & Resources
http://www.dwfaq.com - DW FAQs,
Tutorials & Resources
http://www.macromedia.com/support/search/
- Macromedia (MM) Technotes
==================
"dreamnovice" <[email protected]> wrote in
message
news:[email protected]...
> Can anyone help me with flash buttons? I am trying to
build my first
> website,
> and my five flash buttons (inside a 5 col. table) for
page navigation work
> fine
> in testing all 5 web pages with mozilla firefox, and
they look the same on
> the
> index page when testing with IE-7. However when I begin
navigating to
> other
> pages in IE-7, the flash buttons disappear, and the 5
cols in the table
> where
> each flash button was placed now are not equal sizes
anymore like they are
> on
> the index page. In my files area on the right, I notice
3 out of the five
> buttons I created have about 15 to 20 "generations"
shown there, with
> numbers 1
> through 15 or even more to qualify them tacked on to the
end of the names.
> Where do these come from, and why are 2 out of the five
only have 1
> "generation" each? I never expected this, and I think it
has something to
> do
> with the problem, but maybe not. Please help me if you
can!
> -
Help using right-click to display text in the console/call a pop-up menu
Hi folks,
I hope someone can help me with this problem because, to be honest, I cannot see where I'm going wrong!
Basically, I'm trying to create a routine to display a bit of text in the console (and, if I can get this to work, call a pop-up menu) if a user clicks on an image panel (which I've already created and works fine). My code for this is as follows:
// --- Rest of program here
this.addMouseListener(new MouseAdapter()
public void mouseClicked(MouseEvent e)
// This bit works fine
if (e.getClickCount()>=2)
// Display a dialog box if the user double clicks on the panel
else if (e.isPopupTrigger())
System.out.println("Right mouse button clicked")
// Rest of program in hereThe problem is that, despite my best efforts, "Right mouse button clicked" does not display in the console if the right mouse button is clicked, and I cannot figure out why. I can, however, get it to work PARTIALLY if I use e.isControlDown(), but this only works (I guess) if the user is working on a Mac but isn't using an external mouse. Not ideal.
I'm developing on a Mac (10.4.8) using Eclipse (rather than a PC), but this surely cannot be the problem?Do you start this application in a console window?
If yes then isPopupTrigger() is never true - presumably mouseClicked gets called.
If no then please note that java does not 'pop' a console window when System.out is called. System.out represents an existing output connection. If you want to pop some sort of console then you need to add code to do that. -
Help with makin an interface for text files in a directory
hi all..
i m in need to help for making a GUI, that takes all the filenames from a directory, count them,
display all their names on the GUI in form of radio buttons... for the user to choose from..
and then their shud be some options of changin the data inside the particular file that is chosen..
and storin it back...
i thought to do the GUI part in applet... and other program in simple java code....
but there is some problem in insert that code in applet...
can anyone help tellin me .. if this task can be fully done in java itself..
or can suggest anyother language,,,,
i also have problem in readin the filenames from directory..
and showin it as a option in interface????
please help...
thanks to allHello, I'm trying to do a thing pretty much the same although more simple.
I'm trying to list all contents of a directory, then check if the directory has a directory inside it named according to the contents of the file readed. To summarize, I'm trying to repeatedly open files and compare them.
Here is the code I've written so far:
package archivos;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.io.File;
import java.util.StringTokenizer;
class ej18 extends Frame implements ActionListener
private TextField tf;
private Button b;
private TextArea ta1,ta2,ta3,ta4;
private Label la;
ej18()
setLayout(new FlowLayout());
setSize(200,200);
setVisible(true);
la = new Label("Escribe el nombre del directorio donde se encuentra patrones y patrones.txt:");
tf = new TextField("",20);
ta1 = new TextArea(15,40);
ta2 = new TextArea(15,40);
ta3 = new TextArea(15,40);
ta4 = new TextArea(15,40);
b = new Button("Comenzar");
b.addActionListener(this);
add(la);
add(tf);
add(b);
add(ta1);
add(ta2);
add(ta3);
add(ta4);
pack();
public void actionPerformed(ActionEvent e1)
String x,y;
Button Boton;
Boton = (Button)e1.getSource();
int op=0;
if(Boton==b)
try
x=tf.getText();
File patrones = new File(x);
if(patrones.exists()&&patrones.isDirectory())
{ta1.append("******\nDirectorio <patrones> existe\n");}
else{ta1.append("Directorio <patrones> no existe\n");}
String[] files1 = patrones.list();
ta1.append( "Archivos:\n" );
for( String file : files1 ){ta1.append( file + "\n");}
File textfile = new File(x,"patrones.txt");
if(textfile.exists()&&textfile.isFile())
{{ta2.append("******\nArchivo <patrones.txt> existe\nContenido:\n");
BufferedReader in = new BufferedReader(new FileReader(textfile));
String s="";
//tokeinzer
while ( s != null )
ta2.append(s+"\n");
s = in.readLine();
String rs=s;
String[] result = rs.split(",");
String r = result[result.length-1];
File textfile1 = new File(x,r);
if(textfile1.exists()&&textfile1.isFile())
{ta3.append("*****\nArchivo <"+r+"> existe\nContenido\n");
StringTokenizer st = new StringTokenizer(r,".");
String rr=st.nextToken();
File textdir = new File(x,rr);
if(textdir.exists()&&textdir.isDirectory())
{ta4.append("*****\nEl directorio <"+rr+"> existe\n");
String[] files2 = textdir.list();
ta4.append( "Archivos:\n" );
for( String file : files2 ){ta4.append( file + "\n");}
else{ta4.append("*****\nEl directorio <"+rr+"> no existe\n");}
BufferedReader in1 = new BufferedReader(new FileReader(textfile1));
String ss="";
while ( ss != null )
ta3.append(ss+"\n");
ss = in1.readLine();
else{ta3.append("*****\nArchivo <"+r+"> no existe\n");}
//!tokenizer
in.close();}}
else{{ta2.append("Archivo <patrones.txt> no existe\n");}}
catch (Exception e2)
System.err.println("File input error");
class Intanciador_ej18
public static void main(String ar[])
ej18 obj = new ej18();
}
Maybe you are looking for
-
Photoshop CC 2014 Crashing Consistently
Hello, I am seeking help with my Photoshop CC 2014. I have completely run out of ideas on how to resolve the crashes what I have tried is the following: -Completely replaced hardware from a custom built PC to a Macbook Pro. -Replaced Drawing tablet w
-
Safari 4.0.3 - Apple Home Page takes ages to load
Hi Everyone, Whenever I start up Safari at its default home page (www.Apple.com/starpage) it takes a couple of minutes for the page to load completely. Once the page has (finally) loaded, I get the below message in the status bar at bottom of the Saf
-
Problem with Bridge CS6 and MCXRedirector (OS X 10.9.5)
Good afternoon all, I have a very irritating issue with Bridge CS6 that I've pretty much given up on now, so I'm wondering if anyone out there can help me before I do. The issue lies with Bridge CS6 running in a networked Mac environment, first, a li
-
I have Lightroom 3.6 and want to buy Lightroom 5. Can I get an upgrade or do I need the full program?
-
TS3988 icloud.exe does not load from the installer onto my windows 7 laptop
Installed the iCloudSetup from Apple. Installer said everything installed and finished. When I go to open iCloud, the laptop is looking for the iCloud.exe file and after a few minutes, it notifies me that it cannot find the original .exe file. I am