如何获取特定的数组列表项

How to get Specific Array List Item

我在从数组列表中进行选择时遇到一点问题。我正在编写一些代码,使我能够将大约 10 个 JButton 固定在一个圆圈中,我做对了,但是......我想在每个 Button 上设置一个 actionListener,但我不明白,所有按钮继承一个按钮所需的操作。我该如何具体化,...这是我的代码...提前致谢!

private JButton quest;

public Beginner() {

    int n = 10; // no of JButtons
    int radius = 200;
    Point center = new Point(250, 250);
    double angle = Math.toRadians(360 / n);

    List<Point> points = new ArrayList<Point>();

    points.add(center);

    for (int i = 0; i < n; i++) {
        double theta = i * angle;
        int dx = (int) (radius * Math.sin(theta));
        int dy = (int) (radius * Math.cos(theta));
        Point p = new Point(center.x + dx, center.y + dy);
        points.add(p);
    }

    draw(points);

}

public void draw(List<Point> points) {

    JPanel panels = new JPanel();

    SpringLayout spring = new SpringLayout();

    // Layout used
    int count = 1;
    for (Point point : points) {

        quest = new JButton("Question " + count);
        quest.setForeground(Color.BLUE);
        Font fonte = new Font("Script MT Bold", Font.PLAIN, 20);
        quest.setFont(fonte);

        add(quest);
        count++;

        spring.putConstraint(SpringLayout.WEST, quest, point.x, SpringLayout.WEST, panels);

        spring.putConstraint(SpringLayout.NORTH, quest, point.y, SpringLayout.NORTH, panels);

        setLayout(spring);

        panels.setOpaque(false);
        panels.setVisible(true);
        panels.setLocation(10, 10);

        add(panels);

        // action Listener to be set on individual buttons
        quest.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent a) {

                if (quest.equals(points.get(5)))
                    ;
                String c = "Hello!";
                JOptionPane.showMessageDialog(null, c);
            }
        });
    }
}

问题是表达式

if (quest.equals(points.get(5)));

什么都不做。我想应该这样改写

if (quest.equals(points.get(5))) {
    String c = "Hello!";
    JOptionPane.showMessageDialog(null, c);
}

我对这个问题的理解是,您有多个按钮,并且您希望每个按钮都有自己的关联操作。有几种方法可以做到这一点。您可以根据要创建的按钮为每个 JButton 创建一个新的 ActionListener。

您还可以在 ActionListener 中创建一个大的 case/switch 或 if/else,它由选择的按钮决定。为此,您可以为 ActionEvent 对象调用 getActionCommand() 函数。

quest.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent a) {

            if (a.getActionCommand().equals("Question 1"))
            {
                String c = "Hello!";
                JOptionPane.showMessageDialog(null, c);
            }
            else if(a.getActionCommand().equals("Question 2"))
            {
                //have it do something else
            }
            //and so on so forth

        }
    });

您需要重新考虑整个设计。你有这条线:

if (quest.equals(points.get(5))) {

但是points是一个包含Point对象的列表; points.get(5) returns 一个点。 quest 是一个 JButton。 JButton 实例如何等于 Point 实例?