Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java Problem with code, possibly multiple extensions of JFrame

Tags:
  1. Feb 14, 2017 #1

    BiGyElLoWhAt

    User Avatar
    Gold Member

    I am making a simple text editor program. You can load, save and exit, and other things.
    I have the loading and saving working, but the exiting is giving me a peculiar problem. In my project, I have a gui class that extends JFrame, and I also have an ExitOption class that extnds JFrame. I am convinced that this is the root of my problem. When I create an instance of exitoption, It loads a box, with the title, but not my JLabel or my two buttons (ok and cancel). However, I made a new project with a class ExitOption, copied all of my ExitOption code from my other project to ExitOption project, and it works fine (the buttons don't do anything, actually, I am handling that in my gui class). Literally the same code, with the addition of a main method that has 2 lines
    ExitOption eO = new ExitOption();
    eO.setVisible(true);
    Any idea what's up?

    Code (Java):
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.Toolkit;
    import java.awt.event.*;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;

    @SuppressWarnings("serial")
    public class TextBoxGUI extends JFrame implements ActionListener{
     
        private TextAreaPanel tAP;
        private JPanel text;
        private JPanel right;
        @SuppressWarnings("unused")
        private JPanel fileMenu;
     
        private JButton add;
        private JButton remove;
        private JMenuBar menuBar;
        private JMenu menu;
        private JMenuItem save;
        private JMenuItem load;
        private JMenuItem exit;
        private JMenuItem rgb;
        JFileChooser fc;
        Browse browse;
        Scanner s;
     
        Dimension screenSize;
        double width;
        double height;
     
     
     
        public TextBoxGUI()
        {
            browse = new Browse();
            setTitle("Simple Wordpad");
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
     
            /*
             * Get values for screen resolution and center the GUI with
             * 1/32 of screen height above and below and 1/4 of screen
             * width to the left and right.
             */

     
            screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            width = screenSize.getWidth();
            height = screenSize.getHeight();
            setBounds((int)  width/4, (int) height/32, (int) width/2, (int) ( 15*height/16));
     
            tAP = new TextAreaPanel("",(int) width/2 - 50,(int) (height*15/16)-75);

            /*
             * Create Stuff
             */

     
            text = new JPanel(new GridLayout());
            right = new JPanel(new GridLayout());
            fileMenu = new JPanel();
     
            text.add(tAP);
     
            /*
             * Add Buttons for adding colors and add action listeners to said buttons
             */

     
            add = new JButton("Add");
            remove = new JButton("Remove");
            add.addActionListener(this);
            remove.addActionListener(this);
     
            /*
             * Create the File Menu and subsidiaries
             */

     
            menuBar = new JMenuBar();
            menu = new JMenu("File");
            menu.setMnemonic(KeyEvent.VK_F);
     
            save = new JMenuItem("Save");
            save.setMnemonic(KeyEvent.VK_S);
            save.addActionListener(this);
     
            load = new JMenuItem("Load");
            load.setMnemonic(KeyEvent.VK_D);
            load.addActionListener(this);
     
            exit = new JMenuItem("Exit");
            exit.setMnemonic(KeyEvent.VK_X);
            exit.addActionListener(this);
     
            menu.add(save);
            menu.add(load);
            menu.add(exit);
     
            menu.getAccessibleContext().setAccessibleDescription(
                    "The only menu in this program that has menu items");
            menuBar.add(menu);
     
            add(text,BorderLayout.CENTER);
            add(menuBar,BorderLayout.NORTH);
            add(right,BorderLayout.EAST);
     
     
     
     
     
     
        }
        //Main Method, obviously.
        public static void main(String args[]){
     
            TextBoxGUI box = new TextBoxGUI();
            box.setVisible(true);
     
     
        }
     
     
     
        /*
         * Waits for stuff to happen, then does stuff accordingly.
         */

        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == load) {
                File file = browse.load(menu); //Call load
                //System.out.println("Load");
                loadText(file); //call load text with the file from load (Browse)

            }
            else if(e.getSource() == save)
            {
                browse.save(menu,tAP.getText());
            }
            else if(e.getSource() == exit)
            {
                ExitOption eO = new ExitOption();
                eO.setVisible(true);
                while(!eO.isSelected()){}
                if(eO.getC().equals(eO.ok))
                {
                    eO.dispose();
                    System.exit(0);
                }
                else if(eO.getC().equals(eO.cancel))
                {
                    eO.dispose();
                }
                else eO.dispose();
            }
        }
     
     
        /*
         * This method gets a file from the load method of the Browse class.
         * Tries to make a scanner in f, clears the text panel, and adds all
         * the text from the file line by line. This literally just adds text
         * to tAP (TextAreaPanel Object).
         */

     
     
        private void loadText(File f)
        {
            try{
                s = new Scanner(f);
                tAP.clearText();
                while(s.hasNextLine())
                {
                    String stuff = s.nextLine();        
                    tAP.appendText(stuff);
                }
                s.close();
            }
            catch(FileNotFoundException fnf){
                System.out.println("File Not Found");
                //loadText(browse.load(menu));
            }
            catch(Exception e){
         
            }
     


     
        }
     

     


    }
     
    Code (Java):
    import javax.swing.JPanel;
    import javax.swing.*;


    import java.awt.Dimension;

    @SuppressWarnings("serial")
    public class TextAreaPanel extends JPanel {

        private JScrollPane scrollPane;
        private JTextArea textArea;
        private String text;
        private int width = 500;
        private int height = 500;
     
     
     
        public TextAreaPanel()
        {
            text = "";
            textArea = new JTextArea(text,20,20);
            textArea.setLineWrap(true);
     
            scrollPane = new JScrollPane(textArea);
            scrollPane.setPreferredSize(new Dimension(width,height));
     
            add(scrollPane);
     
        }
     
        public TextAreaPanel(String t,int w, int h)
        {
            text = "";
            height = h;
            width = w;
     
            textArea = new JTextArea(t,20,20);
            textArea.setLineWrap(true);
     
            scrollPane = new JScrollPane(textArea);
            scrollPane.setPreferredSize(new Dimension(width,height));
     
            add(scrollPane);
        }
     
        public String getText(){
     
            text = textArea.getText();
            return text;
        }
     
        public void setText(char c)
        {
            text = text + c;
        }
        public void appendText(String s)
        {
            textArea.append(s + "\n");
        }
     
        public void clearText()
        {
            textArea.setText("");
        }
     
        public void setHeight(int h)
        {
            height = h;
        }
     
        public void setWidth(int w)
        {
            width = w;
        }
     
     
     
    }
     
    Code (Java):
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;

    @SuppressWarnings("unused")
    public class Browse{
     


        JFileChooser fc;
     
        public Browse()
        {
            fc = new JFileChooser();
            fc.setCurrentDirectory(new File("./Files"));
        }
     
        public File load(Component c)
        {
            File f = new File("");
            int returnVal = fc.showOpenDialog(c);
     
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                f = fc.getSelectedFile();
         
                //System.out.println(f.toString());
            }
     
            return f;
        }
     

     
        public void save(Component c,String s)
        {
            int returnVal = fc.showSaveDialog(c);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                try{
                FileWriter fw = new FileWriter(file);
                fw.write(s);
                fw.close();
                }
                catch(Exception e){System.out.println("idk what you did, but you ****ed up");}
         
         
            }
        }



     

    }
     
     
    Code (Java):
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    //import java.awt.TextField;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.WindowConstants;

    @SuppressWarnings("serial")
    public class ExitOption extends JFrame implements ActionListener{
     
        Component c;
        boolean selected = false;
     
        JPanel buttons;
        JPanel center;
     
        JButton ok;
        JButton cancel;

        JLabel text;
        //String option = "";
     
        public ExitOption()
        {
     
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            double width = screenSize.getWidth();
            double height = screenSize.getHeight();
            setBounds((int)  width/2-200, (int) height/2-200, 400 , 400);
     
            setTitle("Are you sure you want to exit?");
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            //setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
     
            buttons = new JPanel(new GridLayout(1,2));
            center = new JPanel(new GridLayout(1,1));
     
            ok = new JButton("OK");
            cancel = new JButton("Cancel");
     
     
     
            //final String lostData = "Any unsaved data will be lost!";
            text = new JLabel("Any unsaved data will be lost!");
     
            buttons.add(ok);
            buttons.add(cancel);
            center.add(text);
     
            ok.addActionListener(this);
            cancel.addActionListener(this);
     
     
            this.add(buttons,BorderLayout.SOUTH);
            this.add(center);
     
     
     
        }

        public boolean isSelected(){return selected;}
        public Component getC(){return c;}

     
        /*
         * Didn't need selfDestruct. I can call ExitOption.dispose();
         */

     
        //public void selfDestruct()
        //{
        //    this.dispose();
        //}
     
     
        @Override
        public void actionPerformed(ActionEvent ee) {
            if(ee.getSource() == ok)
            {
                c = ok;
                selected = true;
         
            }
            else if(ee.getSource() == cancel){
                c = cancel;
                selected = true;
            }
     
        }

    }
     

    Literally just tag this in the bottom of the exit option class and it works in a new project.
    Code (Java):
        public static void main(String args[])
        {
            ExitOption eO = new ExitOption();
            eO.setVisible(true);
        }
    What I get when I run as part of my text project vs. standalone.
    ExitOption_newProject.png ExitOption_textBoxProject.png

    Also, I should mention, in Browse, I set the default folder to "./Files".
    If you don't have that folder, I'm not sure what it will do, probably just default to the home container or whatever it's called. You can fix that by making it setCurrentDirectory(new File("."))
     
    Last edited: Feb 14, 2017
  2. jcsd
  3. Feb 14, 2017 #2

    jedishrfu

    Staff: Mentor

  4. Feb 14, 2017 #3

    BiGyElLoWhAt

    User Avatar
    Gold Member

    Well, there they just talk about why it's good practice or not, it seems. I don't understand why it works in a standalone project but not when implemented with something else. It's almost as if my add() methods aren't doing anything. I've tried adding in this.add(), I just tried removing the JFrame extension and creating one called j, then adding all functions as j.add(). None of it is working. But it works just fine when you make a new project. What's more, when implemented with my text box gui, the close button doesn't work. WTF? I actually have to kill the program in eclipse to get the exit dialog to close out.
     
  5. Feb 14, 2017 #4

    jedishrfu

    Staff: Mentor

  6. Feb 14, 2017 #5

    jedishrfu

    Staff: Mentor

    I think the bottom line is one jframe per application is the best practices approach.

    https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html

    However, according to this tutorial it can be done and here's an example for you to analyze:

    https://www.eduonix.com/blog/java-programming-2/learn-to-create-multiple-frames-java/

    User clicks on button and a new frame is opened. Both are using JFrame.DISPOSE_ON_CLOSE action.
     
  7. Feb 15, 2017 #6

    jedishrfu

    Staff: Mentor

    Did this help?
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Problem with code, possibly multiple extensions of JFrame
  1. Fortran code problem (Replies: 2)

Loading...