How to pass the instance of the actual jFrame to other jFrame - java

I have two classes, and from the first jFrame1 (CotizacionGUI) I instantiate and make visible the other one (jFrame2), and I want to pass the instance of this jFrame1 (CotizacionGUI), to the other, in the constructor, to dispose it in an action triggered by the button at any moment...
public class CotizacionGUI extends javax.swing.JFrame{
public CotizacionGUI() {
initComponents();
}
private void buttonCallFrame2ActionPerformed(java.awt.event.ActionEvent evt) {
BuscarCotizacionGUI bC = new BuscarCotizacionGUI(thisjFrameinstance);
bC.setVisible();
}
}
And this is the Frame2 (BuscarCotizacionGUI), here is where I want to dispose the previous jFrame, triggered by the action performed event:
public class BuscarCotizacionGUI extends javax.swing.JFrame {
public BuscarCotizacionGUI(final JFrame otherFrame) {
initComponents();
this.setLocationRelativeTo(null);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
otherFrame.dispose();
}
});
}
}
Can you help me guys please, I don't want to do it using other class, i want to pass the reference in the jFrame1, Thanks!

The instance of first JFrame is always available to you in the same class as this
public class CotizacionGUI extends javax.swing.JFrame{
public CotizacionGUI() {
initComponents();
}
private void buttonCallFrame2ActionPerformed(java.awt.event.ActionEvent evt) {
BuscarCotizacionGUI bC = new BuscarCotizacionGUI(this);
bC.setVisible();
}
}
Hope this is what you are looking for.
Good luck.

Related

Action Listener is not working when I press a Button

I got this code but when I run it the actionListener is not working.
Code
public class MenuPrincipal extends javax.swing.JFrame implements ActionListener {
public MenuPrincipal() {
initComponents();
this.setVisible(true);
this.setLocationRelativeTo(null);
this.addListener();
this.jButton1 = new JButton();
this.jButton2 = new JButton();
}
public static void main(String args[]) {
new MenuPrincipal();
}
private void addListener() {
this.jButton1.addActionListener(this);
this.jButton2.addActionListener(this);
JOptionPane.showMessageDialog(null, "Activado");
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(this.JButton1){
// do something
}
if(event.getSource().equals(this.JButton2){
// do something
}
}
}
I'm using Netbeans to make the interface, thus I'm not pasting here the generated code.
You should write something in the method of the handler:
#Override
public void actionPerformed(ActionEvent event) {
System.out.println("button pressed!");
}
and your class should implement the ActionListener interface
Alternatively you can use the java8 lambdas:
btn.addActionListener(e -> {System.out.println("button pressed!)});
remove this 2 lines from the constructor
this.jButton1 = new JButton();
this.jButton2 = new JButton();
Since addLsiteners method didnt throw any exception, that means you have already instantiated those JButtons. if you re instantiated then those fields will have the reference to different instances than the instance you added the action listener .

Append Code to method

I am a beginner and not so familar with Java yet, so the solution to this might be simple.
I have one MainClass that includes the main method. This MainClass creates a JFrame which can have various JPanels inside. I have one class called CommandInput which creates a JPanel containing a JTextArea. Now I want that when the user closes the JFrame of the MainClass that it asks if he wants to save the changes. As the JPanels inside the JFrame vary I do not really want to include this in the MainClass. I know that it is possible for every "SubClass" like the CommandInput to add a windowListener to the JFrame of the MainClass but that does not really seems efficient to me:
public class CommandInput {
public CommandInput(JFrame mainFrame) {
mainFrame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override //Overwrites the normal behavior of this method
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
System.out.println("Closing Event triggered and detected by CommandInput object");
}
});
}
}
Should I maybe rather have one WindowAdapter in the MainClass and add this code to its windowClosing method? And if so how would I do that?
I now solved it in a way that each SubClass adds an anonymous inner class of an interface containing a method that returns if the JFrame can be closed to a list. Only if all of the anonymous inner classes in the list return true the JFrame closes:
public interface ClosingListener {
public boolean allowClosing();
}
public MainClass {
private ArrayList<ClosingListener> closingListeners = new ArrayList<ClosingListener>();
public MainClass() {
JFrame frame = new JFrame();
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
boolean canClose = true;
for (ClosingListener closingListener : closingListeners) {
if (!closingListener.allowClosing()) {
canClose = false;
break;
}
}
if (canClose) {
System.exit(0);
}
}
});
}
public void addClosingListener(ClosingListener closingListener) {
closingListeners.add(closingListener);
}
}
May be you need this
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
int choice = JOptionPane.showConfirmDialog(null, "Save changes?");
if(choice==0) System.exit(0);
}
});

on pressing default cancel icon[x] of called JFrame layout class, calling layout class gets cancelled too

Class1 which is a NewJFrame Form and is also a calling class to class2, NewJFrame3 has a Jbutton component, jButton1, for which method actionPerformed has been over-ridden. I call the object with a thread. On calling, Class2, NewJFrame3, a new frame pops up. Problem is when I press the default cross of called class, NewJFrame3, button [X], both screens gets cancelled. I was not using threads before and was calling the layout method for JFrame3 with just object, but it had this problem, so i used thread but it wouldnt work.
Code of calling class (Layout is fine for this and on clicking its button JButton1, class NewJframe3’s layout pops up) :
public class NewJFrame extends javax.swing.JFrame implements ActionListener
{
public NewJFrame()
{
initComponents();
jButton1.addActionListener(this);
}
private void initComponents()
{
//layout code for JFrame1 – gives the desired layout/output
}
public void actionPerformed(ActionEvent e)
{
If(some_condition)
{
NewJFrame3 obj2 = new NewJFrame3();
Thread th1 = new Thread(obj2, "thread1");
th1.start();
}
}
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new NewJFrame().setVisible(true);
}
});
}//Main ends
}//Calling Class NewJFrame1 ends
Code for called class(same package) :
public class NewJFrame3 extends javax.swing.JFrame implements Runnable
{
public void run()
{
// System.out.println("Inside Run");
this.test();
this.setVisible(true);
}
protected void test()
{
//layout code for JFrame3 – gives the desired layout/output
}
PSVM()
{
//Main method code not relevant here, since layout function is called from run() which gets called on starting thread for this class.
}
} //Called Class NewJFrame3 end
Thanks a ton for your time!
you have to set for defaultCloseOperation, set to DISPOSE_ON_CLOSE in this case, last of JFrames to terminating an Current JVM
your current issue is default value HIDE_ON_CLOSE, then current JVM is still running, consume and increase RAM in PC
use CardLayout or JDialog with parent, and/or setModal/ ModalityTypes instead of two JFrames

Disable a JButton from a listener that's in a separate class

I'm writing a pretty big class and don't want to post it here. The question is the following, how do I refer to the button that was pressed in the constructor of a different class? Let's say, I want to disable it after some actions in the listener. If the listener were anonymus or were an inner class of the SomeClass, I would just use the name of the variable like this:
button.setEnabled(false);
But how can I do it when my listener is a separate class? Tried using e.getModifiers().setEnabled(false) and e.getSource().setEnabled(false), didn't work.
public class SomeClass extends JPanel {
private JButton button = new JButton("Button");
public SomeClass() {
button.setActionCommand("button");
button.addActionListener(new ButtonListener());
}
public static void main(String[] args) {
// TODO code application logic here
}
}
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String src = e.getActionCommand();
if (src.equals("button")) {
//some actions here
//then
}
}
}
Try this ((JButton)e.getSource()).setEnabled(false)
It must work)
e.getSource() return component to which this event refers( docs)

Unable to call the repaint in applet from child frame

I have made an applet name ParentApplet.java whose task is to create a child frame
Child frame coding is defined in ChildFrame.java
ParentApplet.java
public class ParentApplet extends Applet {
ChildFrame frame;
private static int time = 0;
#Override
public void start() {
frame.setVisible(true);
}
#Override
public void stop() {
frame.setVisible(false);
}
#Override
public void init() {
frame = new ChildFrame("Child");
this.setSize(400, 400);
}
#Override
public void paint(Graphics g) {
g.drawString("Child's Info : " + (++time), 50, 100);
g.drawString(frame.getMessage(), 400, 100);
System.out.println(frame.getMessage().isEmpty() ? "Empty" : frame.getMessage());
}
}
ChildFrame.java
public class ChildFrame extends Frame {
private String mess = "";
public ChildFrame(String title) {
super(title);
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter(this));
setSize(300, 500);
}
public String getMessage() {
return mess;
}
public void setMessage(String mess) {
this.mess = mess;
(new ParentApplet()).repaint();
System.out.println("Click");
}
}
MyMouseAdapter.java
public class MyMouseAdapter extends MouseAdapter {
ChildFrame frame;
public MyMouseAdapter(ChildFrame frame) {
this.frame = frame;
}
#Override
public void mouseClicked(MouseEvent e) {
frame.setMessage("Mouse Cliked in Child");
}
}
MyWindowAdapter.java
public class MyWindowAdapter extends WindowAdapter {
ChildFrame frame;
public MyWindowAdapter(ChildFrame frame) {
this.frame = frame;
}
#Override
public void windowClosing(WindowEvent we) {
frame.setVisible(false);
}
}
Now i am unable to reach the paint method again even after calling the repaint method from the ChildFrame class. Please suggest me whether i have done something wrong or some thing i need to understand.
Thanks in advance
Gagandeep Singh
The answer to your question is basically "you don't do that".
The Applet's paint() method is responsible for painting the contents of the actual applet component-- i.e. the visible component that appears in the web page. Your ChildFrame should then have a separate paint() method to paint itself (or in fact, would usually have a Canvas added to it, and that Canvas in turn has its own paint() method).
(Remember that in Java a "Frame" is effectively a "window"-- i.e. a standalone window that opens separately to the web page.)
You can call repaint() on whatever component from wherever you like. This will eventually lead to that component's paint() method being called. In your particular example, you shouldn't call "new ParentApplet()" -- you don't want to call repaint() on some randomly created new applet, but rather on the single already existing one. So change this by passing a reference to your applet into the constructor of ChildFrame which ChildFrame can then hold as an instance variable and re-use when needed:
public class ChildFrame extends Frame {
private String mess = "";
private final ParentApplet parentApplet;
public ChildFrame(ParentApplet applet, String title) {
super(title);
this.parentApplet = applet;
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter(this));
setSize(300, 500);
}
...
public void setMessage(String mess) {
this.mess = mess;
parentApplet.repaint();
}
}
I must admit that so far, it's not immediately obvious why you would have a setMessage() on a separate frame whose purpose is to set the message displayed in the applet. Why not put the setMessage() method on the applet in that case? But maybe you have another reason for doing it your way that isn't apparent so far.

Categories

Resources