我正在尝试创建此代码,以便在每次单击“提交”时添加或减去每次显示的初始值。我已经搜索了多个线程如何完成这个,我没有遇到任何非常清楚的。向正确的方向推进真的会有所帮助。
package TwoPanelDesign;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JButton;
public class TwoPanelDesign extends JFrame {
private static final long serialVersionUID = 1L;
public TwoPanelDesign() {
getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 151, 262);
getContentPane().add(panel);
panel.setLayout(null);
final JLabel lblYourChoice = new JLabel("Your choice...");
lblYourChoice.setBounds(10, 11, 172, 14);
panel.add(lblYourChoice);
final JRadioButton rdbtnAdd = new JRadioButton("Add 2");
rdbtnAdd.setBounds(10, 32, 109, 23);
panel.add(rdbtnAdd);
final JRadioButton rdbtnMinus = new JRadioButton("Minus 2");
rdbtnMinus.setBounds(10, 58, 109, 23);
panel.add(rdbtnMinus);
ButtonGroup group = new ButtonGroup();
group.add(rdbtnAdd);
group.add(rdbtnMinus);
JPanel panel_1 = new JPanel();
panel_1.setBounds(97, 0, 349, 262);
getContentPane().add(panel_1);
panel_1.setLayout(null);
panel_1.setBackground(Color.BLUE);
final JLabel label = new JLabel("0");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(67, 0, 260, 262);
label.setFont(new Font("Arial", Font.BOLD + Font.ITALIC, 45));
panel_1.add(label);
JButton btnSubmit = new JButton("Submit");
btnSubmit.setBounds(10, 88, 88, 23);
panel.add(btnSubmit);
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if (rdbtnAdd.isSelected())
label.setText("2");
if (rdbtnMinus.isSelected())
label.setText("-2");
}
}
);
}
public static void main(String[] args) {
TwoPanelDesign A = new TwoPanelDesign();
A.setSize(500,400);
A.setVisible(true);
A.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
答案 0 :(得分:3)
您必须保留以前的结果:
public void actionPerformed(ActionEvent e){
int v = Integer.parseInt(label.getText());
if (rdbtnAdd.isSelected()){
v += 2;
} else {
v -= 2;
}
label.setText(Integer.toString(v));
}