所以我认为自己是一名初学程序员,但是点击一下按钮做一些简单的事情就很简单了吧?我先粘贴代码,然后问问题。
/*
* Created By Vili Milner
*/
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class MainView extends JFrame implements ActionListener {
private long cookieBalance = 0;
private String stringBalance = Long.toString(cookieBalance);
private JLabel balance = new JLabel(stringBalance);
public MainView(){
display();
}
public void display(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setTitle("Cookie Clicker");
setSize(300, 200);
GridLayout gridOneTwo = new GridLayout(1, 2);
GridLayout gridOneTen = new GridLayout(1, 10);
GridLayout gridOneThree = new GridLayout(1, 3);
Panel mainPanel = new Panel();
mainPanel.setLayout(gridOneTwo);
Panel upgradePanel = new Panel();
upgradePanel.setLayout(new BoxLayout(upgradePanel, BoxLayout.Y_AXIS));
JButton upgradeButtonOne = new JButton("UPGRADE 1");
JButton upgradeButtonTwo = new JButton("UPGRADE 2");
JButton upgradeButtonThree = new JButton("UPGRADE 3");
JButton upgradeButtonFour = new JButton("UPGRADE 4");
JButton upgradeButtonFive = new JButton("UPGRADE 5");
upgradePanel.add(upgradeButtonOne);
upgradePanel.add(upgradeButtonTwo);
upgradePanel.add(upgradeButtonThree);
upgradePanel.add(upgradeButtonFour);
upgradePanel.add(upgradeButtonFive);
mainPanel.add(upgradePanel);
Panel displayPanel = new Panel();
displayPanel.setLayout(new BoxLayout(displayPanel, BoxLayout.Y_AXIS));
displayPanel.add(balance);
mainPanel.add(displayPanel);
Panel cookiePanel = new Panel();
cookiePanel.setLayout(gridOneThree);
JButton cookieButton = new JButton("COOKIE");
cookieButton.setActionCommand("cookie");
cookieButton.addActionListener(this);
cookiePanel.add(cookieButton);
JLabel emptyLabelOne = new JLabel(" ");
JLabel emptyLabelTwo = new JLabel(" ");
displayPanel.add(cookiePanel);
displayPanel.add(emptyLabelOne);
displayPanel.add(emptyLabelTwo);
add(mainPanel);
}
@Override
public void actionPerformed(ActionEvent click) {
String action = click.getActionCommand();
if (action.equals("cookie")){
cookieBalance++;
}
}
}
继续,我可以让按钮做任何事情,除了使显示标签上升1.换句话说,按钮本身确实有效,但由于某种原因标签没有改变。我相信这是一个相当简单的错误,我似乎无法找到它。所以我的问题是:为什么一旦我增加值,标签就不会改变?
答案 0 :(得分:1)
重复评论中所说的内容,JLabel
balance
未使用该值进行更新,它只是反映了cookieBalance
原来的价值。
您应该调用:
@Override
public void actionPerformed(ActionEvent click) {
String action = click.getActionCommand();
if (action.equals("cookie")){
balance.setText(String.valueOf(++cookieBalance));
}
}