在我的GUI程序中,我有4组卡片,我想为每个卡片按钮添加一个动作监听器,这样当它被点击时它就会变得不可见。我已经尝试过source.setVisible(),但它仍然无效。我认为我的问题是我通过for循环创建了所有的Card按钮,但我并不完全确定。
import java.awt.GridBagConstraints;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
public class CardGame extends JFrame implements ActionListener {
private JButton Deal;
CardGame(){
setTitle("A Card Game");
setSize(2000, 1000);
final GridBagConstraints layoutSpec = new GridBagConstraints();
layoutSpec.gridx = 0;
layoutSpec.gridy = 0;
final GridBagConstraints dealSpec = new GridBagConstraints();
layoutSpec.gridx = 4;
layoutSpec.gridy = 4;
final GridBagConstraints dealSpecs = new GridBagConstraints();
layoutSpec.gridx = 7;
layoutSpec.gridy = 7;
JPanel cardA = new JPanel();
cardA.setPreferredSize(new Dimension(100, 100));
add(cardA, BorderLayout.NORTH);
for(int i = 0; i < 13; i++) { //Loop that Creates a Hand of Cards for Hand A
cardA.add(new JButton("Card A-" + Integer.toString(i+1)), layoutSpec);
}
JPanel cardB = new JPanel();
cardB.setPreferredSize(new Dimension(100, 100));
add(cardB, BorderLayout.EAST);
for(int i = 0; i < 13; i++) { //Loop that Creates a Hand of Cards for Hand B
cardB.add(new JButton("Card B-" + Integer.toString(i+1)), layoutSpec);
}
JPanel cardC = new JPanel();
cardC.setPreferredSize(new Dimension(100, 100));
add(cardC, BorderLayout.WEST);
for(int i = 0; i < 13; i++) { //Loop that Creates a Hand of Cards for Hand C
cardC.add(new JButton("Card C-" + Integer.toString(i+1)), layoutSpec);
}
JPanel cardD = new JPanel();
cardD.setPreferredSize(new Dimension(100, 100));
add(cardD, BorderLayout.SOUTH);
for(int i = 0; i < 13; i++) { //Loop that Creates a Hand of Cards for Hand D
cardD.add(new JButton("Card D-" + Integer.toString(i+1)), layoutSpec);
}
JPanel fillCenter = new JPanel();
fillCenter.setPreferredSize(new Dimension(100, 100));
add(fillCenter, BorderLayout.CENTER); //Adds a panel that fills the center of the JFrame
fillCenter.add(new JButton("Deal"), dealSpec); //Adds a Deal Button on top of the fillCenter JPanel
fillCenter.add(new JButton("Reset"), dealSpecs); //Adds a Reset Button on top of the fillCenter JPanel
}
@Override
public void actionPerformed(ActionEvent event){
if(event.getSource() == (Deal)){
};
if(event.getSource() == ("Deal"));
for(int i = 0; i < 13; i++){
if(event.getSource() == ("Card " + Integer.toString(i+1)));
}
}
public static void main(String[] args) {
CardGame cards = new CardGame();
cards.setVisible(true);
return;
}
}
答案 0 :(得分:0)
试试这个((JButton)event.getSource()).setVisible(false);