从jButton获取文本值 [英] Getting text value from a jButton

查看:406
本文介绍了从jButton获取文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要简单检查点击按钮的文本是X还是O(制作tic tac toe)
此代码不起作用:

So I need to simply check whether a clicked button's text is "X" or "O" (making tic tac toe) This code doesn't work:

if (jButton1.getText()=="X")

但是以下代码确实有效:

However the following code does work:

String jButText = jButton1.getText();
if (jButText=="X")

为什么不是第一位代码工作的时候第二个呢?是否需要更像if( jButton1.getText()。toString ==X)?顺便说一下,我认为Java中不存在 toString 。这在Visual Basic中有点等同,这是我通常用来创建GUI的。

Why doesn't the first bit of code work when the second does? Does it need to be something more like if (jButton1.getText().toString=="X")? By the way, I don't think toString exists in Java. That is just somewhat the equivalent in Visual Basic, which is what I normally use to create GUIs.

推荐答案

此行为不可重现在java 1.7.0_45或1.7.0_25中,字符串实习可能是一个奇怪的现象java版。

This behavior is not reproducible in java 1.7.0_45 or 1.7.0_25, it might be a weird occurrence of String interning for your java version.

为了让你的代码在所有java版本上正常工作,你必须使用 equals()

In order for your code to work properly on all java versions you have to use equals()

== 同时比较对象 .equals()比较字符串对象的内容。

== compares objects meanwhile .equals() compares the content of the string objects.

jButton1.getText().equals("X")

这篇关于从jButton获取文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆