JList单元格中的JButton不可点击

JList单元格中的JButton不可点击,第1张

JList单元格中的JButton不可点击

尽管您无法获得与普通按钮单击相同的视觉效果,但以下示例似乎可行。也许某个绘画技巧比我更好的人可以改进此技巧来模拟视觉按下按钮效果。

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class JButtonListDemo implements Runnable{  private JList jlist;  public static void main(String args[])  {    SwingUtilities.invokeLater(new JButtonListDemo());  }  public void run()  {    Object[] items = new ButtonItem[] {        new ButtonItem("Apple"),        new ButtonItem("Banana"),        new ButtonItem("Carrot"),        new ButtonItem("Date"),        new ButtonItem("Eggplant"),        new ButtonItem("Fig"),        new ButtonItem("Guava"),    };    jlist = new JList(items);    jlist.setCellRenderer(new ButtonListRenderer());    jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);    jlist.setVisibleRowCount(5);    jlist.addMouseListener(new MouseAdapter()    {      @Override      public void mouseClicked(MouseEvent event)      {        clickButtonAt(event.getPoint());      }    });    Jframe frame = new Jframe();    frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);    frame.getContentPane().add(new JScrollPane(jlist));    frame.pack();    frame.setLocationRelativeTo(null);    frame.setVisible(true);  }  private void clickButtonAt(Point point)  {    int index = jlist.locationToIndex(point);    ButtonItem item = (ButtonItem) jlist.getModel().getElementAt(index);    item.getButton().doClick();//    jlist.repaint(jlist.getCellBounds(index, index));  }  public class ButtonItem  {    private JButton button;    public ButtonItem(String name)    {      this.button = new JButton(name);      button.addActionListener(new ActionListener()      {        @Override        public void actionPerformed(ActionEvent e)        {          System.out.println(button.getText() + " was clicked.");        }      });    }    public JButton getButton()    {      return button;    }    @Override    public String toString()    {      return button.getText();    }  }  class ButtonListRenderer extends JButton implements ListCellRenderer  {    public Component getListCellRendererComponent(JList comp, Object value, int index,      boolean isSelected, boolean hasFocus)    {      setEnabled(comp.isEnabled());      setFont(comp.getFont());      setText(value.toString());      if (isSelected)      {        setBackground(comp.getSelectionBackground());        setForeground(comp.getSelectionForeground());      }      else      {        setBackground(comp.getBackground());        setForeground(comp.getForeground());      }      return this;    }  }}

或者,您始终可以将JButton垂直地布置在JPanel上(也许使用新的GridLayout(0,1)),然后将JPanel放在JScrollPane中,从而模拟JButton的JList。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5142231.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存