1

I'm working on a java application which has 5 gui windows, one of them is greeting or main window, I've finished my work on all logical parts and I'm 99.99% done, the only thing left is that how can i code in this way that when i click on a button , let say a button on main window , and it will lead me to the 2nd window and the main window will be automatically closed, How can i make it happen?

Any help would be appreciated.


Edit

here is the code sir

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

class Nc extends JFrame
{
private JLabel label;
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JLabel label4;
private JButton b;
private JButton o;
private JButton h;
private JButton d;

private Bn ob;
private Hd oh;
private Oc oo;
private Dc od;

public Nc()
{
    setTitle("Number Converter");
    setSize(200 , 300);
    setResizable(false);
    setLocation(500 , 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout(FlowLayout.CENTER, 25, 10));

    label = new JLabel("Number Converter");
    label1 = new JLabel("Java Application");
    label2 = new JLabel("Programmed by: Hassan Zia");
    label3 = new JLabel("Copyright 2014");
    label4 = new JLabel("Click a button");

    b = new JButton("Binary");
    o = new JButton("Octal");
    h = new JButton("Hexa Decimal");
    d = new JButton("Decimal");

    add(label);
    add(label1);
    add(label2);
    add(label3);
    add(label4);

    add(b); // Binary Button
    add(o); // Octal Button
    add(h); // Hexa Decimal Button
    add(d); // Decimal Button

    b.addActionListener(new action());
    o.addActionListener(new action());
    h.addActionListener(new action());
    d.addActionListener(new action());

    setVisible(true);
}

void bnc()
{
    ob = new Bn();
}

void hdc()
{
    oh = new Hd();
}

void occ()
{
    oo = new Oc();
}

void dcc()
{
    od = new Dc();
}

private class action implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == b)
        {
            bnc();
        }
        if (e.getSource() == h)
        {
            hdc();
        }
        if (e.getSource() == o)
        {
            occ();
        }
        if (e.getSource() == d)
        {
            dcc();
        }
    }
}

public static void main (String args[])
{
    Nc obj = new Nc();
}

This is a picture of the app

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Hassan Zia
  • 330
  • 5
  • 17
  • I'm guessing that this is a Swing application? You never say, and the GUI library used is quite important as changing it will change the answer drastically. Please provide more detail on your problem, show relevant code, and add appropriate tags to your question to help us to better understand your problem and to attract the right experts to this question. – Hovercraft Full Of Eels Sep 13 '14 at 16:58
  • 1
    Also ask yourself, how many professional applications do you use that jump from window to window? Not many because it is a very distracting and often unpleasant experience for the user. Most use a single main application window that swaps gui views within this window and with an occasional dialog window popping up when information is needed in a modal fashion. You might want to consider emulating this design. Please have a look at [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice) – Hovercraft Full Of Eels Sep 13 '14 at 16:58
  • sir actually i'm working on a number convertor application, which coverts numbers from binary to (OCT, DC , HD) and similarly from other formats to other formats (hope you get what i mean), i've main window which have 4 buttons (Binary conversion , Octal conversion, e.tc) and when i click on a button, let say Binary Conversion it will open a new window named as Binary conversion, but the main window is still there and I want it to close when i click a button . thats all , – Hassan Zia Sep 13 '14 at 17:08
  • 1
    You still have yet to tag the question for the appropriate GUI library -- Swing? AWT? Android? SWT? Something else? You still need to post code, especially a code attempt, and a [Minimal, Complete, and Verifiable Example Program](http://stackoverflow.com/help/mcve), and you still need to make your questions much more specific describing in detail just where you might be stuck. Please help us help you. – Hovercraft Full Of Eels Sep 13 '14 at 17:11
  • See edit to answer for my take on your program. – Hovercraft Full Of Eels Sep 13 '14 at 18:23

1 Answers1

4

If this is a Swing application (you still haven't told us), then you could solve your direct question, by placing in a JButton's ActionListener code that calls setVisible(false) on the current window if you will use it again or dispose() on it if you won't be using it again, and then calls setVisible(true) on the next window object that you wish displayed. This could be as simple as:

myButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       ThisGuiClass.this.setVisible(false);
       newGUI.setVisible(true);
    }
});

but again unanswered questions remain.

  • Again, is this a Swing GUI? Specific solutions will depend on the GUI library that you're using.
  • The specifics of a code solution will also depend completely on the specific code and program structure that you're using, something you've not shown us. Please show us code if you want a better answer.
  • Again, I stand by my recommendation to minimize the windows that are thrown at a user, to favor use of say CardLayout to swap views on a single window, if possible, and to limit 2nd window use to modal JDialogs (as much as possible). A great reference on this remains the link, The Use of Multiple JFrames, Good/Bad Practice?

Edit
OK, I've seen that you've added a Swing and AWT tag, thanks, but I still think that my answer is as yet very incomplete because the question is still incomplete.


Edit 2

Based on your code, I would stand by my original recommendations and would use a CardLayout to swap JPanel "views". For example, run this:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class NumberConverterWithCardLayout extends JPanel {
   private CardLayout cardlayout = new CardLayout();
   private JPanel cardPanel = new JPanel(cardlayout);
   private BinaryPanel binaryPanel = new BinaryPanel();
   private OctalPanel octalPanel = new OctalPanel();
   private HexadecimalPanel hexadecimalPanel = new HexadecimalPanel();
   private DecimalPanel decimalPanel = new DecimalPanel();
   private JPanel[] allPanels = { binaryPanel, octalPanel, hexadecimalPanel,
         decimalPanel };

   public NumberConverterWithCardLayout() {
      JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));

      setLayout(new BorderLayout());
      add(cardPanel, BorderLayout.CENTER);
      add(buttonPanel, BorderLayout.PAGE_END);

      cardPanel.add(createIntroPanel(), "intro");

      for (final JPanel jPanel : allPanels) {
         cardPanel.add(jPanel, jPanel.getName());
         buttonPanel.add(new JButton(new AbstractAction(jPanel.getName()) {

            @Override
            public void actionPerformed(ActionEvent evt) {
               cardlayout.show(cardPanel, jPanel.getName());
            }
         }));
      }
   }

   private JPanel createIntroPanel() {
      JPanel introPanel = new JPanel(new GridBagLayout());
      introPanel.add(new JLabel("Introductory panel which introduces me and the program"));
      return introPanel;
   }

   private static void createAndShowGui() {
      NumberConverterWithCardLayout mainPanel = new NumberConverterWithCardLayout();

      JFrame frame = new JFrame("Number Converter Application");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class BinaryPanel extends JPanel {
   public static final String NAME = "Binary";
   private static final int PREF_W = 500;
   private static final int PREF_H = 400;

   public BinaryPanel() {
      setName(NAME);
      add(new JLabel("A complex GUI that does binary calculations will go here"));
   }

   @Override
   // just to give it some size
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }
}

class OctalPanel extends JPanel {
   public static final String NAME = "Octal";

   public OctalPanel() {
      setName(NAME);
      add(new JLabel("A GUI that does octal calculations will go here"));
   }

}

class HexadecimalPanel extends JPanel {
   public static final String NAME = "Hexadecimal";

   public HexadecimalPanel() {
      setName(NAME);
      add(new JLabel("A GUI that does hexadecimal calculations will go here"));
   }
}

class DecimalPanel extends JPanel {
   public static final String NAME = "Decimal";

   public DecimalPanel() {
      setName(NAME);
      add(new JLabel("A GUI that does decimal calculations will go here"));
   }

}

Of course the calculation JPanels would be much more involved, holding nested JPanels each with its own layout manager, JTextFields, JButtons, and whatever else would be needed to implement their functionality.


Edit 3
Actually, on thinking this over, even that is overkill. Your far better off using a single JPanel with two text fields, one for number entry and one for result display, that has a bunch of buttons at the bottom. Then the display will change depending on which button (which type of conversion) is pressed. KISS principle.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • thank you very much sir!! now i'll try to use JPanels and then will embed them into this code, i didn't know about cardLayout before, – Hassan Zia Sep 13 '14 at 18:46
  • @HassanZia: actually you're better off not using CardLayout, but instead have a look at Edit 3. – Hovercraft Full Of Eels Sep 13 '14 at 18:50
  • i already have made some programs which use a single JPanle to display dfrnt JPanels in it (embedding several classes to a single window) but that was only embedding not swaping. anyways sir i'd try to learn about card layout and swaping of windows – Hassan Zia Sep 13 '14 at 19:05