Handling button event from another class in Jframe - java

I am using netbeans to make a GUI. To make it simple, let say what I want to do is that when I press a button it just opens a new JFrame and print a text on a JPanel, a text entered by the user.
It sounds easy if I just complete the automatically generated function from Netbeans :
private void popUpButtonActionPerformed(java.awt.event.ActionEvent evt) {
// I added these three lines
JFrame newFrame = new myPopUpWindow();
myPopupWindow.getTextLabel().setText("Hello" + enteredText.getText());
this.dispose();
}
And everything works as I want. Now what I want to do is having a cleaner code. I want to put these two line in a class ButtonHandler.java in a function handleHelloPopUp(String enteredStringText) Now comes the dilemma:
If I make handleHelloPopUp static, I get some error when I access some non static variable
If I don't make handleHelloPopUp I just have to pass it as argument in my Jframe -> horrible code structure
What is the best way to do this ? Please help ...

Related

How to close a called class using JFrame without closing the class that called it?

I seem to have a fairly unique problem, and I searched for a while for an answer on here without finding one. I have a class that has a simple JFrame with two buttons. Each button calls the Main method of a different class, as such:
checkRuling = new JButton("Check Your Deck's Rulings");
checkRuling.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
ReadHtmlCardDatabase.main(null);
}
});
One calls a class that takes a series of inputs into a text field and creates a formatted html document from the inputs, and the other loads the html document into a JEditorPane. My problem is that when I close one of the JFrames for the subclasses (either the input or html loader one), it exits my program completely, and I want to keep the main class (with the two buttons) open. I've tried using:
close = new JButton("CLOSE");
close.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
System.exit(1);
}
});
On a button in the subclasses, to no avail. When the button is clicked it simply exits everything. I've also tried using:
JFrame.DISPOSE_ON_EXIT
For the subclasses, but this causes the JFrames to go away without the subclasses actually closing, so the first one that saves the html document never actually saves it, and the second subclass that opens that same html document won't work, because it wasn't saved. Any help would be appreciated, because I can't figure out how to do this.
As Fast Snail says in the comments, you shouldn't be calling a main method. Instantiate a class that does each functonality. Set the frame to visible using setVisible(true) when you start using it, then setVisible(false) when you're done. So, in the action listener, just change the visibility.
Then, assuming you don't have anything too wild going on, the frame you just set to invisible should go out of scope and get freed so that memory isn't chewed up. You just instantiate a new copy of the ReadHtmlCardDatabase class each time you need one. Or you could have one static copy that you set visible/invisible as needed.
one of the JFrames
You should use only one JFrame in Your GUI. For other windows You can use for example JDialog or JWindow.
This should help, if not You can always use frame.setVisible(false) instead of dispose on close, but it' s not very neat.
Thanks to someone who posted a comment and then deleted it, I've figured out my own problem. I just had to replace my main call with this:
setDeck = new JButton("Set Deck");
setDeck.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
WriteHtmlCardDatabase w = new WriteHtmlCardDatabase();
w.main(null);
}
});
Thank you!

Java Application Restart or Reset Button

I have a very simple, choose your path, Java game that I am working on in the NetBeans IDE. Basically what happens is the user will click one of the three buttons, and pre-made JLabel's which are set to "" (nothing) will be reset to whatever text I decide that label should then use. I do this by adding the code below.
private void option1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel6.setText("You go down the dark tunnel...");
}
Now all this works fine but I'd like a way to restart/reset my application by clicking a button labelled "restart". I don't mind if it has to close the application and then open it again or if it will simply reset all the JLabel's back to "". I just don't want to have to type out the code below for every single JLabel.
jLabel1.setText("");
jLabel2.setText("");
jLabel3.setText("");
I have done some research on this site and none of the code that people provide seems to work for my situation, either because it simply doesn't work or because I am doing something wrong. Any help would be greatly appreciated and please try and be specific because I am fairly new to writing Java and don't understand everything.
It would also work for me if someone could provide a way for me to close 1 window in an application instead of the whole thing, like when
System.exit(0);
is used.
First, I recommend importing the JLabel class specifically so you can write JLabel instead of javax.swing.JLabel:
import javax.swing.JLabel;
Instead of declaring each JLabel individually, create an Array of JLabels:
JLabel[] jLabels = new JLabel[N]; // where N is the number of JLabels
Whenever you need to access a JLabel, use:
jLabels[6].setText("You go down the dark tunnel...");
When you want to reset all the JLabels, use:
for (JLabel jLabel : jLabels) {
jLabel.setText("");
}
For more details on Arrays, read http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
If you are having your program as a executable jar file then you can use
public void restert(){
Runtime.getRuntime().exec("java -jar yourapp.jar");
System.exit(0);
}
If you want to know more about restarting java application you can go through this
Found the answer to my own question:
Thanks to Holger for suggesting "dispose". This is what I found worked.
private void restartButtonActionPerformed(ActionEvent evt) {
if(evt.getSource() == restartButton)
{
dispose();
MyGUI game = new MyGUI();
game.setVisible(true);
}
}

java: how can i pass a variable from the starter JFrame to the last without having to pass it through all JFrames?

I have this problem: I have an ArrayList that contains a few items that I want to use in a particular frame, the problem is that the array list gets full by initializing it in the main class of my project. In this class I also launch my starting frame that is chained with other frames (login frame -> middle frame --> last frame). I want to carry this ArrayList without having to carry it on through all frames and get it directly usable from main --> last frame. How can I do this?
EDIT
Wat I did it was like first frame start with this ArrayList as parameter:
Jframe jf = new LoginFrame(arraylistvariable,"Login Window");
Then in all ActionListener calls on the buttons that create new frames, disposing old ones, I set it like:
Jframe jo = new MiddleFrame(arraylistvariable,"Middle Window");
Passing this variable all over the frames but I want this to be like called only by the frame that needs this, because login frame doesn't need this variable. However, it is necessary to start the program by the login frame.
"However, it is necessary to start the program by the login frame."
No it's not.
public class MiddleFrame() {
private LoginFrame;
}
...
public static void main(String[] args){
new MiddleFrame();
}
Make the middle frame not visible upon instantiation, but make the LoginFrame visible. If the login is successfful, but make the MiddleFrame visible.
Note You don't need to use to many frame. Make use of JDialogs. See this answer for How to make a Login with a JDialog
one from the easiest way it to pass it/them trough system properties
You might want to create some class like ArrayListVariableProviderService and make it accessible either to all classes (JFrames) or via static call.
This can act as a container to many things, yet it'll abstract out all peculiarities.
Good luck.

Calling A JFrame method from Another JFrame

I'm looking to find a solution too my issue. Currently I have 2 JFrames and 1 utilities class in my netbeans project. I'm no expert on java so please bear with me. I've tried looking through the java docs and on this site but cannot seem to find a solution to my problem.
Here is the scenario:
My launcher class launches the JFrame called MainForm.java the form then initializes components onto the screen. On this form I have a button that launches a new form called ConfigEditor.java. This form is used to edit a config file. I have a Save button on this form, and what I basically want to do is once I click save get the MainForm.java to call a method to fill in the right components with the new values.
Heres an example, heres some of the code from my Save button on the ConfigEditor.java:
if(reply == JOptionPane.YES_OPTION){
try {
Utilities.writeConfigFileBasic(ExecutionLists.getText(),DefaultResultsFile.getText(),
DefaultTestDir.getText(), Environments.getText(), ResultsViewerFile.getText());
ConfigTextArea.append(Utilities.readConfigFile());
JOptionPane.showMessageDialog(rootPane, "Saved");
Now just after the last line I want to call somthing like MainForm.initMyComponents(); as this method exists in the MainForm JFrame but it wont let me call this. The purpose of that method is to populate some of the fields with data extracted from a config file.
I'm sorry if I haven't explained it very well, I'm fairly new to Java if you need any clarification please let me know and I'll do my best to clarify it.
Can you simply pass a reference of MainForm to ConfigEditor when it is constructed? For instance:
... //Code fired by clicking the button you mentioned which is in class MainFrame
ConfigEditor configEditor = new ConfigEditor(this); //This would be a reference to your MainFrame
With this reference you can then call your desired method in the MainFrame class.

Using KeyListener for a Calculator in NetBeans

I have written a calculator in NetBeans and it functions perfectly. However, I have to actually click the buttons to insert numbers and am trying to remedy that with a KeyListener. I have all my numbers and function buttons set inside a JPanel named buttons. I have my display label in a JPanel named display.
I set my class to implement KeyListener and it inserted the KeyPressed, -Typed, and -Released methods; however I stuck from there. I'm not sure how to make my buttons actually listen for the KeyPressed event, and when it hears the event - activate the button. Also, my buttons are named by their number (e.g. the Zero Button is named zero, One button is one, etc.).
I've read that you actually have to implement a KeyListener somewhere by using: something.addKeyListener(something);
but I cannot seem to figure this out.
Can I get some help here? I'm new to Java and this is my first solo project. And let me know if I didn't provide enough information.
EDIT: Most of my code is NetBeans Generated and I cannot edit the initialization of the components which seems to be my problem I think?
My class declaration:
public class Calculator extends javax.swing.JFrame implements KeyListener {
//Creates new form Calculator
public Calculator() {
initComponents();
}
One of my buttonPressed actions (all identical with changes for actual number):
private void zeroActionPerformed(java.awt.event.ActionEvent evt) {
if (display.getText().length() >= 16)
{
JOptionPane.showMessageDialog(null, "Cannot Handle > 16 digits");
return;
}
else if (display.getText().equals("0"))
{
return;
}
display.setText(display.getText().concat("0"));
Main method supplied by NetBeans:
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Calculator().setVisible(true);
}
});
}
The initComponents() netbeans generated is absolutely massive (about 500 lines of code) and I cannot edit any of it. Let me know if I can supply any more helpful information.
Could there be an issue of Focus, and if so how can I resolve the issue?
Yes there is probably an issue with focus. That is why you should NOT be using a KeyListener.
Swing was designed to be used with Key Bindings. That is you create an Action that does what you want. Then this Action can be added to your JButton. It can also be bound to a KeyStroke. So you have nice reusable code.
Read the Swing tutorial on How to Use Key Bindings for more information. Key Bindings don't have the focus issue that you currently have.
I'm not sure I completely understand your question, and some code would help, but I'll take a crack, since it sounds like a problem I used to have a lot.
It sounds like the reason that your key presses aren't being recognized is that the focus is on one of the buttons. If you add keylisteners to the buttons, then you shouldn't have any problem.
In netbeans you can add keylisteners through the design screen really easily.
Here's a picture showing you how to add a keyPressed listener to a button in a jPanel.
private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {
//Check which key is pressed
//do whatever you need to do with the keypressed information
}
It is nice to be able to write out the listeners yourself, but if you are just learning, then it is also nice to get as much help as possible.
This might not be the best solution, since you would have to add the listener for each of your buttons.

Categories

Resources