E
E
Elnurhan2019-07-23 23:14:00
Java
Elnurhan, 2019-07-23 23:14:00

How to change text color in JList on button click?

I am writing a simple ToDo List.
You need to make it so that when you click on the "Done" button, the text in the JList becomes green
Here is the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

public class Window extends JFrame {

    private JTextField input = new JTextField("");
    private JButton addBtn = new JButton("Добавить");
    private JButton deleteBtn = new JButton("Удалить");
    private JButton completeBtn = new JButton("Выполнено");
    private ArrayList<String> missions = new ArrayList<>();
    private DefaultListModel<String> dlm = new DefaultListModel<String>();
    private JList<String> list = new JList<String>(dlm);

    Window() {
        super("ToDo List");
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setBounds(100,100,600,200);
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(5, 3));
        addBtn.addActionListener(new AddActionListener());
        deleteBtn.addActionListener(new DeleteActionListener());
        container.add(input);
        container.add(addBtn);
        container.add(deleteBtn);
        container.add(completeBtn);
        container.add(new JScrollPane(list));
        setVisible(true);
    }

    class AddActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            dlm.add(dlm.getSize(), input.getText());
        }
    }

    class DeleteActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            dlm.remove(list.getSelectedIndex());
        }
    }

    class CompleteActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Не знаю как реализовать данный класс
        }
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Moseychuk, 2019-07-24
@Elnurhan

https://docs.oracle.com/javase/7/docs/api/javax/sw...
You need to implement your renderer and set it to a list.
The renderer receives information about the cell and returns the component with which this cell should be drawn.
The component does not have to be re-created each time. It's normal practice to draw all cells with one component instance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question