java - 向 JTextArea 添加 double ?

标签 java swing jtextarea

在我点击北按钮后,我试图将代表我的玩家耐力的 double 值添加到 jTextArea 中,但似乎无法做到这一点,这是我的代码:

private void northButtonActionPerformed(java.awt.event.ActionEvent evt) 
{                                            
    game.playerMove(MoveDirection.NORTH);
    update();
    double playerStamina = player.getStaminaLevel();

    //tried this
    String staminaLevel = Double.toString(playerStamina);
    jTextArea1.setText("Stamina: " + staminaLevel);
}                

我是新来的,如果这不对,抱歉

这是主要方法

public class Main 
{
/**
 * Main method of Lemur Island.
 * 
 * @param args the command line arguments
 */
public static void main(String[] args) 
{
    // create the game object
    final Game game = new Game();
    // create the GUI for the game
    final LemurIslandUI  gui  = new LemurIslandUI(game);
    // make the GUI visible
    java.awt.EventQueue.invokeLater(new Runnable() 
    {
        @Override
        public void run() 
        {
            gui.setVisible(true);
        }
    });
}

这就是类(class)

public class LemurIslandUI extends javax.swing.JFrame
{
private Game game;
private Player player;
/** 
 * Creates a new JFrame for Lemur Island.
 * 
 * @param game the game object to display in this frame
 */
public LemurIslandUI(final Game game) 
{
    this.game = game;     
    initComponents();
    createGridSquarePanels();
    update();      
}

private void createGridSquarePanels() {

    int rows = game.getIsland().getNumRows();
    int columns = game.getIsland().getNumColumns();
    LemurIsland.removeAll();
    LemurIsland.setLayout(new GridLayout(rows, columns));

    for (int row = 0; row < rows; row++)
    {
        for (int col = 0; col < columns; col++)
        {
            GridSquarePanel panel = new GridSquarePanel(game, row, col);
            LemurIsland.add(panel);
        }
    }  
}

/**
 * Updates the state of the UI based on the state of the game.
 */
private void update()
{ 
    for(Component component : LemurIsland.getComponents()) 
    {
        GridSquarePanel gsp = (GridSquarePanel) component;
        gsp.update();
}
    game.drawIsland();

}

最佳答案

您的类似乎没有实现 ActionListener,因此按钮上的操作不会被触发。

你的类声明应该是:

public class LemurIslandUI extends javax.swing.JFrame implements ActionListener 

并将按钮操作的代码放入其中:

public void actionPerformed(ActionEvent e) {}

或者,您可以使用匿名类来实现按钮的代码,而不是让您的类实现ActionListener。像这样的东西:

final JButton button = new JButton();

    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionevent)
        {
            //code
        }
    });

关于java - 向 JTextArea 添加 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19541895/

相关文章:

java - JComboBox 的值

java - 将节点从 JTree 拖放到 JLabel 上以执行操作

Java - JList 中的 JTextArea 不显示所需的文本

java - 如何将字符串从工作线程发送到文本区域?

java - 在 JTextPane 中绘制水平线

java - 如何在一个请求中执行多个事务

java - 插入和选择阿拉伯语数据 Android SQLite

java - 具有输入验证功能的简单可编辑 JTable

java - Java中使用JDBC的并发访问

Java setVisible问题