[英]How to add a custom checkbox into JList (Java)?
This is how the program looks: 该程序的外观如下:
This is how I want it to look: 这就是我想要的样子:
As you can see in the picture I have tried a bit and learned that I need to use ListCellRenderer
, but the problem is i have created 2 custom png files 如您在图片中看到的,我已经尝试了一下,并了解到我需要使用
ListCellRenderer
,但是问题是我创建了2个自定义png文件
checked.png and Checked.png和
unchecked.png unchecked.png
when I click daily goals #1
it should give state = true
and checked.png
should appear and stay checked unless I click it again. 当我点击每日
goals #1
它应该设置为state = true
并且checked.png
应该出现并保持选中状态,除非再次单击它。 Unchecked.png
could be standard on the jList column
. Unchecked.png
可能是在标准jList column
。
I also want to place my checkbox 1 cm to the left of the end of the row (padding) not sure hows its done in java sadly. 我也想将我的复选框放置在行尾(填充)的左侧1厘米,不确定如何在Java中完成它。 (You'll understand better by looking at the picture)
(通过查看图片,您会更好地理解)
After looking through some guides I have learned that the only way to add extra stuff to a JList column
is by using ListCellRenderer
. 看了一些指南之后,我了解到向
JList column
添加额外内容的唯一方法是使用ListCellRenderer
。 I have tried quite a while with no success so thought of asking others. 我尝试了很长时间没有成功,所以想到了问别人。 Does anyone have any ideas on how to do this?
有人对如何执行此操作有任何想法吗?
The thought was to get it to work then display in a JTable by changing the Jtable column to Daily goals and displaying X to indicate the goal was achieved. 想法是让它工作,然后通过将Jtable列更改为Daily目标并显示X来表示已实现目标,从而在JTable中显示。 But I think I should be able to do this, The main question is the custom checkbox implementation.
但是我认为我应该能够做到这一点,主要的问题是自定义复选框的实现。
Note to override the text in the checkbox to the actual list cell value 注意将复选框中的文本覆盖为实际的列表单元格值
public class TestFrame extends JFrame { ImageIcon iconChecked = new ImageIcon(TestFrame.class.getResource("checked.png")); ImageIcon iconUnchecked = new ImageIcon(TestFrame.class.getResource("unchecked.png")); JList jList = new JList(new Object[]{"ABC", "123"}); public TestFrame() { this.add(jList); jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); jList.setCellRenderer(new ListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { for (int i : list.getSelectedIndices()) { if (index == i) { JCheckBox checkBoxChecked = new JCheckBox(value.toString(), iconChecked); return checkBoxChecked; } } JCheckBox checkBoxUnchecked = new JCheckBox(value.toString(), iconUnchecked); return checkBoxUnchecked; } }); }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.