1

我正在尝试一种不同的方法只是为了练习目的。我知道这似乎很荒谬。我的目标是在构造函数初始化时检索数字数组。但我做不到。我怎样才能做到这一点?

public class Myclass  extends JPanel{
 String[]num={"1","2","3"};

public Myclass() {
    JList list=new JList(new mymodel(num));
    JScrollPane pane=new JScrollPane(list);
      add(pane);

}
class mymodel extends DefaultListModel{

    public mymodel(String[] numbers) {
        super();
    }


}
public static void  main(String...args){
JFrame  frame=new JFrame();
frame.setContentPane(new d());
frame.setVisible(true);
frame.setSize(300,300);
    }
}
4

1 回答 1

1

一种方法是遍历数组,将每个元素添加到ListModel. 另外,考虑用MyPanel extends JPanel返回 a 的方法替换JPanel

private static class MyModel extends DefaultListModel {

    public MyModel(String[] numbers) {
        for (String string : numbers) {
            this.addElement(string);
        }
    }
}

图片

SSCCE

import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

/**
 * @see http://stackoverflow.com/a/17904479/230513
 */
public class Test {

    private static class MyPanel extends JPanel {

        String[] num = {"1 One", "2 Two", "3 Three"};

        public MyPanel() {
            this.setLayout(new GridLayout());
            JList list = new JList(new MyModel(num));
            list.setVisibleRowCount(3);
            JScrollPane pane = new JScrollPane(list);
            this.add(pane);
        }
    }

    private static class MyModel extends DefaultListModel {

        public MyModel(String[] numbers) {
            for (String string : numbers) {
                this.addElement(string);
            }
        }
    }

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new MyPanel());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test().display();
            }
        });
    }
}
于 2013-07-28T02:41:58.053 回答