Nae*_*ghi 8 java swing renderer jcombobox right-align
我想要一个右对齐的JComboBox.我怎样才能做到这一点?有人说"你可以设置一个渲染器到JComboBox,它可以是一个JLabel有JLabel #setHorizontalAlignment(JLabel.RIGHT)",但我不知道怎么办呢?
cam*_*ckr 16
有人说"你可以设置一个渲染器到JComboBox,它可以是一个JLabel,有JLabel#setHorizontalAlignment(JLabel.RIGHT)"
是的,默认的renederer是JLabel,因此您无需创建自定义渲染器.你可以使用:
((JLabel)comboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);
Run Code Online (Sandbox Code Playgroud)
好吧,你可以使用ListCellRenderer,如下所示:
import java.awt.Component;
import java.awt.ComponentOrientation;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class ComboboxDemo extends JFrame{
public ComboboxDemo(){
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setRenderer(new MyListCellRenderer());
comboBox.addItem("Hi");
comboBox.addItem("Hello");
comboBox.addItem("How are you?");
getContentPane().add(comboBox, "North");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private static class MyListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
component.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
return component;
}
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ComboboxDemo().setVisible(true);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8699 次 |
| 最近记录: |