计算切换按钮和

时间:2014-01-08 12:03:58

标签: java swing jlabel jtextfield jtogglebutton

http://i415.photobucket.com/albums/pp235/wong93_photos/Untitled-3.png

哟伙计们我在这里几乎没有问题,在我问之前,我想要用这个程序做的是计算已经按下的切换次数,并将jTextField中的总数设置为“数量”。 例如,我按下A和B切换按钮,因此数量将显示2,jLabel7将显示20

1)如何计算已按下的切换次数?我无法在任何地方找到这个

2)如何在jTextField中输入值?我知道这是基本的,但我不知道如何,我搜索周围,所有这些都是关于从文本字段检索信息而不是插入

3)如何将jLabel7中的值传递给我的其他jFrame?因为我想用它作为收据,例如:总费用是20

非常感谢!

1 个答案:

答案 0 :(得分:2)

import java.awt.Dimension;
import java.awt.FlowLayout;
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;
import javax.swing.JTextField;

public class Example extends JPanel {

    private static final long serialVersionUID = 1L;

    private int toggle_count = 0;
    private JTextField text_field;
    private JLabel label;

    public Example() {

        this.setLayout(new FlowLayout());

        JButton button_a = new JButton("Button A");
        this.add(button_a);

        JButton button_b = new JButton("Button B");
        this.add(button_b);

        text_field = new JTextField("0");
        text_field.setPreferredSize(new Dimension(50, 20));
        text_field.setEditable(false);
        this.add(text_field);

        label = new JLabel("x 10 = 0");
        this.add(label);

        button_a.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

                updateToggle();
            }
        });

        button_b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

                updateToggle();
            }
        });

        JButton receipt = new JButton("Receipt");
        this.add(receipt);

        receipt.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub

                SomeClass.main(toggle_count*10);
            }
        });

    }

    public void updateToggle() {

        toggle_count++;
        text_field.setText("" +toggle_count);
        label.setText("x 10 = " + toggle_count * 10);
    }

    public static void main(String[] args) {

        JFrame frame = new JFrame("Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(640, 480);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setContentPane(new Example());

        frame.setVisible(true);
    }
}

SomeClass是另一个带有main方法的类,它将toggle_count * 10作为参数