这是一个有助于暴露问题的测试用例。
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import junit.framework.TestCase;
public class JTabbedPaneTest extends TestCase {
private JTabbedPane pane;
private int count = 0;
protected void setUp() throws Exception {
pane = new JTabbedPane();
ChangeListener listener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JTabbedPane pane = (JTabbedPane)e.getSource();
int before = count;
count = pane.getTabCount();
System.out.println(String.format("%s --> %s", before, count));
}
};
pane.addChangeListener(listener);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
pane.add(panel1);
pane.add(panel2);
}
public void testOne() throws Exception {
assertEquals(1, count); // I actually expect 2
assertEquals(2, pane.getTabCount());
pane.remove(0);
pane.remove(0);
assertEquals(0, count);
assertEquals(0, pane.getTabCount());
}
public void testMany() throws Exception {
assertEquals(1, count); // I actually expect 2
assertEquals(2, pane.getTabCount());
pane.removeAll();
assertEquals(2, count); // I actually expect 0
assertEquals(0, pane.getTabCount());
}
}
我认为存在同步问题;输出是:
0 --> 1
1 --> 1
1 --> 0
0 --> 1
1 --> 2
看起来好像一些更改事件正在丢失。
更新:为后代保留它,但这是错误的;正如 mmyers 指出的那样,事件仅在选择更改时触发。