Mudar a cor da linha JList em tempo de execução
-
13-09-2019 - |
Pergunta
Eu estou tentando alterar linhas JList dinamicamente. Eu preciso mudar de cor enésima linha, destaque-(n é desconhecido durante a compilação). Eu vi um monte de exemplos com ListCellRenderer costume, mas todos eram "estático".
Em outras palavras eu tenho JList com linhas x. Durante runtime meu "lógica de negócios" detecta enésima linha é importante. Então, eu quero fazer o seu fundo verde, espere um segundo, e depois torná-lo branco novamente. Só mais uma coisa, não wan seleção de linha mudança.
O que é a melhor maneira de fazê-lo?
Solução
Com base em amostra ListDemo de dom
Se você digitar algum texto no campo de texto que não está na lista e você acertar destaque ele é adicionado.
Se o texto está na lista e você acertar destaque a entrada na lista fica temporariamente destacado azul.
Observe a solução aqui com o campo de jogo é apenas para demonstração. Para a implementação mais correto considerar as outras idéias propostas e considerar o uso javax.swing.Timer
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ListDemo extends JPanel {
private JList list;
private DefaultListModel listModel;
public String match = null;
private static final String hireString = "Highlight";
private JTextField employeeName;
public ListDemo() {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("Test1");
listModel.addElement("Test2");
listModel.addElement("Test3");
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.setVisibleRowCount(5);
list.setCellRenderer(new MyListCellRenderer());
JScrollPane listScrollPane = new JScrollPane(list);
JButton hireButton = new JButton(hireString);
HireListener hireListener = new HireListener(hireButton);
hireButton.setActionCommand(hireString);
hireButton.addActionListener(hireListener);
hireButton.setEnabled(false);
employeeName = new JTextField(10);
employeeName.addActionListener(hireListener);
employeeName.getDocument().addDocumentListener(hireListener);
listModel.getElementAt(list.getSelectedIndex()).toString();
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane,
BoxLayout.LINE_AXIS));
buttonPane.add(Box.createHorizontalStrut(5));
buttonPane.add(employeeName);
buttonPane.add(hireButton);
buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
add(listScrollPane, BorderLayout.CENTER);
add(buttonPane, BorderLayout.PAGE_END);
}
class MyListCellRenderer extends JLabel implements ListCellRenderer {
public MyListCellRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList paramlist, Object value, int index, boolean isSelected, boolean cellHasFocus) {
setText(value.toString());
if (value.toString().equals(match)) {
setBackground(Color.BLUE);
SwingWorker worker = new SwingWorker() {
@Override
public Object doInBackground() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) { /*Who cares*/ }
return null;
}
@Override
public void done() {
match = null;
list.repaint();
}
};
worker.execute();
} else
setBackground(Color.RED);
return this;
}
}
class HireListener implements ActionListener, DocumentListener {
private boolean alreadyEnabled = false;
private JButton button;
public HireListener(JButton button) {
this.button = button;
}
public void actionPerformed(ActionEvent e) {
String name = employeeName.getText();
if (listModel.contains(name)) {
match = name;
list.repaint();
employeeName.requestFocusInWindow();
employeeName.selectAll();
return;
}
if (name.equals("")) {
Toolkit.getDefaultToolkit().beep();
employeeName.requestFocusInWindow();
employeeName.selectAll();
return;
}
int index = list.getSelectedIndex();
if (index == -1)
index = 0;
else
index++;
listModel.insertElementAt(employeeName.getText(), index);
employeeName.requestFocusInWindow();
employeeName.setText("");
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
}
public void insertUpdate(DocumentEvent e) {
enableButton();
}
public void removeUpdate(DocumentEvent e) {
handleEmptyTextField(e);
}
public void changedUpdate(DocumentEvent e) {
if (!handleEmptyTextField(e))
enableButton();
}
private void enableButton() {
if (!alreadyEnabled)
button.setEnabled(true);
}
private boolean handleEmptyTextField(DocumentEvent e) {
if (e.getDocument().getLength() <= 0) {
button.setEnabled(false);
alreadyEnabled = false;
return true;
}
return false;
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("ListDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new ListDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() { createAndShowGUI(); }
});
}
}
Outras dicas
Simples, definir um ListCellRenderer personalizado para seu JList usando:
list.setCellRenderer(myListCellrenderer);
Agora, dentro do método substituído getListCellRendererComponent () fazer algo como isto:
public Component getListCellRendererComponent(.....) {
Component c = super.getListCellRendererComponent();
c.setBackGround(Color.blue)
return c;
}
O exemplo acima assume que o seu costume renderizador overrid DefaultListCellRenderer
Seu ListCellRenderer personalizado, que implementa o método getListCellRendererComponent
, terá acesso a ambos os JList
eo valor que está Redering. Isto dá-lhe algumas opções de como determinar quando pintar a n th verde consecutivas:
- Você poderia subclasse
JList
e têm o renderizador de pedi-lo que a cor a ser usada para o bg. A subclasseJList
poderia desencadear uma repintura quando a lógica de negócios determina que é tempo para o n th fila para ser verde, e, em seguida, iniciar um balançoTimer
para desencadear uma repaint retornando o bg volta ao normal - Quando a lógica de negócios determina quando você deve mostrar a linha como o verde, você também tem a opção de definir estado no objeto de apoio da linha, e testá-lo para esse Estado dentro
getListCellRendererComponent
, definindo a verde bg se o estado for corrigir. Novamente, você tem a opção de definir umTimer
balanço para reverter o estado no objeto de apoio.