我的问题是,这个号码是从一个arraylist获得的,例如
JNumber.size()=10
;
for(int a=0;a<JNumber.size();a++)
{
btnNumber= new JNumber(""+(a+1));
btnNumber.setPreferredSize(new Dimension(20, 10));
panel.setLayout(new GridLayout(10,10));
panel.add(btnNumber, BorderLayout.SOUTH);
}
然后如何在单击按钮时返回数字?
输出:
点击数字2。
答案 0 :(得分:2)
您可以在ActionListener中执行此操作。 使用给出的代码,这应该适用于您的情况:
如果您希望显示的文本不仅是数字,则使用特定文本初始化按钮,并将按钮的action命令设置为实际数字。 (见下文。)
btnNumber= new JNumber(""+(a+1));
btnNumber.setActionCommand(""+(a+1));
btnNumber.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)evt.getSource();
int num = Integer.parseInt(button.getActionCommand());
System.out.println(num);
}
});
答案 1 :(得分:1)
这是一个小例子,希望它有所帮助。基本上只需将JButton
添加到JPanel
,将ActionListener
添加到每个JButton
,然后在点击按钮JPanel
后添加JFrame
println()
1}}将使用JButton
的ActionCommand执行(setActionCommand()
使用+1到@ Pr0gr4mm3r:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class ButtonsTest {
public ButtonsTest() {
initComponents();
}
private void initComponents() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(2, 2));//create gridlayput to hold buttons
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
//display action command of jbutton
String ac = ((JButton) ae.getSource()).getActionCommand();
System.out.println(ac);
//display full test in Jbutton
//String text = ((JButton) ae.getSource()).getText();
//System.out.println(text);
}
};
for (int i = 0; i < 4; i++) {
JButton b = new JButton("No: " + String.valueOf((i + 1)));
b.setActionCommand(String.valueOf((i + 1)));
b.addActionListener(al);
panel.add(b);
}
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//set L&F and create UI on EDT
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {//set L&F
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
//create UI
new ButtonsTest();
}
});
}
}
答案 2 :(得分:0)
将btnNumber
声明为final
并向其添加ActionListener
:
btnNumber.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Number " + btnNumber.getText() + " is clicked");
}
});