简体   繁体   English

Java JScrollPane的事件处理程序

[英]Event handler of Java JScrollPane

I already have a custom control base on JList like this 我已经有一个像这样的基于JList的自定义控件

public class MyClass extends JList<String> {

   private DefaultListModel<String> items = new DefaultListModel<String>();

   public MyClass() {
      setModel(items);
   }

   public String getAAAA() { //code here.. }
   public int getBBB() { //code here... }
}

But I want the Jlist have scrollbar, so I change the super class of my custom control to JScrollPane and add the JList into it. 但是我希望Jlist具有滚动条,因此我将自定义控件的超类更改为JScrollPane并将JList添加到其中。 code like this 像这样的代码

public class MyClass extends JScrollPanel {

  private JList<String> list = new JList<String>();
  private DefaultListModel<String> items = new DefaultListModel<String>();

  public MyClass() { 
    list.setModel(items);
    this.setViewportView(list);
  }

  public String getAAAA() { //code here.. }
  public int getBBB() { //code here... }
}

Well, if MyClass extends JList, in the JFrame I can addMouseListener to MyClass object and in mouseClicked I compare the MouseEvent getSource is a instance of MyClass and call these method of MyClass. 好吧,如果MyClass扩展了JList,则可以在JFrame中将MouseListener添加到MyClass对象,并在mouseClicked中比较MouseEvent getSource是MyClass的实例,并调用MyClass的这些方法。

@Override    
public void mouseClicked(MouseEvent arg0)
{
    Object source = arg0.getSource();
    if (source instanceof MyClass)
    {
        String a = ((MyClass) source).getAAAA();
        int b = ((MyClass) source).getBBB();
    }
 }

But if MyClass extends JScrollPane, I add MouseListener to MyClass object and like above, in mouseClicked I compare the MouseEvent getSource instanceof MyClass and call these method (getAAA(), getBBB()...) but it's not working?? 但是,如果MyClass扩展了JScrollPane,则将MouseListener添加到MyClass对象中,就像上面一样,在mouseClicked中,我比较MyClass的MouseEvent getSource实例并调用这些方法(getAAA(),getBBB()...),但是它不起作用?

You likely do not want to extend JScrollPane. 您可能不想扩展JScrollPane。 You can add any Component to a JScrollPane to achieve having scroll bars. 您可以将任何Component添加到JScrollPane以实现具有滚动条。 JList is a component, so you can add it directly. JList是一个组件,因此您可以直接添加它。 There shouldn't be much you need to do. 您不需要做太多事情。

see: http://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html 参见: http : //docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM