Problem with code, possibly multiple extensions of JFrame

  • Context: Java 
  • Thread starter Thread starter BiGyElLoWhAt
  • Start date Start date
  • Tags Tags
    Code Java Multiple
Click For Summary

Discussion Overview

The discussion revolves around a programming issue related to the implementation of multiple JFrame extensions in a Java text editor application. Participants explore the challenges faced when integrating an ExitOption class that also extends JFrame, particularly regarding the visibility and functionality of GUI components.

Discussion Character

  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant describes a problem where the ExitOption JFrame does not display its JLabel or buttons when instantiated within the main text editor project, despite working correctly in a standalone project.
  • Another participant references a Stack Overflow discussion suggesting that using multiple JFrames is generally not considered good practice, as it complicates the application structure.
  • A participant expresses confusion over why the ExitOption class behaves differently in the main project compared to a standalone project, noting issues with the add() methods and the close button functionality.
  • Some participants assert that best practices suggest using one JFrame per application, while acknowledging that multiple frames can be implemented under certain conditions, as indicated by a tutorial link shared in the discussion.

Areas of Agreement / Disagreement

There is no consensus on the best approach to using multiple JFrames, with some participants advocating for a single JFrame while others point out that multiple frames can be used effectively under certain circumstances. The discussion remains unresolved regarding the specific issue faced by the original poster.

Contextual Notes

Participants mention limitations related to the handling of GUI components and the behavior of JFrame instances, but do not resolve the underlying issues or assumptions about the code structure.

BiGyElLoWhAt
Gold Member
Messages
1,637
Reaction score
138
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
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.
 

Similar threads

  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 14 ·
Replies
14
Views
6K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 15 ·
Replies
15
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
Replies
1
Views
2K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K