class MyCellRenderer extends JLabel implements ListCellRenderer {
public MyCellRenderer() {
setOpaque(true)
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
setBackground(isSelected ? Color.BLUE : Color.LIGHT_GRAY)
setHorizontalAlignment(SwingConstants.CENTER)
setText(value.toString())
return this
}
}
可以居中显示。实现方法为
将ComboBox.DrawMode设置为DrawMode.OwnerDrawFixed,
对ComboBox的DrawItem事件编程,各个项目居中显示。
具体步骤如下:
(1)在Visual Studio中创建一个“Windows 窗体应用程序”项目。在Form1上布置一个ComboBox控件
(2)Form1窗体代码Form1.cs
using System.Drawingusing System.Windows.Forms
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent()
// 允许代码重新绘制,固定大小
comboBox1.DrawMode = DrawMode.OwnerDrawFixed
string[] items = {
"项目",
"项目 1",
"项目 10",
"项目 100",
"项目 1000",
"项目 10000"
}
comboBox1.Items.AddRange(items)
}
// 将comboBox1中的项目居中显示!
private void comboBox1_DrawItem(object sender,
DrawItemEventArgs e)
{
string s = this.comboBox1.Items[e.Index].ToString()
// 计算字符串尺寸(以像素为单位)
SizeF ss = e.Graphics.MeasureString(s, e.Font)
// 水平居中
float left = (float)(e.Bounds.Width - ss.Width) / 2
if (left < 0) left = 0f
float top = (float)(e.Bounds.Height - ss.Height) / 2
// 垂直居中
if (top < 0) top = 0f
top = top + this.comboBox1.ItemHeight * e.Index
// 输出
e.DrawBackground()
e.DrawFocusRectangle()
e.Graphics.DrawString(
s,
e.Font,
new SolidBrush(e.ForeColor),
left, top)
}
}
}
(3)运行效果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)