试图从一个方法返回两个值

时间:2018-05-25 10:41:34

标签: java javafx

我运行一个GUI来显示来自MySQL数据库的每个图像,它在我点击下一个按钮时显示图像没有任何问题之前工作正常,现在我想要不仅返回图像而且还返回来自同样的方法,这就是为什么我从“图像”类型更改为PAIR但我不明白如何划分从该方法返回的两个变量:

配对示例:

    public Pair<Integer,Image> image2()throws SQLException
        {
            int id;

            try {

                boolean anyResults = false;

                if (rs.next())
                {

                    anyResults = true;

                    Blob blob = rs.getBlob("image");

                    id = rs.getInt("id");


                    InputStream in = blob.getBinaryStream(1, blob.length());


                    BufferedImage image = ImageIO.read(in);


                    Image image1 = SwingFXUtils.toFXImage(image,null);


                    return new Pair<>(id, image1);

                }
                else if (!anyResults)
                {
                    JOptionPane.showMessageDialog(null, "Not Found");
                }


            } catch (Exception e)
            {
                e.printStackTrace();
            }

            return null;
        }

下一个按钮点击方法的示例:

public void NextButtomClicked() throws SQLException
    {
        //  this is what i used before =>   Image image1 = sql.image2();

        Pair<Integer, Image> image1 = sql.image2();

        this.imageView.setImage(image1);


    }

2 个答案:

答案 0 :(得分:1)

Pair<Integer, Image> pair = sql.image2();
Integer id = pair.getKey();
Image image = pair.getValue();
// now do what you want with id and image

您可能还应该处理null个案,因为您的方法可以返回它。

答案 1 :(得分:0)

你得到了两个值,你的对没有任何问题。

之后,您将imageView.image设置为Pair<>,但无效。

您的image1不再是Image类型,而是Pair类型。

您的NextButtomClicked()应该是这样的:

public void NextButtomClicked() throws SQLException {
    Pair<Integer, Image> pair = sql.image2();

    this.imageView.setImage(pair.getValue());
    this.imageView.setId(pair.getKey());
}

pair.getValue()会返回Pair<>的第二个参数。在您的情况下Image

pair.getKey()会返回Pair<>的第一个参数。在您的情况下,Integer(ID)。