Home > Net >  I use a button to open a window . And inside that window is another button which closes the window j
I use a button to open a window . And inside that window is another button which closes the window j

Time:01-24

I made a button that creates a new window and is disabled. Inside the new window I created, I enter another button which closes this newly opened window and enables the first button. I am nit able to figure out how to do that


    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == button) {
            button.setEnabled(false);
            
            JButton button3 = new JButton();
            button3.setBounds(1,1,50,25);
            button3.addActionListener(this);
            
            
            JFrame y = new JFrame();
            y.setVisible(true);
            y.setSize(240,240);
            y.setLocationRelativeTo(null);
            y.add(button3);
            
71.     //here I want to use button3 to close window y and enable button 1 again, but how I 
        //make the button 3 do that?
            
            
            if (e.getSource() == button3) {
                button.setEnabled(true);
                y.setVisible(false);
            }

I am not able to read the actions of button3 . I really will be grateful if u tell me how to do that.

CodePudding user response:

You have to initialize Jbutton button3 in the class, not in the method actionPerformed() and you have to put if(e.getSource() == button3) in the method, not in the scope of the first if-branch

CodePudding user response:

Thanks John very cool. I share my code now, (cause I know its useless)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

//go to line 71 and I am extremely sorry for including this long code

public class w extends JFrame implements ActionListener {
    private static final long serialVersionUID = 1005007250764256307L;
    public JButton button = new JButton();
    public JButton button2;
    JPanel panel;
    boolean b = true;
    
    w(){
        
        
        
        button.setBounds(100,100,100,50);
        button.addActionListener(this);
        button.setBackground(Color.blue);
        button.setText("Settings");
        button.setFocusable(false);
        button.setForeground(Color.green);
        button.setEnabled(b);
        
        button2 = new JButton();
        button2.setBounds(200,200,100,50);
        button2.addActionListener(this);
        button2.setBackground(Color.red);
        button2.setText("About");
        button2.setFocusable(false);
        button2.setForeground(Color.blue);
        button2.setEnabled(true);
        
        panel = new JPanel();
        panel.setBounds(0, 0, 420, 420);
        panel.setBackground(Color.GREEN);
        
        this.setVisible(true);
        this.setSize(420,420);
        this.setLocationRelativeTo(null);
        this.setTitle("Kukur er Maa");
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(button);
        this.add(button2);
        this.setLayout(null);
        
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == button) {
            button.setEnabled(false);
            
            JFrame y = new JFrame();
            JButton button3 = new JButton();
            button3.setBounds(0,0,100,50);
            button3.setBackground(Color.blue);
            button3.setText("Back");
            button3.setFocusable(false);
            button3.setForeground(Color.green);
            button3.setEnabled(true);
            button3.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    if(e.getSource() == button3) {
                        y.setVisible(false);
                        button.setEnabled(true);
                    }
                    
                }
                
            });
            
            
            
            y.setVisible(true);
            y.setSize(420,420);
            y.setLocationRelativeTo(null);
            y.add(button3);
            y.setLayout(null);
            
        //here I want to use button3 to close window y and enable button 1 again, but how I 
        //make the button 3 do that?
            
            
            if (e.getSource() == button3) {
                button.setEnabled(true);
                y.setVisible(false);
            }
            
            
        }
        else if(e.getSource()== button2) {
            JFrame ne = new JFrame("About");
            ne.setVisible(true);
            ne.setSize(240,240);
            ne.setLocationRelativeTo(null);
            button2.setEnabled(false);
            
            
        }
    }

}

CodePudding user response:

Your code and your problems could be improved upon, including:

  • Any "child" windows should not be JFrames but rather dialog windows. JFrames are for application windows, and only one of these should be displayed at a time (really, only one should be created), while when your application needs dependent sub-windows or "child" windows, then the standard practice is to use dialogs, which Swing implements as JDialogs. These do not show up in the OS's taskbar (while JFrames do), and a single application should only show one task in the OS's taskbar.
  • There are two main types of Swing JDialogs, modal, and non-modal. A modal dialog, like a JOptionPane, blocks the user from interacting with the parent window until the dialog is no longer visible, while a non-modal dialog (such as a drawing program's editor toolbox) allows interaction with the parent window. Your application probably should use a modal dialog.
  • JDialogs are created much the same way as a JFrame, except that you should pass a reference to the parent window into the JDialog's constructor, and you should pass into the constructor if the dialog will be modal or not, via a ModalityType parameter.
  • If the child window is a modal JDialog, if you want to re-activate the main parent window, all you have to do is close the child window, in my example below via window.dispose()
  • Best to create separate classes for separate sections of your program, such as a class (or more than one often) for the main window, and classes for any child windows. You can add listeners to the child window classes in its constructor if desired (and as shown below).

Other more minor issues:

  • Best to avoid null layouts and setBounds(...) and instead learn and use the Swing layout managers to help you build GUI's that are easier to build, that look good on all OS's and that are easily changed later
  • No need to disable the main window's buttons if you are using a modal JDialog since by being modal, the user cannot interact with the main window until the dialog is no longer visible.
  • You may be painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.

For example (and please see comments in code):

import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import javax.swing.*;

@SuppressWarnings("serial")
// Avoid extending JFrame and instead extend JPanel. Even this is not necessary
public class W2Panel extends JPanel {
    // I like using larger fonts if I want my buttons to be larger
    private static final Font BTN_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 24);
    
    // variables for the 2 JButtons:
    private JButton settingsButton = new JButton("Settings");
    private JButton aboutButton = new JButton("About");
    
    // variable for the sub window
    private W2SettingsPanel w2SettingsPanel;

    public W2Panel() {
        // avoid setting sizes and instead set properties and let the GUI size itself
        int gap = 120;
        setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
        settingsButton.setFont(BTN_FONT);
        aboutButton.setFont(BTN_FONT);

        // add an ActionListener to the JButton
        settingsButton.addActionListener(e -> settingsAction());

        // use layouts to set position of things
        JPanel innerPanel = new JPanel(new GridLayout(3, 2));
        innerPanel.add(settingsButton);
        innerPanel.add(new JLabel("  "));
        innerPanel.add(new JLabel("  "));
        innerPanel.add(new JLabel("  "));
        innerPanel.add(new JLabel("  "));
        innerPanel.add(aboutButton);

        // nest JPanels where needed
        setLayout(new GridBagLayout());
        add(innerPanel);
    }

    private void settingsAction() {
        // if settings panel not yet created, then create it
        if (w2SettingsPanel == null) {
            // this gets a reference to the main JFrame:
            Window window = SwingUtilities.getWindowAncestor(this);
            
            // call the W2SettingsPanel constructor, passing in the JFrame's reference
            w2SettingsPanel = new W2SettingsPanel(window);
        }
        w2SettingsPanel.display();
    }

    @SuppressWarnings("unused") // TODO: remove this
    private void aboutActions() {
        // TODO: create and display a modal dialog to display here as well
    }

    public static void main(String[] args) {
        // create and display the main GUI in a Swing safe manner
        SwingUtilities.invokeLater(() -> {
            // create an instance of this class
            W2Panel mainPanel = new W2Panel();

            // create a JFrame, and add this instance into it
            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack(); // let layouts do their thing and size the GUI
            frame.setLocationRelativeTo(null); // center the GUI
            frame.setVisible(true); // show it!
        });
    }

}
@SuppressWarnings("serial")
class W2SettingsPanel extends JPanel {
    private static final Font BTN_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 24);
    private JDialog dialog;
    private JButton backButton = new JButton("Back");
    
    public W2SettingsPanel(Window window) {
        int gap = 200;
        setBorder(BorderFactory.createEmptyBorder(0, 0, gap, gap));
        
        backButton.setFont(BTN_FONT);
        backButton.addActionListener(e -> backAction());
        add(backButton);
        
        dialog = new JDialog(window, "Settings", ModalityType.APPLICATION_MODAL);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.add(this);
        dialog.pack();
        dialog.setLocationRelativeTo(window);
    }
    
    public void backAction() {
        // get the enclosing window (here a JDialog)
        Window window = SwingUtilities.getWindowAncestor(this);
        window.dispose();  // and dispose of it, make it disappear
    }

    public void display() {
        dialog.setVisible(true);
    }
}
  •  Tags:  
  • Related