所以,我知道有这样的:
int number = Integer.parseInt("5");String numtxt = Integer.toString(12);double number = Double.parseDouble("4.5");String numbertxt = Double.toString(8.2);String letter = Character.toString('B');char letter = "stringText".charAt(0);so on...
但是我不知道如何使String值动态调用现有的JButton变量名;它甚至可能吗?
Let’s say, I have 4 JButton called btn1, btn2, btn3 and btnFillNumber;
I create a String called buttonName;
package testing;public class Testing extends javax.swing.JFrame {String buttonName;int num;public Testing() { initComponents();}@SuppressWarnings("unchecked")// Generated Code <<<-----private void btnFillNumberActionPerformed(java.awt.event.ActionEvent evt) { for(num = 1; num <= 3; num ){ buttonName = "btn" Integer.toString(num); JButton.parseJButton(buttonName).setText(num); }} /** * @param args the command line arguments */public static void main(String args[]) { /* Set the Nimbus look and feel */ // Look and feel stteing code (optional) <<<----- /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Testing().setVisible(true); } });}// Variables declaration - do not modify private javax.swing.JButton btn1;private javax.swing.JButton btn2;private javax.swing.JButton btn3;private javax.swing.JButton btnFillNumber;// End of variables declaration }
我知道没有JButton.parseJButton(),我只是不想做复杂的解释,我只想从String转换动态调用JButton的变量名.
看到这个:
for(num = 1; num <= 3; num ){ buttonName = "btn" Integer.toString(num); JButton.parseJButton(buttonName).setText(num); }
我想用String做一个循环
>一个固定的字符串值(btn)和
>之后的增量数(1,2,3 ……)和
>使用来调用JButton.
我可以简单地做到这一点,但如果我得到25或更多呢?这就是我想要的循环……
btn1.setText("1");btn2.setText("2");btn3.setText("3");
Note that the value of these JButtons are not necessarily incremental in some purpose.
输出:
我真正的发展:
附:我用来在NetBeans Design中制作JFrame(只需点击并拖动调色板窗口中的对象,如JPanel,JButton等,所以除了制作我自己的逻辑方法外,我不会手动输入代码;而且我无法编辑代码在源视图中的灰色背景中,由设计视图自动生成,但在设计视图中.如果您有提示和指南,我将很乐意).
解决方法:
使用地图:
private Map<String,JButton> buttonMap = new HashMap<String,JButton>();
在构造函数中添加按钮:
buttonMap.add("btn1", btn1);buttonMap.add("btn2", btn2);buttonMap.add("btn3", btn3);buttonMap.add("btn4", btn4);
在你的动作中,Listener / Loop无论做什么:
String buttonName = "btn1"; //should be parameter or whateverJButton button = buttonMap.get(buttonName);
作为替代方案,您也可以设置一个JButton数组:
JButton[] buttons = new JButton[4];button[0] = new JButton(); //btn1button[1] = new JButton(); //btn2button[2] = new JButton(); //btn3button[3] = new JButton(); //btn4
并访问它
JButton but = button[Integer.parseInt(buttonString)-1];
或者通过利用向UI元素添加自定义属性的可能性(您需要一个JComponent)
getContentPane().putClientProperty("btn1", btn1);
然后检索whith
JButton but = (JButton)getContentPane().getClientProperty("btn1");
来源:https://www.icode9.com/content-1-304501.html
联系客服