Killing JFrames in a JFrame

Hi,
I have a few JFrames popping up in my program with GUI stuff in it, what i want to do is to use the 'OK' / 'CANCEL' buttons i put in the JFrames to work, i.e. 'Cancel' should kill the internal JFrame and 'Ok' should do something with my inputted values and then exit, any help greatly appreciated :)

Hi there
Why exactly are yo using JFrames when you easily use a JOptionPane.showConfirmDialog(...) to get input from your users?
This saves you the over-head of hiding the dialog after receiving the input.
The ICEMAN

Similar Messages

  • Please help - JFrame, menu, another JFrame, setBackground

    I am trying to make a simple program that draws a JFrame with a menu. The menu has one item, which when selected draws another JFrame. That JFrame has a button, which when pressed changes the background color. Many hours have gone into this, despite the fact that I made a similar program a few weeks ago.
    The compiler complains about the method getContentPane, when I remove that, it runs and draws the first window, but the menu item does not make the second window. Also, the setDefaultCloseOperation confuses the compiler as well.
    Please help.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MenuAction2
    public static void main(String[] args) 
         MainWindow window = new MainWindow("Menu action example");
      //window.setDefaultCloseOperation.(JFrame.EXIT_ON_CLOSE);
         window.setVisible(true);      
    class MainWindow extends JFrame
         MainWindow(String title)
         super(title);
         getContentPane.setLayout(new BorderLayout());
         Toolkit theKit = getToolkit();          
         Dimension wndSize = theKit.getScreenSize();  
         setBounds(0, 0,wndSize.width, wndSize.height);
         setJMenuBar(menuBar);
         fileMenu = new JMenu("File");
         connectItem = new JMenuItem();
         connectItem = fileMenu.add("Connect...");
         connectItem.addActionListener(menuHandler = new Handler());
         menuBar.add(fileMenu);
         getContentPane.add(toolBar, BorderLayout.NORTH);  
    class Handler implements ActionListener
         public void actionPerformed(ActionEvent e)
          win = new ConnectWindow("Connect to Database");
          getContentPane().add(win, BorderLayout.NORTH);
          setVisible(true);
      private JMenu fileMenu;
      private JMenuItem connectItem;
      private JMenuBar menuBar = new JMenuBar(); 
      private JToolBar toolBar = new JToolBar();
      private Handler menuHandler;
      private ConnectWindow win;
    class ConnectWindow extends JFrame
         ConnectWindow(String title)
              super(title);
              setSize(200,200);
              setLayout(new BorderLayout());
              JButton connectB = new JButton("Connect");
              connectB.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        setBackground(Color.red);
              add(connectB,BorderLayout.SOUTH);
              setVisible(true);
    }

    getContentPane is a method so you should use it that way:
    getContentPane().setLayout(new BorderLayout());
    getContentPane.add(new Button("Ok"));

  • JFrame calling a JFrame....

    Hello,
    I was trying to create a JFrame which has a BorderLayout() and there is a button set at the SOUTH of the layout of this JFrame........
    Now when I click on this button..... this event would create another JFrame which also has a BorderLayout() and a button located at its SOUTH......
    Now the problem is that when I click on the button of the first JFrame, it creates another JFrame as expected but it does not create the button at the SOUTH of this new JFrame...... How do I overcome this problem......
    The code is given below..........
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TT extends JFrame implements ActionListener
         JButton but;
         public TT()
              setLayout(new BorderLayout());
              but=new JButton();                    
              but.addActionListener(this);
              add(but,BorderLayout.SOUTH);
         public void actionPerformed(ActionEvent ae)
              JFrame jj=new JFrame();          
              JButton jb=new JButton();
              jj.setLayout(new BorderLayout());
              jj.setSize(100,100);
              jj.setLocation(300,300);
              jj.setVisible(true);
              add(jb,BorderLayout.SOUTH);
         public static void main(String args[])
              TT obj=new TT();
              obj.setSize(400,400);
              obj.setLocation(200,200);
              obj.setVisible(true);
    }It would be highly appreciated if anybody who knows the answer would take the PAIN of answering this question....... Thank you in advance.......

    Hai,
    Execute this modified code. It's executing perfectly. U better assign some text to the button.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TT extends JFrame implements ActionListener
         JButton but;
         public TT()
              getContentPane().setLayout(new BorderLayout());
              but=new JButton();                    
              but.addActionListener(this);
              getContentPane().add(but,BorderLayout.SOUTH);
         public void actionPerformed(ActionEvent ae)
              JFrame jj=new JFrame();          
              JButton jb=new JButton();
              jj.getContentPane().setLayout(new BorderLayout());
              jj.setSize(100,100);
              jj.setLocation(300,300);
              jj.setVisible(true);
              jj.getContentPane().add(jb,BorderLayout.SOUTH);
         public static void main(String args[])
              TT obj=new TT();
              obj.setSize(400,400);
              obj.setLocation(200,200);
              obj.setVisible(true);
    }rgds,
    rdRose

  • Open a jFrame on another jFrames close

    New to java
    I have 2 jFrames, frame1.java & frame2.java
    frame1 has a button which makes frame1 invisible and opens frame2.
    I can do the above.
    but when I close frame2 I want to re-open frame1.
    I do not want to use a button on frame2, I want to use the X at the top right of the jFrame.
    I'm using NetBeans 6.1
    Please help
    Thanks

    Recommended: don't use 2 JFrames, use one JFrame and make the second a modal JDialog.
    But if you must do it this way, take a look at WindowListener#windowClosing.
    In future (not this time), Swing related questions should be posted in the [Swing forum|http://forums.sun.com/forum.jspa?forumID=57]
    db

  • How to resize the components in a JFrame when the JFrame Resizes?

    Hi all,
    i have some problems with my app. I have set the JFrame resizable and that works fine for the JFrame but not for the components in the JFrame.
    So my question is how can i set the components in a JFrame to resize automatically when the JFrame resizes?
    Here are the important things from my code,...if you need more, just let me know, its my first post in a forum .
    Its a JFrame with a JTabbedPane and on the Tabs are Panels with buttons and Tables.
    Thank you in advance!
    public class MainMonitor extends JFrame {
    public MainMonitor() {
              super();
              initialize();
              setVisible(true);
         private void initialize() {
              this.setSize(1145, 785);
              this.setIconImage(Toolkit.getDefaultToolkit().getImage("Images/c.gif"));
              this.setContentPane(getJContentPane());
              this.setTitle("Company Manager");
              this.setResizable(true);
              this.setLocationRelativeTo(null);
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.setOpaque(true);
                   jContentPane.add(getJTabbedPane(), null);
                   jContentPane.add(getJPanel11(), null);
              return jContentPane;
         private JTabbedPane getJTabbedPane() {
              if (jTabbedPane == null) {
                   jTabbedPane = new JTabbedPane();
                   jTabbedPane.setLocation(new Point(6, 69));
                   jTabbedPane.setSize(new Dimension(1120, 684));
                   jTabbedPane.addTab("P", null, getJPanel(), null);
                   jTabbedPane.addTab("K", null, getJPanel1(), null);
                   jTabbedPane.addTab("B", null, getJPanel2(), null);
              return jTabbedPane;
         

    Giasaste wrote:
    Thanks a lot, i didnt knew that the Layout Manager is a must.It's not a must, but it is the way to allow your app to be resized nicely and makes it much easier to maintain and enhance your program. Imagine creating a complex gui then later decide that you want another radiobutton and to remove a jlabel / jtextfield pair. with layout managers a chore becomes easy.

  • Launching a JFrame from another JFrame

    Hi,
    I have a JFrame containing a menu(buttons). When I click on a button, I want that it launches another JFrame.
    I tried making use of the code
    Process p = Runtime.getRuntime().exec("java CreateStudentRecord");
    where CreateStudentRecord is the JFrame I want to launch. however this did not work.
    Can anyone help me find out how I can launch another JFrame when I click on a button within another JFrame.
    Thanks,
    Rahul.

    How about just using the following:
    private CreateStudentRecord csr;
    JButton b1 = new JButton("New Student Record");
    b1.addActionListener( new ActionListener() {
         public void actionPerformed(ActionEvent e){
              csr = new CreateStudentRecord().show();
    Rick

  • JFrame calling another JFrame

    Hello,
    I have a simple question:
    2 java files with 2 JFrames in them
    JFrame1(Cars.java) calls JFrame2(AddCar.java) from actionlistener.
    What I think is wrong is JFrame1 actionListener:
    if(ae.getSource() == CarEdit_btn){
    AddCar objEditAddCar = new AddCar();
    objEditAddCar.EditCar();
    And JFrame2's EditCar() method:
    public void EditCar(){
    AddCar windowAddCar1 = new AddCar();
    windowAddCar1.setTitle("Add Car");
    windowAddCar1.pack();
    windowAddCar1.show();
    AddCarMilage_txt.setText("544");
    The problem is that AddCarMilage_txt.setText("544"); doesnt update the value of the JTextField of JFrame2.
    Any ideas? Thanks
    Or another way to go around for me is, how do I use args[] from main inside the constructor?

    read this:
    http://forum.java.sun.com/thread.jspa?threadID=5199666&messageID=9792440#9792440
    it has also 2 classes and updates the textfield of the other class just copy and paste the code.

  • A JFrame calling another JFrame running a Thread

    Hi,
    here is my problem: I have an instance of Frame1 (extending JFrame) containing a button. When this button is clicked, a new instance of Frame2 (extending JFrame too) is created. The constructor of this Frame2 then calls the run method of an implementation of Runnable (called MyThread). For the purpose of this example I put a simple incrementation of a counter in the run method of the thread.
    The goal is to stop the incrementation by clicking anytime on the stop button of Frame2, hence ending the thread.
    When I create a new instance of Frame2, it works fine and I am able to end the thread, but when I create an instance of Frame1, the application freezes and I don't get any control on Frame2.
    The code for those classes is:
    public class Frame1 extends JFrame implements ActionListener{
         public static void main(String[] args) {
              new Frame1();
         public Frame1(){
              getContentPane().setLayout(new GridLayout(1,1));
              JButton b = new JButton("Run");
              b.addActionListener(this);
              getContentPane().add(b);
              setVisible(true);
              setSize(400,400);          
         public void actionPerformed(ActionEvent e) {
              Frame2 f= new Frame2();
    public class Frame2 extends JFrame implements ActionListener{
         MyThread t;
         boolean running = true;
         public Frame2(){
              getContentPane().setLayout(new GridLayout(1,1));
              JButton b = new JButton("Stop");
              b.addActionListener(this);
              getContentPane().add(b);
              setVisible(true);
              setSize(200,200);          
              t = new MyThread();
              t.run();
         public void actionPerformed(ActionEvent e) {
              t.setRunning(false);
    public class MyThread implements Runnable{
         boolean running = true;
         public void run(){
              int count = 0;
              while(isRunning())
                   count++;
              System.out.println("Last count: "+count);
         public boolean isRunning() {
              return running;
         public void setRunning(boolean running) {
              this.running = running;
    One thing I have tried is to make Frame2 implementing Runnable, but it didn't work. Any idea how to get the control on Frame2?
    Thanks

    You are calling t.run() and you really should be using t.start(). The code inside run() in MyThread is not running in a separate thread, so the call that you make to t.run() never returns.

  • JFrame opening 2 JFrame

    I have an app that does some lengthy processing so I create new Thread that does the processing and also opens a new JFrame that provides a JProgressBar visual of it's progress.
    GUI problem:
    How to control where this new JFrame opens up. Users have requested that the new JFrame open over the old JFrame or at least near, which it sometimes does.
    How do you control where on desktop a new JFrame will open?
    Any ideas?

    You need to override the show method
    The following show centers the window on the desktop.
    public void show()
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frame = this.getSize();
    int x = screen.width/2 - frame.width/2;
    int y = screen.height/2 - frame.height/2;
    this.pack();
    this.setLocation(x, y);
    super.show();

  • Bind Child JFrame to Parent JFrame

    Is there anyway of creating a JFrame that could have another JFrame attached to it? I don't so much mean an JInternalFrame, because what I need is a separate window (a properties window) that shows the user information, but doesn't register with the OS as a new window (i.e. place itself in the Windows taskbar). As far as I know, a JInternalFrame will actually be limited to the bounds of the JFrame containing it. I want mine to be a fully separate window, just bound to the parent window.
    Is it possible to do this by making both windows JInternalFrames and adding them both to a JDesktopPane???
    Thanks in advance for the help.

    What's with all those asterisks in your code? They're very distracting and prevent us from using your code.
    Anyway, the second window should be a JDialog, not a JFrame. I have to wonder why you call initComponents twice? Perhaps by doing so, the components displayed are not the ones with actionListeners added. It's hard to say not being able to run and test your code. Can you code Swing without using NetBeans code generation? If so, you should create a simpler example of this, one that we can run and test, and let us see exactly what is wrong. If you can't do this, then it would be worth your while to learn more Swing from the Sun/Oracle tutorials as this will serve you well in the long term.

  • JFrame 1 and JFrame 2

    Need help please.....
    how to send a text from jTextField1 of JFrame 1 to jTextField2 of JFrame 2? i'm using netbeans.... thanks..

    use something like this....
    public class frame1 extends JFrame{
        private JTextField text1;
        public frame1(){
            text1 = new JTextField();
            JButton button = new JButton("My Button");
            text1.setText("hello world!!!");
            add(text1);
            add(button);
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    new frame2(this).setVisible(true);
        public String getText(){
            return text1.getText();
    public class frame2 extends JFrame{
        public frame2(frame1 frame){
            JTextField text1 = new JTextField();
            text1.setText(frame.getText());
            add(text1);
    }

  • How to go one jFrame to another JFrame after click on button?

    I am having two frames loginFrame.java and UserinfoFrame.java.
    In loginFrame.java to click on login button i want to goto UserinfoFrame
    (LogInSuccessPanel).
    private void bnLoginActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    int loginCounter=0;
    this.remove(jPanel2);
    LogInSuccessPanel login = new LogInSuccessPanel();
    this.add(login);
    update();
    //if(evt.getSource()=="login")
    // while(loginCounter <= 5)
    if(!login(jTextField1.getText(), new String(jPasswordField1.getPassword()))) {
    loginCounter++;
    System.out.println("UserName : "+jTextField1.getText()) ;
    System.out.println("Password : "+jPasswordField1.getPassword());
    if(loginCounter >= 6) {
    System.out.println("Unable to Login");
    connectToDB();
    if(jTextField1.equals("UserName"))
    //Check Whether username is existing in DB
    private void connectToDB() {
    try{
         Class.forName("com.mysql.jdbc.Driver");
    Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
    Statement stmt = con.createStatement();
    ResultSet rset = stmt.executeQuery("SELECT UserName from login table");
    jTextField1.setText("Connected to the Database. Fetching Values from login Tables.\n");
    StringBuffer allRowValues = new StringBuffer();
    int counter=1;
    if (rset.next())
    //allRowValues.append("ROW " + counter + ": Username = " + rset.getString(1) + " & Password = " + rset.getString(2) + "\n");
    //counter++;
    System.out.println(" LOGIN SUCCESSFUL ");
    System.out.println("Username : " + rset.getString("username"));
    System.out.println("Password " + rset.getString("password"));
    System.out.println(" LOGIN SUCCESSFUL ");
    else
    System.out.println(" LOGIN FAILED ");
    // .setText(allRowValues.toString());
    rset.close();
    stmt.close();
    con.close();
    } catch (SQLException ex) {
    System.out.println("Connection Error = " + ex.toString());
    ex.printStackTrace();
    }catch(ClassNotFoundException e){
         System.out.println("Error in loading class" + e);
    private boolean login(String name, String pwd) {
    int count=0;
    if(count<=5)
    count++;
    return true;
    else return false;
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Login().setVisible(true);
    Thanks and regards

    search results for
    login
    http://onesearch.sun.com/search/onesearch/index.jsp?charset=UTF-8&qt=login&rf=0&rt=1&site=dev&nh=10&cs=0&col=developer-forums&dftab=siteforumid%3Ajava57&chooseCat=javaall&subCat=siteforumid%3Ajava57

  • Disable mouse or get fullscreen jframe in linux

    I am trying to create a login screen that will grant a user access to a particular application. For the login screen, I would like the ability to make the jframe run at fullscreen. I am able to do this on windows, but can't duplicate it on ubuntu linux. Since I am unable to get the code below to work on linux, maybe someone knows another way to get the same effect, or would it be possible to turn off the use of the mouse, not only on the jframe, but on the system itself?
    Thanks for the help.
    public static void main(String[] args) {
    // initialize the Graphic device to default one
            final GraphicsDevice myDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    // create the frame
            final JFrame test = new JFrame("Login Screen");
    // set recomended attributes
            test.setResizable(false);
            test.setUndecorated(true);
    // test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // we don't really need this because no mouse close is provided
            test.addKeyListener(new KeyAdapter() {
                @Override
                public void keyReleased(KeyEvent e) {
                    super.keyReleased(e);
    // code to kill off other events such as ALT-F4 on windows should go here
    // lets provide a way out for now
                    if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                        myDevice.setFullScreenWindow(null);
                        test.dispose();
                        System.exit(0);
           System.out.println("before full screen");
    // query for supported
            if (myDevice.isFullScreenSupported()) {
                System.out.println("full screen supported");
                try {
                    myDevice.setFullScreenWindow(test);
                } catch (Exception e) {
    // if something goes wrong kill the window get back to desktop
                    myDevice.setFullScreenWindow(null);
                    e.printStackTrace();
        }

    Hi,
    I am not an expert and am trolling this site hoping to find the answer to my problem. However, I think that I might know the answer to this one.
    Open a site that has a flash application in it (like a you tube video). Right click on the flash window, select settings, and click the check box that selects "Enable hardware acceleration".  Doing this should improve the speed of video playback.
    Of course, it has done nothing for me since upgrading to Flash version 10.1, but it might work better for you.
    William

  • Browser reload increses the number of open JFrames

    Hey guys,
    this is funny.... I have an JApplet... it opens two JFrame's.... this works fine... but when I am reloading the browser (firefox or safari) I have 4 frames.... reload... 6 frames.... reload 8 frames....
    Reload invokes the destroy() method... and actually the applet and all its resources should be away.... but it isnt?!
    I tried to memorize all my open JFrame's and to invoke .dispose() or .removeAll() on them if the destroy() method is called... but nuthing!
    Really... I am confused.. can anybody help me, please!
    SA.

    That's easy.. try this please:
    public class HahaApplet extends JApplet {
         private Image im;
         public void init() {
              JFrame frame1 = new JFrame();
              JFrame frame2 = new JFrame();
              frame1.setSize(100, 200);
              frame2.setSize(500, 500);
              frame1.setVisible(true);
              frame2.setVisible(true);
    }after you deployed it with a html file and tried to open it with your browser... press several times the reload button... and the frames will be popuplating your whole screen! ;-)
    I meant with memorizing, that I hold a reference to all my open frames in my real application... when the browser invokes the destroy method i could invoke on all my frames dispose() or removeAll() to make sure the frame are killed from the heap. But nothing helps... frames are coming like snow in the alps!
    Thank you.

  • Problem with threads in JFrame

    Hy everyone...i have a small problem when i try to insert clock in my JFrame , because all i get is an empty text field.
    What i do is that i create inner class that extends Thread and implements Runnable , but i dont know ... i saw some examples on the intrnet...but they are all for Applets...
    Does any one know how i can implement this in JFrame (JTextField in JFrame).
    Actually any material on threads in JFrame or JPanel would be great....THNX.

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

Maybe you are looking for