我有一个带有自定义选项卡的JTabbedPane,它显示文件名,后跟一个按钮。按下按钮时,我想关闭该选项卡。我的第一个想法是(希望)当我点击按钮时,它会首先切换到该选项卡,然后我就可以关闭该索引处的选项卡。然而事实并非如此。我正在寻找一种方法来检索按钮所在的选项卡索引,然后我可以关闭该选项卡。我尝试过研究并想出了indexOfComponent
,但我不确定如何在我的情况下使用它。我的标签是动态创建的,因此我将内容存储在矢量中,创建JPanels,然后根据所选索引显示当前信息。 (tab 0将包含vec [0],tab 1 = vec [1]等内部的所有组件)。
我的TextEdit类设置如下:
public class TextEdit extends JTabbedPane {
private Vector<JTextArea> vec; // User can make and edit files
private Vector<JPanel> tabPanel; // Panel that has a JLabel for fileName and JButton to close file
private Vector<JLabel> absolutePath; // Path to which file will be saved
public TextEdit() {
// Sets up actionlisteners, initializes variables, etc
}
protected void AddTab(String fileName) {
JPanel panel = new JPanel; // Where textarea will be
panel.setLayout(new GridLayout(0,1));
JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);
panel.add(sp);
JPanel tp = new JPanel(); // The tab panel
tp.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 2));
JLabel label = new JLabel(fileName);
JButton button = new JButton("X");
button.addActionListener(CloseOne); // My Action that will close the file
tp.add(label);
tp.add(button);
this.addTab(fileName, panel); // Sets the text area into the tab
this.setTabComponentAt(this.getSelectedIndex, tp); // Sets the tab to the fileName and button
vec.add(ta); // Add textarea to vector for future use
tabPanel.add(tp); // Add the tabpanel for future use. this is where the button is, I need to setSelectedIndex to the tab that the button resides onclick
}
text editor.Java
Action CloseOne = new AbstractAction("CloseOne") {
@Override
public void actionPerformed(ActionEvent e) {
// This is where I need to set the selected tab to the tab in which the button was pressed.
}
};
TextEditor类是我的所有操作,并持有TextEdit(标签等所在的位置)。
我的textedit有方法来设置和获取所选索引。
回到indexOfComponent,我需要指定我正在使用的组件,但是,我的组件是动态添加的,我必须弄清楚selectedindex进入vector或JPanels甚至使用它。或者我错过了什么?有什么建议?
在AddTab方法中,将actionCommand设置为关闭按钮,作为新添加的选项卡的索引,如下所示
JButton button = new JButton("X");
button.setActionCommand( "" + tabPanel.size() );
button.addActionListener(CloseOne);
在TextEdit类中添加removeTabComponentAtmethod
public void removeTabComponentAt( int index ) {
vec.removeElementAt(index );
tabPanel.removeElementAt(index );
this.removeTabAt( index );
}
在“关闭”操作中,获取单击按钮的索引
Action CloseOne = new AbstractAction("CloseOne") {
public Component getTextEdit ( Component comp) {
if( comp instanceof TextEdit ) {
return ( TextEdit ) comp;
}
if( comp.getParent() != null ) {
return getTextEdit ( comp.getParent() );
} else {
return null;
}
}
@Override
public void actionPerformed(ActionEvent e) {
String indexStr = e.getActionCommand();
int index=-1;
try {
index = Integer.parseInt( indexStr );
} catch( NumberFormatException ex ) {
}
if( index > -1 ) {
TextEdit textEdit = getTextEdit( ( Component ) e.getSource() ) ;
if( textEdit != null ) {
textEdit.removeTabComponentAt( index );
}
}
}
};