我不熟悉 Swing 核心功能。我有网页设计经验。 id
表示唯一性,class
表示通用性。
<div class="x" id="div1"></div>
<div class="x" id="div2"></div>
如果我想为所有的 div 设置属性,我将使用类 x。
.x
{
} or via javascript or jquery
如果我想访问单个 div,我将使用 id。因为它是独一无二的。
Java swing buttons 中有同样的方法吗?假设我有 jbuttons 的二维数组。
到目前为止已经尝试过
我找到了 putClientProperty
和 getClientproperty
。它设置并返回 id。
btnName.putClientproperty('id',value);
我的第一个问题:
设置唯一 ID 的方法是否正确?还有其他方法吗?
JButton[][] btns = new JButton[5][5];
for(int i=0; i<5; i++)
{
for(int j=0;j<5;j++)
{
btns[i][j] = new JButton("Button"+i+j);
}
}
以上代码将创建 25 个带有名称的按钮。
我的第二个问题:
我不知道它。如何设置类以便我可以使用单行代码启用或禁用它们?我的意思是
所有 25 个按钮都有一个共同的类让它成为 tiles
JButton.find('tiles').setEnabled(false);
java中有类似的东西吗?我知道迭代和执行它的方法。但我想减少行数,函数调用。这就是我发布这个问题的原因。请告诉我
最佳答案
在您的代码示例中...
JButton[][] btns = new JButton[5][5];
for(int i=0; i<5; i++)
{
for(int j=0;j<5;j++)
{
btns[i][j] = new JButton("Button"+i+j);
}
}
你说...
The above code will create 25 buttons with names.
这不完全正确,它创建了 25 个带有 Button"+i+j
文本的按钮,这听起来像是吹毛求疵,但这很重要,因为按钮不没有名称,到目前为止,唯一区别它们的是屏幕上显示的文本。
多个按钮可能有相同的文本,所以除了它们各自的(内存)引用之外,这并不是真正设置唯一性。
"Unique id's" 也是模棱两可的。您创建的每个按钮都是独一无二的,但它可能共享相似的属性,例如 name
、text
和 actionCommand
,因此唯一使它成为独特之处在于它在内存中的位置。
如果那是你的意思,那么是的,这将是开始......
My Second Question: I am unaware of it.How to set classes so that i can enable or disable them with single line code? I meant All the 25 buttons has a common class let it be tiles
从 API 的角度来看,没有。您需要迭代按钮并单独管理每个按钮。不过,话虽如此,您还是可以利用 Action
API。
一个 Action
通常是一个独立的工作单元,这使得它很容易应用于多个按钮、菜单项和键绑定(bind)......但在你的情况下,我们只感兴趣操纵它的 enabled
状态,例如,从...开始
public class GroupAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent evt) {
}
}
然后你可以做类似...
GroupAction groupAction = new GroupAction();
JButton[][] btns = new JButton[5][5];
for(int i=0; i<5; i++)
{
for(int j=0;j<5;j++)
{
btns[i][j] = new JButton(groupAction);
// This is important as the button will want
// to use the Action properties to configure itself
btns[i][j].setText("Button"+i+j);
}
}
然后你可以使用类似...
groupAction.setEnabled(false);
使用 GroupAction
的 SAME 实例禁用所有按钮
看看How to Use Actions了解更多详情
关于java - JButton 的通用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25236845/