JButton不响应单击事件 [英] JButton not Responding to Click Events

查看:104
本文介绍了JButton不响应单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的应用程序要求使用JList,其中每个ListItem是一个Label,然后是一个Button.

An application i am working on requires the use of a JList where each ListItem is a Label followed by a Button.

我所做的是我创建了一个具有Text字段的String成员的Class,并将Class Objects添加到Jlist.

What i did is i created a Class having a String member for the Text field and added the Class Objects to the Jlist.

现在,对于Button,我实现了一个自定义列表单元格渲染器,它是:

Now for the Button,i implemented a Custom List Cell Renderer which is as :

    public renderer()
{
    text=new JLabel();
    button=new JButton("Track");
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            System.out.println("Hey");

        }
});
}

public Component getListCellRendererComponent(JList list, Object value, int index,boolean isSelected, boolean cellHasFocus)
{
    it=(item)list.getModel().getElementAt(index);
    text.setText(it.tex);
    return this;
}

public void paintComponent(Graphics g)
{
    this.add(text);
    this.add(button);
    this.setVisible(true);
}

public Dimension getpreferredSize(){
    Font font=UIManager.getDefaults().getFont("JLabel.Font");
    Graphics g=getGraphics();
    FontMetrics fm=g.getFontMetrics(font);
    return new Dimension(fm.stringWidth(it.tex)+button.getWidth(),fm.getHeight()>button.getWidth()?fm.getHeight():button.getWidth());
}
}

但是当我单击按钮时,该按钮没有响应.我错过了什么?

But the button is non responsive when i Click it.What did i miss?

谢谢

推荐答案

您也应该创建一个自定义列表单元格编辑器,它会重用ListCellRenderer中的代码进行外观,但在按钮上实现动作侦听器. 单元格渲染器仅用于在列表中标记图形图像.要在JList中使用控件,应使用单元格编辑器.

You should create a custom List Cell Editor too, wich reuses code from ListCellRenderer for looks, but implements action listener on button. The cell renderers are used just to stamp graphic images in list. For using controls in JList you should use cell editors.

这篇关于JButton不响应单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆