我有一个JList,允许您选择“取消”哪些选项。单击取消按钮后,JLabel将打印出已取消的选项。但是,当我尝试测试代码,并选择选项并单击“取消”时,JLabel不打印任何内容。所以我假设取消按钮的ActionListener不起作用。我在下面列出了相关代码:
public class WarehouseInterface extends JFrame{
private JFrame frame;
public WarehouseInterface(){
frame = new JFrame("Warehouse Interface");
DefaultListModel demoList = new DefaultListModel();
HashMap<String, Job> jobHashMap = SharedInformation.jobs;
int i = 0;
ArrayList<String> jobIDs = new ArrayList<>();
Iterator it = jobHashMap.entrySet().iterator();
while (it.hasNext() && i < 10) {
Map.Entry pair = (Map.Entry)it.next();
Job job = (Job) pair.getValue();
String jobID = job.getID();
demoList.add(i, jobID);
jobIDs.add(jobID);
i++;
}
JList list = new JList(demoList);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
list.setCellRenderer(new CheckList());
JButton cancel = new JButton("Cancel");
cancel.setFont(new Font("Serif", Font.PLAIN, 14));
JPanel panel2 = new JPanel();
panel2.setLayout(new GridLayout(2,0));
panel2.add(list);
panel2.add(cancel);
JPanel panel3 = new JPanel();
panel3.setLayout(new GridLayout(3,0));
panel3.add(label3);
ActionListener cancelListener = new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
for(int index : list.getSelectedIndices()) {
String jobID = (String) demoList.get(index);
JLabel cancelledJobLabel = new JLabel(jobID);
cancelledJobLabel.setPreferredSize(new Dimension(50, 20));
cancelledJobLabel.setFont(new Font("Serif", Font.PLAIN, 18));
cancelledJobLabel.setOpaque(true);
panel3.add(cancelledJobLabel);
//ERROR HERE :(
}
}
};
cancel.addActionListener(cancelListener);
frame.add(panel2, BorderLayout.CENTER);
frame.add(panel3, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
class CheckList extends JLabel implements ListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean hasFocus) {
setComponentOrientation(list.getComponentOrientation());
if (isSelected) {
setBackground(Color.RED);
setForeground(Color.WHITE);
// unselected, and not the DnD drop location
} else {
setBackground(Color.WHITE);
setForeground(Color.BLACK);
};
setOpaque(true);
setEnabled(list.isEnabled());
setFont(list.getFont());
setText(value.toString());
return this;
}
}
答案 0 :(得分:3)
panel3.add(cancelledJobLabel);
当您向可见的GUI添加/删除组件时,基本代码为:
panel.add(...);
panel.revalidate();
panel.repaint();
revalidate()
调用布局管理器。否则组件的大小为(0,0),因此无需绘制任何内容。