- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we add different font style items to JList in Java?
A JList is a subclass of JComponent class and it can be used to display a list of objects that allows the user to select one or more items. A JList can generate a ListSelectiionListener interface and need to implement the abstract method valueChanged(). A DefaultListModel class provides a simple implementation of a list model, which can be used to manage items displayed by a JList control. We can add the items to a JList using the addElement() method of the DefaultListModel class, we can also add items with different fonts to JList using HTML tags like <b> for bold style text, <i> for italic style text, <u> for underlined style text etc.
Example
import java.awt.*; import javax.swing.*; public class JLabelListTest { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new JLabelListTest().makeUI(); } }); } public void makeUI() { String[] data = {"<html>Raja</html>", "<html><b>Adithya</b></html>", "<html><i>Jaidev</i> </html>", "<html><u>Chaitanya</u></html>"}; JList list = new JList(data); list.setBackground(Color.lightGray); JFrame frame = new JFrame(); frame.getContentPane().add(new JScrollPane(list), BorderLayout.NORTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
Output
Advertisements