【问题标题】:How to properly add textarea to tabbedpane如何正确地将 textarea 添加到 tabbedpane
【发布时间】:2017-09-12 15:35:24
【问题描述】:

我有一个任务是创建一个类似于 Gedit 的多选项卡编辑器。所以我使用了 JTabbedPane 并在其构造函数中添加了 JTextArea。我在使用方法时遇到问题 textarea.cut();其中 textarea 是 textarea ,就像用户创建新标签一样,用户必须能够实现剪切、复制、粘贴。所以我使用了 tabbedPane.getSelectedComponent()。但是现在它说组件不能转换为 jTextArea 所以我使用了类型转换它。问题是我没有得到预期的输出,即它没有正确添加选项卡我的问题是如何添加这些以干净有效的方式将组件添加到选项卡式窗格。任何替代方法都非常受欢迎。

这是我的代码的 sn-ps。

         //components declared in class Editor which extends Jframe
        JTextArea textarea ;
        JScrollPane scrollpane ;
        JTabbedPane tabbedpane ;

        public Editor(){

    this.setLayout(new FlowLayout());
    tabbedpane = new JTabbedPane();
    tabbedpane.addTab("File",textarea);
    add(tabbedpane);
    scrollpane = new JScrollPane(tabbedpane);
    getContentPane().add(scrollpane, BorderLayout.CENTER);

    //content in my constructor

   //also contains other components but are not shown here. 
   } //end constructor



        //add new Tabs
          newfile = new JMenuItem("New File");
           file.add(newfile);
           newfile.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                   tabbedpane = new JTabbedPane();
                   tabbedpane.addTab("File",textarea);
                   add(tabbedpane);
                  scrollpane = new JScrollPane(tabbedpane);
                  getContentPane().add(scrollpane, BorderLayout.CENTER);
            }//end actionPerformed
           });//end method new 

           this.add(tabbedpane, BorderLayout.CENTER);



             //added cut as JMenuItem to Menu edit Which is then added toJMenuBar



                cut = new JMenuItem("Cut");
                edit.add(cut);
                cut.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ActionEvent){

            JTextArea txtarea = new JTextArea();
            txtarea = (JTextArea)tabbedpane.getSelectedComponent();
                txtarea.cut();

        }//end actionPerformed

    });//end Method cut

【问题讨论】:

    标签: java jtextarea jtabbedpane


    【解决方案1】:

    Tab 键(选项卡名称)应该不同,并且您的 TabbedPane 应该只添加一次。

    //constructor
    public Editor() {
        tabs = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
        add(tabs, BorderLayout.CENTER);
    }
    
    //class method
    void addFile(String name) {
        tabs.addTab(name, new JScrollPane(new TextArea()));
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-31
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      相关资源
      最近更新 更多