Как я могу сделать некоторые объекты в ListBox полужирными?

Новый, поскольку 1.8 - это метод List.sort () вместо использования Collection.sort (), поэтому вы вызываете mylistcontainer.sort ()

. Вот фрагмент кода, который демонстрирует List.sort ():

List<Fruit> fruits = new ArrayList<Fruit>();
fruits.add(new Fruit("Kiwi","green",40));
fruits.add(new Fruit("Banana","yellow",100));
fruits.add(new Fruit("Apple","mixed green,red",120));
fruits.add(new Fruit("Cherry","red",10));

// a) using an existing compareto() method
fruits.sort((Fruit f1,Fruit f2) -> f1.getFruitName().compareTo(f2.getFruitName()));
System.out.println("Using String.compareTo(): " + fruits);
//Using String.compareTo(): [Apple is: mixed green,red, Banana is: yellow, Cherry is: red, Kiwi is: green]

// b) Using a comparable class
fruits.sort((Fruit f1,Fruit f2) -> f1.compareTo(f2));  
System.out.println("Using a Comparable Fruit class (sort by color): " + fruits);
// Using a Comparable Fruit class (sort by color): [Kiwi is green, Apple is: mixed green,red, Cherry is: red, Banana is: yellow]

Класс Fruit:

public class Fruit implements Comparable<Fruit>
{
private String name;
private String color;
private int quantity;

public Fruit(String name,String color,int quantity)
{ this.name = name; this.color = color; this.quantity = quantity;}

public String getFruitName() { return name; }        
public String getColor() { return color; }  
public int getQuantity() { return quantity; }

@Override public final int compareTo(Fruit f) // sorting the color
{
    return this.color.compareTo(f.color);
}     
@Override public String toString()
{   return (name + " is: " + color);
}

} // конец класса Fruit

14
задан Chris Hanson 3 December 2008 в 04:32
поделиться

1 ответ

Необходимо изменить DrawMode поля списка на DrawMode. OwnerDrawFixed. Проверьте эти статьи о MSDN:
Перечисление DrawMode
ListBox. Графика События
DrawItem. Метод DrawString

Также взгляд на этот вопрос на форумах MSDN:
Вопрос на объектах ListBox

А простой пример (оба объекта - Black-Arial-10-Bold):

 public partial class Form1 : Form
 {
    public Form1()
    {
        InitializeComponent();

        ListBox1.Items.AddRange(new Object[] { "First Item", "Second Item"});
        ListBox1.DrawMode = DrawMode.OwnerDrawFixed;
    }

    private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground();
        e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), new Font("Arial", 10, FontStyle.Bold), Brushes.Black, e.Bounds);
        e.DrawFocusRectangle();
    }
 }
30
ответ дан 1 December 2019 в 08:53
поделиться