我正在编写我的第一个 LWUIT 和 Java ME 应用程序,并尝试让按钮状态正常工作。我知道我可以在资源编辑器中完成此操作,但我真的很想知道为什么我的代码不起作用。我下面的代码的行为看起来很不稳定。如果我选择第一个按钮,它工作正常。当我选择第二个按钮时,该按钮具有选定状态的前景,但具有未选定状态的背景。第三个按钮也是如此。但是,当我回到第一个按钮时,第一个按钮和第三个按钮都具有选定状态的背景,第一个按钮具有选定状态的前景,第三个按钮具有未选定状态的前景。 我尝试过阅读教程和在线论坛,但似乎其中大多数都已经过时了。即使官方 LWUIT 页面上的教程中也包含已过时的命令,以至于 Netbeans 将它们显示为未解决而不是已过时。我确信这是一个简单的错误,但我只是无法从这段代码中看出其他按钮应如何受到选择或取消选择的影响,或者为什么每次按钮状态更改时选择和未选择的样式都会改变。
Style buttonUp = new Style();
buttonUp.setAlignment(Component.CENTER);
buttonUp.setBgColor(0x0082ff);
buttonUp.setFgColor(0xffffff);
buttonUp.setMargin(5,5,0,0);
Style buttonDown = new Style();
buttonDown.setAlignment(Component.CENTER);
buttonDown.setBgColor(0xd7d7ee);
buttonDown.setFgColor(0x000000);
buttonDown.setMargin(5,5,0,0);
Container buttons = new Container(new BoxLayout(BoxLayout.Y_AXIS));
Button firstButton = new Button("first");
firstButton.setUnselectedStyle(buttonUp);
firstButton.setSelectedStyle(buttonDown);
firstButton.setPressedStyle(buttonDown);
Button secondButton = new Button("second");
secondButton.setUnselectedStyle(buttonUp);
secondButton.setSelectedStyle(buttonDown);
secondButton.setPressedStyle(buttonDown);
Button thirdButton = new Button("third");
thirdButton.setUnselectedStyle(buttonUp);
thirdButton.setSelectedStyle(buttonDown);
thirdButton.setPressedStyle(buttonDown);
这应该是所有相关代码,因为它是唯一处理按钮的部分,除了将按钮添加到容器以及将容器添加到表单的 addComponent 调用之外。
最佳答案
您正在重用样式对象实例,这是不合法的每个组件状态必须有一个单独的实例。在 LWUIT 中更常见的做法是:
button.getUnselectedStyle().setFgColor(...);
或者,您可以在方法中实现逻辑:
updateButtonTheme(Style);
并将其调用为:
updateButtonTheme(button.getUnselectedStyle());
关于java-me - 在 LWUIT 中设置按钮状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7375742/