Question

I'm trying to make a small text editor. When someone presses on a sub-item in my menu (File -> Open )

This is the main class which extends JFrame. In this app there is created as soon as the app starts:

  • a JMenu ( The edit menu)
  • a Jmenu ( The file menu; the menu my user goes to open the file. )
  • a JMenuBar ( containing the 2 JMenus )
  • a JTabbedPane ( which does not show up when the app starts )

Here is the code for the Main.java file. This is the main file which extends JFrame

import java.awt.Container;
import java.awt.List;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;



/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *

 */
public class Main extends javax.swing.JFrame {

    /**
     * Creates new form Main
     * 
     * 
     * 
     */



    public Main() {

        initComponents();
        OpenAction action = new OpenAction("Open File Chooser",new Integer(KeyEvent.VK_0),"Open",tabbedPanel);
        JMenuItem openFileChooser = new JMenuItem(action);
        fileMenu.add(openFileChooser);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        tabbedPanel = new javax.swing.JTabbedPane();
        menu = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        editMenu = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        fileMenu.setText("File");
        menu.add(fileMenu);

        editMenu.setText("Edit");
        menu.add(editMenu);

        setJMenuBar(menu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tabbedPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 781, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tabbedPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 437, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenuBar menu;
    private javax.swing.JTabbedPane tabbedPanel;
    // End of variables declaration                   
}

The following is the code for the OpenAction.java file. It is the one handling the events:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFileChooser;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 *
 */
public class OpenAction extends AbstractAction {
    JScrollPane text_panel;
    JTextArea textarea;
    JTabbedPane cont;
    JComponent pan;


    public OpenAction(String desc,int mnemonic,String title,JTabbedPane cont_to)
    {

     super(title);
     cont = cont_to;
     putValue(SHORT_DESCRIPTION,desc);
     putValue(MNEMONIC_KEY,mnemonic);

    }

    @Override
    public void actionPerformed(ActionEvent ae) {


         JFileChooser fs = new JFileChooser();
         fs.showOpenDialog(fs);

         File fileChoosed = fs.getSelectedFile();
         String nameOfFile = fileChoosed.getName();

         addToTabbedMenu(nameOfFile);

    }
        private void addToTabbedMenu(String nameOfFile)
        {
        pan = new JPanel();      
        pan.setLayout(new GridLayout(20,20));

        textarea = new JTextArea("Random");
        text_panel = new JScrollPane(textarea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        pan.add(text_panel);
        cont.addTab(nameOfFile,pan);

        }



}

What I'm expecting from my code is when the user press on open ( File -> Open ) I will see a tab appear there is a empty textarea which is scrollable. What I am now getting is just a tab with the name of the file (which is good ) but no textarea.

My question is why doesn't my textarea appear in my panel.

Thank you

Was it helpful?

Solution

Why do you have a separate method to add the text area to the panel?

I'm guessing the problem is that the tab is made visible BEFORE you add the text area to the panel on the tab. So you need to do one of two things:

  1. Invoke revalidate() and repaint() on the panel after you add the text area to the panel

  2. Keep you code for creating the panel in one place. That is create the panel and the label and the text area to the panel at the same time. This is the easy solution from a code design.

Edit

The GroupLayout is causing a problem. I changed the following:

/*
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tabbedPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 781, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tabbedPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 437, Short.MAX_VALUE))
        );
        pack();
*/
        add(tabbedPanel);
        setSize(400, 400);

So that the frame just used the default BorderLayout and the tabbed pane will be added to the CENTER.

I then changed the panel to use the default FlowLayout:

//pan.setLayout(new GridLayout(20,20));

and the text area now displays. I suggest you build GUI's manually to better understand how layout managers work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top