I have an assignment to create a multitab editor something like Gedit .So I have used JTabbedPane and added JTextArea in its constructor . I am facing problem while using methods textarea.cut(); where textarea is textarea as if user creates new tab user must be able to implement cut,copy,paste. so I used tabbedPane.getSelectedComponent().But Now it says that component cannot be converted to jTextArea so I used typecasted it .The question is I am not getting the expected output i.e It is not adding tabs properly My question is How to add these components to tabbed pane in a clean and efficient way. Any alternative methods of doing it are most welcome.
Here is snippets of my code.
//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
Tab key (tab name) should differ, and your TabbedPane you should add only once.
//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()));
}