1

我需要将Actionlistener类型转换为整数来调用方法。有任何想法吗?

import javax.swing.*;
import java.awt.*;
/**
* sold by pound
*/
public class CandyPanel extends JPanel { 
    public CandyPanel () {
        // Create a GridLayout manager with 
        // two rows and one column.
        setLayout(new GridLayout(1, 1));

        // Create the radio buttons.
        JPanel gummyBears = new JPanel(new BorderLayout());

        // Add a border around the panel.
        setBorder(BorderFactory.createTitledBorder("Gummy Bears"));

        // Add the JPanel to the panel.
        add(gummyBears);
    }

    /** 
    * returns the total cost of the item based on the 
    * number of units purchased 
    * @param number    the number of units purchased 
    * @return          the total cost of those units 
    */
    public double getCost(int number) { 
         double total = number * 2.00;
         return total;
    } 

    /** 
    * Prints the ordered item 
    * @param amount    the number of units purchased 
    * @param cost      the total cost of those units 
    */
    public void printOrderItem(int amount, double cost){ 
        JOptionPane.showMessageDialog(null, amount + " Gummy Bears at $2.00/pound = $" + cost + ".");
    } 
}

这是需要转换的方法int

public double getCost(int number) { 
     double total = number * 2.00;
     return total;
} 

我尝试parseInt按照在线研究进行操作,但它不适用于ActionEvent.

4

1 回答 1

1

您不能将 ActionEvent 转换为 int。但是,如果它是您想要转换为 int 的用户输入,比如一个文本框,它将是这样的:

String s = jTextBox.getText();
int i = Integer.valueOf(s);

然后将整数值插入您的方法中。如果您需要帮助,这里还有一个关于如何使用 ActionListener 的教程:http: //docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

希望这可以帮助!

于 2012-06-27T23:24:28.880 回答