2016-05-12 45 views
1

我有兩個組合框他們每個人的篩選我的JTable的diferent行,我想要做的是十個分量上的每個用戶選擇我的過濾器,綁定兩個JComboBox的過濾器

在此刻

首先組合框選擇選項A和過濾僅顯示選項表阿

第二組合框選擇選項B和表過濾僅顯示選項B

我需要的是:

首先組合框選擇選項A和過濾顯示用於選擇匹配的情況下表A中

然後

第二組合框選擇選項B和表必須顯示值第一個組合框和第二個組合框的匹配大小寫顯示選項'A + B'

這是我的組合框代碼,用於過濾單個表:

comboBox.addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent event) { 
     RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox.getSelectedItem().toString(), 2); 
     sorter.setRowFilter(rf); 
    } 
}); 

comboBox_1.addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent event) { 
     RowFilter<DefaultTableModel, Object> rf = RowFilter.regexFilter(comboBox_1.getSelectedItem().toString(), 3); 
     sorter.setRowFilter(rf);     
    } 
}); 

那麼,有沒有一種方式,當選擇一個選項時總是匹配從兩個組合框的情況?

回答

2

使用RowFilter.andFilter()允許多個過濾器應用於單個JTableAND邏輯(僅當過濾器是真的,該項目將顯示出來)(也有一個ORNOT,...)。

沒有測試過,但我想這樣的事情可以工作:

// Collection of filters to be applied to your table 
List<RowFilter<DefaultTableModel, Object>> filters = new ArrayList<>(); 

comboBox.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent event) { 
     if(filters.isEmpty()) 
      filters.add(RowFilter.regexFilter(comboBox.getSelectedItem().toString(), 2)); 
     else 
      filters.set(0, RowFilter.regexFilter(comboBox.getSelectedItem().toString(), 2)); 
     // Apply filters 
     sorter.setRowFilter(RowFilter.andFilter(filters)); 
    } 
}); 

comboBox_1.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent event) { 
     if(filters.size() < 2) 
      filters.add(RowFilter.regexFilter(comboBox_1.getSelectedItem().toString(), 3)); 
     else 
      filters.set(1, RowFilter.regexFilter(comboBox_1.getSelectedItem().toString(), 3)); 
     // Apply filters 
     sorter.setRowFilter(RowFilter.andFilter(filters));   
    } 
}); 
+0

OMG,這是完美的正是我需要非常感謝你! –

0

您可以使用這樣的事情,它使用的ComboBoxModel這樣你就可以動態地添加元素到你的JComboBox:

Integer[] optionsForA = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; 
JComboBox comboBoxA = new JComboBox(optionsForA);//A 
Vector comboItems = newVector(); 
comboItems.add("A"); 
comboItems.add("B"); 
comboItems.add("C"); 
comboItems.add("D"); 
comboItems.add("E"); 
final DefaultComboBoxModel mod = new DefaultComboBoxModel(comboItems); 
JComboBox comboBoxB = new JComboBox(mod);//B 

actionsCB.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) { 
      if()//your condition { 

       for (int i = numbers.lenght; i < numbers.length + mod.size() ; i++) { 
        mod.addElement(optionsForA[i]); //add options from A to B 

       }    
      } 
     } 
    }); 

欲瞭解更多有關添加選項到JComboBox中動態地看看這個帖子:Dynamically adding items to a JComboBox 還是DefaultComboBoxModel API這裏:https://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultComboBoxModel.html

希望它有幫助!