Problem with code, possibly multiple extensions of JFrame

In summary, the conversation discusses the development of a simple text editor program with features such as loading, saving, and exiting. The individual is facing a problem with the exiting function and suspects it to be related to their use of JFrame classes. They have tried implementing the ExitOption class in a standalone project, which works fine, but not when integrated with the text editor program. The conversation also touches on the topic of best practices for using multiple JFrames in an application. Links to discussions and tutorials on the subject are also shared.
  • #1
BiGyElLoWhAt
Gold Member
1,622
131
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?

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){
     
        }
  
    }
 

 }
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;
    }
 
 
 
}
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");}
     
     
        }
    }
 

}
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.
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:
Technology news on Phys.org
  • #3
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.
 
  • #6
Did this help?
 

FAQ: Problem with code, possibly multiple extensions of JFrame

1. What is a JFrame in Java?

A JFrame is a class in the Java Swing library that represents a window in a graphical user interface (GUI). It is used to create and display a window with various components, such as buttons, text fields, and images.

2. How do I add multiple extensions of JFrame in my code?

To add multiple extensions of JFrame, you can create a new class that extends the JFrame class and add your desired components and functionality to it. Then, in your main class, you can create instances of this new class and add them to your JFrame using the add() method.

3. What are some common problems with code involving multiple extensions of JFrame?

Some common problems with code involving multiple extensions of JFrame include conflicting components, improper use of layout managers, and incorrect event handling. It is important to carefully plan and organize your code to avoid these issues.

4. How can I debug issues with my code involving multiple extensions of JFrame?

To debug issues with your code involving multiple extensions of JFrame, you can use debugging tools such as breakpoints and print statements to track the flow of your program and identify any errors. It is also helpful to test your code with different inputs and scenarios to catch any potential issues.

5. Are there any alternative solutions to using multiple extensions of JFrame?

Yes, there are alternative solutions to using multiple extensions of JFrame. One option is to use a single extension of JFrame and create separate classes for each component, adding them to the main JFrame as needed. Another option is to use a different GUI library, such as JavaFX, which offers different approaches to creating and managing windows and components.

Similar threads

Replies
5
Views
2K
Replies
2
Views
1K
Replies
5
Views
2K
Replies
7
Views
2K
Replies
2
Views
1K
Back
Top