I would like to ask about a problem i encountered while trying to make a method which can read text from a file.
For example, I created a simple interface, when you click the buttons, the text with a predefined folder path will be read.
So i use actionListener like this. Note that "einlesen" is "read" in German.
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == einlesenDatei)
{
this.einlesen();
}
if (source == decoder)
{
this.decode();
}
}
The problem is, the readInput method required me to throw a FileNotFoundException, and the actionPerformed method requires me to cut off the throw exception part.
You can put the code for read method in a try catch block like this:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == inputFile) {
try {
this.readInput();
} catch (FileNotFoundException e) {
// handle the exception
}
}
if (source == decoder) {
this.decode();
}
}
Related
I have looked at a bunch of answers to a previous question I had (it was answered), but something that I kept seeing were methods like:
public void keyPressed(KeyEvent e)
but none ever showed where these methods were used, so I never figured out what to do with the argument.
Example:
public void keyPressed(KeyEvent e, Robot r) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
r.keyPress(KeyEvent.VK_R);
r.mousePress(InputEvent.BUTTON1_MASK);
try { Thread.sleep(100); } catch (Exception s) {}
r.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
public static void autoCliker() throws AWTException, InterruptedException
{
Robot r = new Robot();
while(KeyPressed(not sure what to do here, r)//this is what my question is about
{
Thread.sleep(10);
r.keyPress(KeyEvent.VK_R);
r.mousePress(InputEvent.BUTTON1_MASK);
try { Thread.sleep(100); } catch (Exception e) {}
r.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
It's more about how to use an Event in an argument within a method than about the KeyEvent, I am just using one of my programs as an example.
This method, along with others, shows up when your class implements KeyListener.
public class Test implements KeyListener {
This method senses key's pressed on the keyboard. If you want to detect a certain key like w. Do this:
if(e.getKeyCode.equals(KeyEvent.VK_W);
Hope this helps.
Basically, the problem is I created an interface with Java Scene Builder. And from FXML button I wanted to open my class.
#FXML
public void pressButton(ActionEvent event) throws Exception {
Platform.runLater(() -> {
try{
new SerialChart().start(new Stage());
} catch (Exception e) {
e.printStackTrace();
}
});
}
#FXML
public void pressButton2(ActionEvent event) throws Exception {
Platform.runLater(() -> {
try {
new Main().start(new Stage());
} catch (Exception e) {
e.printStackTrace();
}
});
}
And my Main can be open, but my SerialChart can't be opened. It says "The constructor SerialChart() is undefined". So here is the problem I think
public SerialChart(String title) {
super(title);
I think this is the problem why I can't open. Please help me... I can show you the whole code if you need.
Like Jim Garrisson said, your constructor that you call takes no arguments, but your defined one does (String title). This means you need to pass in a String argument (Even a blank one like "" will work) when you call it in the Button function.
new SerialChart("Some Title").start(new Stage()); //should be your call in the Button function.
so this is the answer I figured out SO HAPPY
public void pressButton(ActionEvent event) throws Exception {
Platform.runLater(() -> {
try{
SerialChart serialChartDemo = new SerialChart("Clean Energy Data Real time graph");
serialChartDemo.pack();
RefineryUtilities.centerFrameOnScreen(serialChartDemo);
serialChartDemo.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
As mentioned in the title I have to read a .properties file in java and store it in a Properties object. I use a jFileChooser from java swing to get the file, which actually works, then I pass the file to a new window as calling arguments and then I use the load() method to store it in a Properties object but I get the java.lang.NullPointerException error. I hope I was clear as trying to explain it.
This is the code:
public void actionPerformed(ActionEvent e3) { //when button is pressed
JFileChooser fc2 = new JFileChooser (new File("C:\\Users\\Ciurga\\workspace\\PropertiesManager"));
fc2.setDialogTitle("Load Default Values File");
fc2.setFileFilter(new FileTypeFilter(".properties", "Properties File"));
int result = fc2.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
df = fc2.getSelectedFile(); //getting selected file and storing it in "df" which will be passed as calling argument
defaultNameTextField.setText(df.getName());
}
}
This is how I pass the file to the other window:
public void actionPerformed(ActionEvent e1) {
FormWindow w1 = new FormWindow (df, lf); //when button is pressed, create new window passing the files i got with jFileChooser
}
And this is how I tried to store it in a Properties object:
private static Properties propDef;
private static Properties propLim;
private void run(File def, File lim) {
try {
propDef.load(new FileInputStream(def));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
propLim.load(new FileInputStream(lim));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(propDef.getProperty("name"));
}
Thank you guys, as you said I only had to initialize it and now it seems to work correctly, it was a simple error but I'm actually a beginner in java.
This is what I changed:
private static Properties propDef = new Properties();
private static Properties propLim = new Properties();
You never initialised propDef, thats why you get the NullPointerException.
If you did initialise it, please provide the code!
Probably, your propDef and propLim are null and when you call propDef.load(new FileInputStream(def)); you get a NPE because load method is instance method.
I have a problem with creating an outputstream file.
OutputStream output = new FileOutputStream(username + ".txt");
byte buffer[] = data.getBytes();
output.write(buffer);
output.close();
It worked fine, until I made another method:
public void actionPerformed (ActionEvent e) //When a button is clicked
{
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
Previously, I put throws Exception at the start of each method that calls upon the
createprofile();
method (in which the output stream is). But now I get
ProfileEncryption_2.java:54: error: actionPerformed(ActionEvent) in ProfileEncryption_2 cannot implement actionPerformed(ActionEvent) in ActionListener
public void actionPerformed (ActionEvent e) throws Exception //When a button is clicked
^
overridden method does not throw Exception
Previously, I was wondering if there was another way to throw the exception: cannot implement actionPerformed(ActionEvent) in ActionListener
But now I think that it would be better to somehow force the outputstream to make the file. I have googled multiple phrasings of this, but I do now know how to do this... the things I found did not work either.
The ActionListener interface does not declare it's actionPerformed method as throwing any type of Exception, you can not change this signature.
You need to catch and manage the exception from within the method.
public void actionPerformed(ActionEvent e) //When a button is clicked
{
if (e.getSource() == encrBtn) {
menu.setVisible(false);
try {
createProfile();
} catch (Exception exp) {
exp.printStackTrace();
JOptionPane.showMessageDialog(this, "Failed to create profile", "Error", JOptionPane.ERROR_MESSAGE);
}
menu.setVisible(true);
} else {
//...
}
}
FileOutputStream is capable of creating the file if it does not exist, but may have issues if the path doesn't or if you don't have adequate permissions to write to the specified location or any number of other possible issues...
You're getting a type mismatch. The ActionListener interface's actionPerformed method does not include a throws Exception clause, therefore you can't include one on the method you override. A simple fix is to catch any Exception thrown, and re-throw it as a RuntimeException. Since RuntimeExceptions are unchecked, you don't need to include it in the throws clause.
public void actionPerformed (ActionEvent e) //When a button is clicked
{
try { // <-- Added try block
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
catch (Exception e) { // <-- Catch exception
throw new RuntimeException(e); // <-- Re-throw as RuntimeException
}
}
It's usually better to actually handle the exception if possible, but if you just want to see the exception (e.g. for debugging), then I'd say wrapping it in a RuntimeException and re-throwing it is a little cleaner than just adding throws Exception on the end of all your method signatures. It's also better if you can narrow the type of Exception in the catch block down to the actual exception types you're expecting.
I am creating a checkbook and am unable to create a file to write to for each separate account. When I try to create the file I get the error "unreported exception IOException; must be caught or declared to be thrown". I try to declare that my action listener method throws an exception but that makes the action listener method no longer able to work. I then tried to create a separate method that creates the file and is called by the button press but i still run into the same error
Here is my code:
public void actionPerformed(ActionEvent e) {
...
if (e.getSource() == create) {
creatNewAccount(name3.getText());
BALANCE = Double.parseDouble(name2.getText());
}
}
public void creatNewAccount(String s) throws IOException {
FileWriter fw = new FileWriter(s + ".txt", false);
}
creatNewAccount is declared as possibly throwing an IOException. IOException is not a RuntimeException, so you must catch it.
if (e.getSource() == create) {
try {
creatNewAccount(name3.getText());
} catch (IOException ie) {
ie.printStackTrace();
// handle error
}
BALANCE = Double.parseDouble(name2.getText());
}
For more information, please read about The Catch or Specify Requirement and Catching and Handling Exceptions.
A few other things I noticed:
- The word you're looking for is create, not creat.
- You're assigning something to BALANCE. Uppercase names are generally reserved for constants. Consider renaming this variable balance.
- Consider more descriptive names for your text fields. name2 and name3 don't really say much.
IOException is a checked exception. Given that you're calling it within an ActionListener, rethrowing the exception is not an option so you need to catch it.
try {
creatNewAccount(name3.getText());
} catch (IOException e) {
e.printStackTrace();
// more exception handling
}
In your actionPerformed() you need to put a try/catch block around the createNewAccount call. What you do with the exception once caught is up to you -- an easy thing to do is to wrap it in a RuntimeException which does not need to be caught (but might foul up your process until you do something more elaborate).
public void actionPerformed(ActionEvent e) {
...
if (e.getSource() == create) {
try {
creatNewAccount(name3.getText());
} catch( IOException ioe) {
System.err.println("Whoops! " + ioe.getMessage());
throw new RuntimeException("Unexpected exception", ioe);
}
BALANCE = Double.parseDouble(name2.getText());
}
}
It's likely you'll just need to catch the exception inside the method:
public void creatNewAccount(String s) {
try{
FileWriter fw = new FileWriter(s + ".txt", false);
} catch (IOException e){
//TODO something to handle the error
}
}