JavaでJComboBoxにセパレータを追加するにはどうすればよいですか?
-
02-07-2019 - |
質問
JComboBox を持っていますが、要素のリストに区切り記号を含めたいです。 Javaでこれを行うにはどうすればよいですか。
これが便利になるシナリオの例は、font-family-selectionのコンボボックスを作成する場合です。 WordおよびExcelのfont-family-selection-controlに似ています。この場合、最も使用頻度の高いフォントを上部に表示し、次にセパレーター、最後にセパレーターの下のすべてのフォントファミリーをアルファベット順に表示したいと思います。
誰でもこれを行う方法で私を助けることができますか、これはJavaでは不可能ですか?
解決
java2sでカスタムListCellRendererを使用する方法を示す例が含まれた非常に短いチュートリアルがあります。 http://www.java2s.com/Code/Java/Swing-Components /BlockComboBoxExample.htm
基本的に、リストモデルに既知のプレースホルダーを挿入し、ListCellRendererでプレースホルダーを検出すると、「new JSeparator(JSeparator.HORIZONTAL)」のインスタンスを返します
他のヒント
以下のコードを書いてテストする頃には、おそらくもっと良い答えがたくさんあるでしょう...
実験/学習を楽しんでいたので、私は気にしません(Swingの前面にはまだ少し緑があります)。
[編集] 3年後、私は少し緑が少なくなり、bobndrewの有効な発言を考慮しました。動作するキーナビゲーションに問題はありません(おそらくJVMバージョンの問題ですか?)。ただし、ハイライトを表示するようにレンダラーを改善しました。そして、より良いデモコードを使用します。受け入れられた答えはおそらくより良い(より標準的です)、カスタムセパレータが必要な場合はおそらく私の方が柔軟です...
基本的な考え方は、コンボボックスのアイテムにレンダラーを使用することです。ほとんどのアイテムでは、アイテムのテキストを含む単純なJLabelです。最後/最近使用したアイテムについては、JLabelの下部に線を描くカスタム境界線で装飾します。
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class TwoPartsComboBox extends JComboBox
{
private int m_lastFirstPartIndex;
public TwoPartsComboBox(String[] itemsFirstPart, String[] itemsSecondPart)
{
super(itemsFirstPart);
m_lastFirstPartIndex = itemsFirstPart.length - 1;
for (int i = 0; i < itemsSecondPart.length; i++)
{
insertItemAt(itemsSecondPart[i], i);
}
setRenderer(new JLRenderer());
}
protected class JLRenderer extends JLabel implements ListCellRenderer
{
private JLabel m_lastFirstPart;
public JLRenderer()
{
m_lastFirstPart = new JLabel();
m_lastFirstPart.setBorder(new BottomLineBorder());
// m_lastFirstPart.setBorder(new BottomLineBorder(10, Color.BLUE));
}
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
if (value == null)
{
value = "Select an option";
}
JLabel label = this;
if (index == m_lastFirstPartIndex)
{
label = m_lastFirstPart;
}
label.setText(value.toString());
label.setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());
label.setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
label.setOpaque(true);
return label;
}
}
}
セパレータークラス、太く、カスタムカラーなどを使用できます。
import java.awt.*;
import javax.swing.border.AbstractBorder;
/**
* Draws a line at the bottom only.
* Useful for making a separator in combo box, for example.
*/
@SuppressWarnings("serial")
class BottomLineBorder extends AbstractBorder
{
private int m_thickness;
private Color m_color;
BottomLineBorder()
{
this(1, Color.BLACK);
}
BottomLineBorder(Color color)
{
this(1, color);
}
BottomLineBorder(int thickness, Color color)
{
m_thickness = thickness;
m_color = color;
}
@Override
public void paintBorder(Component c, Graphics g,
int x, int y, int width, int height)
{
Graphics copy = g.create();
if (copy != null)
{
try
{
copy.translate(x, y);
copy.setColor(m_color);
copy.fillRect(0, height - m_thickness, width - 1, height - 1);
}
finally
{
copy.dispose();
}
}
}
@Override
public boolean isBorderOpaque()
{
return true;
}
@Override
public Insets getBorderInsets(Component c)
{
return new Insets(0, 0, m_thickness, 0);
}
@Override
public Insets getBorderInsets(Component c, Insets i)
{
i.left = i.top = i.right = 0;
i.bottom = m_thickness;
return i;
}
}
テストクラス:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class TwoPartsComboBoxDemo extends JFrame
{
private TwoPartsComboBox m_combo;
public TwoPartsComboBoxDemo()
{
Container cont = getContentPane();
cont.setLayout(new FlowLayout());
cont.add(new JLabel("Data: ")) ;
String[] itemsRecent = new String[] { "ichi", "ni", "san" };
String[] itemsOther = new String[] { "one", "two", "three" };
m_combo = new TwoPartsComboBox(itemsRecent, itemsOther);
m_combo.setSelectedIndex(-1);
cont.add(m_combo);
m_combo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String si = (String) m_combo.getSelectedItem();
System.out.println(si == null ? "No item selected" : si.toString());
}
});
// Reference, to check we have similar behavior to standard combo
JComboBox combo = new JComboBox(itemsRecent);
cont.add(combo);
}
/**
* Start the demo.
*
* @param args the command line arguments
*/
public static void main(String[] args)
{
// turn bold fonts off in metal
UIManager.put("swing.boldMetal", Boolean.FALSE);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JFrame demoFrame = new TwoPartsComboBoxDemo();
demoFrame.setTitle("Test GUI");
demoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demoFrame.setSize(400, 100);
demoFrame.setVisible(true);
}
});
}
}
カスタム ListCellRenderer
を使用して、セパレーター項目を異なる方法で描画できます。 を参照してください。 docs と小さなチュートリアル。