如果用户点击了一个Jbutton(所有这些),我怎样才能获得分数增加,如果他点击了框架中的随机位置,我的分数会减少?这是代码
package projet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Letstry {
static int score;
public static void main (String[] args){
JFrame frame = new JFrame("Scity4");
frame.setVisible(true);
frame.setSize(500,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblNewLabel = new JLabel("score : ");
lblNewLabel.setBounds(72, 131, 46, 14);
frame.add(lblNewLabel);
lblNewLabel.setText(String.valueOf(score));
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Score inc");
panel.add(button);
button.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent e) {
score = score +10;
JLabel lblNewLabel = new JLabel("score : ");
lblNewLabel.setBounds(72, 131, 46, 14);
frame.add(lblNewLabel);
lblNewLabel.setText(String.valueOf(score));
}
});
}
}
答案 0 :(得分:0)
好的,此代码适用于每次用户点击+10
按钮时增加+10
。
要使其与-10
或您想要减少的任何数字一起使用,如果他们点击框架,您应该检查JFrame mouse click using JComponent and MouseListener。
正如我所说,下次让你的代码可读时不要使用这个标记(``)来显示代码,而是使用4个空格或clic上面的{ }
按钮。
请勿使用null
布局而是使用Layout Manager。有关此内容的更多信息,请阅读@BillK的this question and the answer。
我希望这会有所帮助,欢迎来到StackOverflow。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Letstry {
static int score;
static JFrame frame;
static JLabel label;
static JButton button;
public static void main (String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
frame = new JFrame("Scity4");
frame.getContentPane().setLayout(new FlowLayout());
label = new JLabel("Score: ");
button = new JButton("+10");
button.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent e) {
score = score + 10;
label.setText("Score: " + score);
frame.pack();
}
});
frame.add(label);
frame.add(button);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}