简体   繁体   English

选项卡式面板中未显示TextArea

[英]TextArea not showing in the Tabbed Panel

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. 这是扩展JFrame的主要类。 In this app there is created as soon as the app starts: 在此应用程序启动后,将立即创建该应用程序:

  • a JMenu ( The edit menu) JMenu(编辑菜单)
  • a Jmenu ( The file menu; the menu my user goes to open the file. ) Jmenu(文件菜单;我的用户用来打开文件的菜单。)
  • a JMenuBar ( containing the 2 JMenus ) 一个JMenuBar(包含2个JMenus)
  • a JTabbedPane ( which does not show up when the app starts ) JTabbedPane(在应用启动时不显示)

Here is the code for the Main.java file. 这是Main.java文件的代码。 This is the main file which extends JFrame 这是扩展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. 以下是OpenAction.java文件的代码。 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. 我从代码中期望的是,当用户按下open(File-> Open)时,我将看到一个选项卡出现,其中有一个可滚动的空白文本区域。 What I am now getting is just a tab with the name of the file (which is good ) but no textarea. 我现在得到的只是带有文件名的选项卡(很好),但没有textarea。

My question is why doesn't my textarea appear in my panel. 我的问题是为什么我的文本区域没有出现在面板中。

Thank you 谢谢

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 将文本区域添加到面板后,在面板上调用revalidate()和repaint()

  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. GroupLayout引起问题。 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. 这样,框架就可以使用默认的BorderLayout,并且选项卡式窗格将添加到CENTER。

I then changed the panel to use the default FlowLayout: 然后,我将面板更改为使用默认的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. 我建议您手动构建GUI,以更好地了解布局管理器的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM