possible lossy conversion from long to int? [duplicate]

血红的双手。 提交于 2020-05-28 11:51:12

问题


I have this program that is pretty much a calculator but with a moving JLabel that is supposed to change colors every time you click the label, but i have 3 errors at the very bottom of the code that i have marked with a comment. all three are: error: incompatible types: possible lossy conversion from long to int

public class TestCalculator {
private ResultPane resultPane;


public static void main(String[] args) {
    new TestCalculator();
}

public TestCalculator() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                resultPane = new ResultPane();
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            }

            JFrame frame = new JFrame("Testing");
            frame.setGlassPane(resultPane);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            frame.add(new CalculatorPane(resultPane));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            frame.setBounds(200,200,500,400);

        }
    });
}

public class ResultPane extends JPanel {

    private JLabel result;
    private Timer timer;

    private int xDelta = (Math.random() > 0.5) ? 1 : -1;
    private int yDelta = (Math.random() > 0.5) ? 1 : -1;
    public void setLabelForeground(Color color) {
        result.setForeground(color);
    }



    public ResultPane() {
        setOpaque(false);
        setLayout(null);
        result = new JLabel();
        Font font = result.getFont();
        font = font.deriveFont(Font.BOLD, 26f);
        result.setFont(font);
        add(result);
        HandlerClass handler = new HandlerClass();
        result.addMouseListener(handler);
        result.addMouseMotionListener(handler);
        timer = new Timer(40, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Point point = result.getLocation();
                point.x += xDelta;
                point.y += yDelta;
                if (point.x < 0) {
                    point.x = 0;
                    xDelta *= -1;
                } else if (point.x + result.getWidth() > getWidth()) {
                    point.x = getWidth() - result.getWidth();
                    xDelta *= -1;
                }
                if (point.y < 0) {
                    point.y = 0;
                    yDelta *= -1;
                } else if (point.y + result.getHeight() > getHeight()) {
                    point.y = getHeight() - result.getHeight();
                    yDelta *= -1;
                }
                result.setLocation(point);
                repaint();
            }

        });
        timer.start();
    }

    public void setResult(Number number) {
        result.setText(NumberFormat.getNumberInstance().format(number));
        result.setSize(result.getPreferredSize());
        setVisible(true);
    }
    public String getResultText() {
        return result.getText();
    }

}

public class CalculatorPane extends JPanel {

    private final ResultPane resultPane;

    private final JLabel firstNumberLabel = new JLabel("First Number:");
    private final JLabel secondNumberLabel = new JLabel("Second Number:");

    private final JTextField firstNumberField = new JTextField(5);
    private final JTextField secondNumberField = new JTextField(5);

    public double result = 0.0;

    public CalculatorPane(ResultPane resultPane) {

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;

        this.resultPane = resultPane;

        JPanel fields = new JPanel();
        fields.add(firstNumberLabel);
        fields.add(firstNumberField);
        fields.add(secondNumberLabel);
        fields.add(secondNumberField);

        add(fields, gbc);

        JPanel buttons = new JPanel();
        buttons.add(new JButton(new AddAction()));
        buttons.add(new JButton(new SubtractAction()));
        buttons.add(new JButton(new MultiplyAction()));
        buttons.add(new JButton(new DivideAction()));

        add(buttons, gbc);

    }

    public class AddAction extends AbstractAction {

        public AddAction() {
            putValue(NAME, "+");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 + num2;
                resultPane.setResult(result);
                String resultText = resultPane.getResultText();
            firstNumberField.setText(resultText);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class SubtractAction extends AbstractAction {

        public SubtractAction() {
            putValue(NAME, "-");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 - num2;
                resultPane.setResult(result);
                String resultText = resultPane.getResultText();
            firstNumberField.setText(resultText);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class MultiplyAction extends AbstractAction {

        public MultiplyAction() {
            putValue(NAME, "x");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 * num2;
                resultPane.setResult(result);
                String resultText = resultPane.getResultText();
            firstNumberField.setText(resultText);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class DivideAction extends AbstractAction {

        public DivideAction() {
            putValue(NAME, "/");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 / num2;
                resultPane.setResult(result);
                String resultText = resultPane.getResultText();
                firstNumberField.setText(resultText);
            } catch (NumberFormatException exp) {
            }
        }
    }

}
private class HandlerClass implements MouseListener, MouseMotionListener {
        public void mouseClicked(MouseEvent event) {
        int r = Math.round(Math.random() * 255);//error here
    int g = Math.round(Math.random() * 255);//here
    int b = Math.round(Math.random() * 255);//and here
    Color col = new Color(r, g, b);
        resultPane.setLabelForeground(col);
        }
        public void mouseReleased(MouseEvent event) {
        }
        public void mousePressed(MouseEvent event) {
        }
        public void mouseExited(MouseEvent event) {
        }
        public void mouseEntered(MouseEvent event) {
        }
        public void mouseMoved(MouseEvent event) {
        }
        public void mouseDragged(MouseEvent event){
        }
    }



}

回答1:


That's because a long is 64 bits and an int is 32 bits, not to mention you're going from floating-point to integer. To go from long to int, you're going to have to discard some information, and the compiler can't/won't do that automatically. You're going to have to explicitly say so through a cast:

int g = (int) Math.round(Math.random() * 255);
        ^^^^^

Alternatively, you can use java.util.Random:

Random r = new Random();
int g = r.nextInt(256);



回答2:


You are trying to have the compiler provide an implicit primitive narrowing conversion, by assigning a long (the result of Math.round) to an int. It cannot be done implicitly; do it explicitly with a cast.

int r = (int) Math.round(Math.random() * 255);



回答3:


Math.random() gives you a long, which can far exceed the range of values that an integer can represent. You then assign that value to an integer.

That is what the compiler is warning you about.

http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html



来源:https://stackoverflow.com/questions/23748942/possible-lossy-conversion-from-long-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!