我用一个方法创建了一些JButton,但我没有给它们一个可以用来调用它们的变量。我想知道,在用另一种方法创建按钮后,是否可以以某种方式更改文本。我知道我可以在按下按钮时获得操作命令,但我想在不按下按钮的情况下更改按钮文本。我可以给按钮起这样的名字,但不愿意。因为我只会叫一半,然后我觉得这不是一个好主意。还是这样?
JButton button1=按钮(0,0,0);
public JButton buttons(int coord, int coord1, int number) {
JButton box = new JButton("");
box.setFont(new Font("Tahoma", Font.PLAIN, 60));
box.setBounds(coord, coord1, 100, 100);
contentPane.add(box);
box.addActionListener(this);
box.setActionCommand(Integer.toString(number));
return box;
}
public static void main(String[] args) {
buttons(0,0,0);
buttons(98,0,1);
buttons(196,0,2);
buttons(0,98,3);
addText();
}
public void addText() {
//help me guys
button.setText("Please fix me");
}
您可以从actionEvent 获得按下按钮
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
}
为什么不把它们放在公共数组列表中呢?
ArrayList<JButton> buttons = new ArrayList<JButton>();
public JButton buttons(int coord, int coord1, int number) {
JButton box = new JButton("");
box.setFont(new Font("Tahoma", Font.PLAIN, 60));
box.setBounds(coord, coord1, 100, 100);
contentPane.add(box);
box.addActionListener(this);
box.setActionCommand(Integer.toString(number));
buttons.add(box);//Add it here
return box;
}
这样你以后就可以循环浏览它们,如果你想改变的话,
for(JButton b : buttons){
if(/*Whatever*/){
b.setText("New name");
}
}
我可以给按钮起这样的名字,但不愿意。因为我只会叫一半,然后我觉得这不是一个好主意。还是这样?
你在给自己制造麻烦。即使你可能只需要打电话给他们中的一些人/没有人,但不为他们保留推荐人也有很大的优势。
如果您有太多的JButton,并且不想为每个JButton都有一个单独的变量名,那么您可以有一个JButton的数组/集合。
JButton[] btns = new JButton[size];
//or
ArrayList<JButton> btns= new ArrayList<JButton>();
要更改所有按钮的文本:
for(JButton b : btns)
btns.setText("whatever here");
要更改特定按钮的文本:
btns[x].setText("whatever here"); //from array
btns.get(x).setText("whatever here"); //from list
或者,如果您不保留参考资料。您可以从内容窗格中获得按钮列表:
Component[] components = myPanel.getComponents();
for(Component c : components)
if(c instanceof JButton)
((JButton)c).setText("whatever here");