我是JFrame按钮的新手,我有两个JButton。提交的工作有效,但当我尝试使用具有特定名称的另一个时,它不会将一个字符串输出到控制台。最后,第二个JButton(btn)将有不同的名称,但点击按钮时没有做任何事情。
package schoolprgm;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class Jeopardy extends JFrame {
static JButton btn = new JButton();static JButton Submit = new JButton();
static JFrame frame = new JFrame("Jeopardy");static JPanel panel = new JPanel(new GridLayout(7,5,10,10));
static JTextField textField = new JTextField(10);
public Jeopardy(){
frame.setDefaultCloseOperation(3);
frame.setVisible(true);
Submit.addActionListener(new ButtonListener());
btn.addActionListener(new ButtonListener());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
frame.setPreferredSize(new Dimension(1000,400));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
int Score = 0;
JLabel l2 = new JLabel("Score: "+ String.valueOf(Score));
JLabel l3 = new JLabel();
ArrayList question = new ArrayList();
JLabel l = new JLabel("Question: "+ question);
Jeopardy.Submit.setText("Submit");
l.setLabelFor(textField);
/*label1.setText("Label1");
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel.add(label5);
panel.add(label6);
*///panel.add(label7);
String words = ("Category 1,Category 2,Category 3,Category 4,Category 5,Category 6,Category 7,C1: 100,100,100,100,100,100,100,200,200,200,200,200,200,200,300,300,300,300,300,300,300,400,400,400,400,400,400,400,500,500,500,500,500,500,500,999,999,99,999,999,999,999,999,999,999,999,999");
ArrayList btnnames = new ArrayList();
String[] words2 = words.split(",");
btnnames.addAll(Arrays.asList(words2));
frame.add(panel);
for(int x=0;x<42;x++){
if( x >= 0 && x<=6){
JLabel label = new JLabel(String.valueOf(btnnames.get(x)));
panel.add(label);
label.setText(String.valueOf(btnnames.get(x)));
}
else{
btn = new JButton(String.valueOf(btnnames.get(x)));
Jeopardy.btn.setText(String.valueOf(btnnames.get(x)));
panel.add(btn);
}}
panel.add(l);
panel.add(textField);
panel.add(Submit);
panel.add(l2);
panel.add(l3);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.getContentPane().add(new Jeopardy());
}
}
class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand()=="Submit"){
System.out.println("submit");
System.out.println(Jeopardy.textField.getText());
} if (e.getActionCommand()==("C1: 100")) {
System.out.println("100 has been clicked");
}
}
}