您好我有这个简单的代码,可以在循环上生成按钮及其操作。 默认循环为1 go,表示1个按钮。
我的目标是对“Adicionar”按钮进行编程以增加循环并使循环生成更多按钮。
这是代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@SuppressWarnings("serial")
public class GuiClass extends JFrame{
// PUBLIC VARS
// VARIAVEIS
public int numeroButoes = 1;
// CONSTRUCTOR
public GuiClass(){
super("Loop Buttons");
setLayout(null);
// BUTOES ADD & REMOVE
JButton mais = new JButton("Adiciona");
//JButton menos = new JButton("Remove");
mais.addActionListener(new handlerBotaoAdd());
mais.setBounds(50, 0, 100, 40);
add(mais);
// LOOP BOTOES
for (int x = 0; x < numeroButoes; x++ ){
JButton teste = new JButton("Botão " + x);
teste.setActionCommand("Botão " +x);
teste.addActionListener(new handlerBotoesLoop(teste.getActionCommand()));
teste.setBounds(450, (x == 0 ? 0: x+(40*x)), 100, 40);
add(teste);
}
}
private class handlerBotoesLoop implements ActionListener{
String texto;
public handlerBotoesLoop(String x){
x = texto;
}
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
private class handlerBotaoAdd implements ActionListener{
public void actionPerformed(ActionEvent event){
numeroButoes++;
}
}
}
答案 0 :(得分:0)
您可以使用方法将逻辑设置为创建按钮,并通过按钮的点击事件调用该按钮
import javax.swing.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class Abc extends JFrame{
// PUBLIC VARS
// VARIAVEIS
public int numeroButoes = 1;
// CONSTRUCTOR
public Abc(){
super("Loop Buttons");
setLayout(null);
// BUTOES ADD & REMOVE
JButton mais = new JButton("Adiciona");
mais.addActionListener(new handlerBotaoAdd());
//JButton menos = new JButton("Remove");
mais.addActionListener(new handlerBotaoAdd());
mais.setBounds(50, 0, 100, 40);
add(mais);
}
// Method for button creating
private void generateButtons(){
for (int x = 0; x < numeroButoes; x++ ){
JButton teste = new JButton("Botão " + x);
teste.setActionCommand("Botão " +x);
teste.addActionListener(new handlerBotoesLoop(teste.getActionCommand()));
teste.setBounds(450, (x == 0 ? 0: x+(40*x)), 100, 40);
add(teste);
}
}
private class handlerBotoesLoop implements ActionListener{
String texto;
public handlerBotoesLoop(String x){
x = texto;
}
@Override
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
private class handlerBotaoAdd implements ActionListener{
@Override
public void actionPerformed(ActionEvent event){
numeroButoes++;
generateButtons();
}
}
}
当您单击Adicionar按钮时,我无法理解您是要创建单个按钮还是多个按钮。在我的解决方案中,每次单击Adicionar按钮都会创建多个按钮。