![](/img/trans.png)
[英]How do i get the particular data into the combo box from txt file in Java swing
[英]How do I combine a Combo Box with a Tree in Swing?
我想我可以將其實現為JViewPort中的JTree組件,然后是一個擴展按鈕。 折疊時,它看起來像一個組合框。 單擊展開按鈕時,視口將展開,從而允許您滾動並選擇JTree中的節點。 當您選擇節點時,查看端口將折疊回只顯示所選節點和擴展按鈕。
嘿,你猜怎么着! 這是你的幸運日。
我過去曾經使用過這個框架。 非常完整。 我不知道他們已經有這個了。
替代文字http://img89.imageshack.us/img89/8324/combotreejj1.png
不太昂貴,但是您將需要一些時間來了解API(這並不復雜,但是他們已經創建了很多新東西)
重寫getListCellRendererComponent方法並按級別順序創建組件。 對於每個樹級別,將繪制的字符串向右移動3個空格。
例:
1個
。 一種
。 b
2
。 C
您可以從中看到的原始實現
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
//Get the selected index. (The index param isn't
//always valid, so just use the value.)
int selectedIndex = ((Integer)value).intValue();
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
//Set the icon and text. If icon was null, say so.
ImageIcon icon = images[selectedIndex];
String pet = petStrings[selectedIndex];
setIcon(icon);
if (icon != null) {
setText(pet);
setFont(list.getFont());
} else {
setUhOhText(pet + " (no image available)",
list.getFont());
}
return this;
}
您可以創建一個ComboBoxEditor,其組件(由getEditorComponent返回)是一個JTree。
盡管您可能已經嘗試過了。
我不知道會是什么樣子。 如果可以,請發布屏幕截圖。 :)
編輯
我快速嘗試一下。 它很糟糕,但是只是一個開始。
替代文字http://img120.imageshack.us/img120/2563/yiakxk2.png
這是代碼,物有所值。 :(
可能您應該開始考慮替代方案。 假的Combo是一個JButton,它在按下隱藏面板時沒有邊框,將與顯示的樹一起出現。
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class ComboTree {
public static void main( String [] args ) {
JComboBox c = new JComboBox( new String [] { "Hello", "there"});
c.setModel( new CustomComboModel() );
c.setEditor( new TreeComboEditor() );
c.setRenderer( new TreeComboEditor() );
JFrame frame = new JFrame();
frame.add( c , BorderLayout.NORTH ) ;
frame.pack();
frame.setVisible( true );
}
}
class CustomComboModel implements ComboBoxModel {
public Object getSelectedItem() { return ":P"; }
public void setSelectedItem(Object anItem) {}
public void addListDataListener(ListDataListener l) {}
public Object getElementAt(int index) { return "at " + index ; }
public int getSize() { return 2; }
public void removeListDataListener(ListDataListener l) {}
}
class TreeComboEditor implements ComboBoxEditor, ListCellRenderer {
// Editor interface
public void addActionListener(ActionListener l) {}
public Component getEditorComponent() {
return new JTree() ;
}
public Object getItem() { return "";}
public void removeActionListener(ActionListener l) {}
public void selectAll() {}
public void setItem(Object anObject) {}
// Render interface
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
return new JTree();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.