开发者

Java GUI: modifying the calculator program

开发者 https://www.devze.com 2023-02-17 21:19 出处:网络
I\'m trying to modify the calculator program our teacher gave to me. It\'s supposed to be composed of the main and GUI programs. My only problem is how to handle events. As you can see

I'm trying to modify the calculator program our teacher gave to me. It's supposed to be composed of the main and GUI programs. My only problem is how to handle events. As you can see I created the Numerics class apart from the main program. What I want to happen is that when I click a number it's supposed to throw the value from the numerics program to the textfield in the NorthPanel class in the main program. But I don't know how. Can anyone give me any ideas on how to do this?

Here is part of the main program

public class NorthPanel extends JPanel {
    private JTextField display;
    private JLabel filler;

    public NorthPanel() {
    //receive the thrown value from Numerics program to be displayed
        setLayout(new BorderLayout());
        String calcTF="0.";
        display = new JTextField(calcTF);
        display.setEditable(false);
        display.setFont(new Font("Century Gothic",Font.BOLD,19));
        display.setHorizontalAlignment(JTextField.RIGHT);                                   
        add(display,BorderLayout.CENTER);                   
    }
}

public class CenterPanel extends JPanel {

    private Numerics numeric;
    private Operations operator;
    private Functions function;

    public CenterPanel() {
        setLayout(null);

        numeric = new Numerics();
        numeric.setBounds(5,5,150,150);

        operator = new Operations();
        operator.setBounds(158,5,45,150);

        function = new Functions();
        function.setBounds(204,5,55,150);

        add(numeric);               
        add(operator);
        add(function,0);
    }
}

and here is part of the Numerics program

public class Numerics extends JPanel implements ActionListener
{
    private JButton c7;
    String value="";
    public Numerics() 
    {
        UIManager.put("Button.background", Color.gray);
        setLayout(new GridBagLayout());

        GridBagConstraints gbc=new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(0,3,5,3);

        c7=new JButton("7");
        c7.setFont(new Font("Arial",Font.BOLD,20));开发者_运维知识库
        c7.setBorder(BorderFactory.createRaisedBevelBorder());
        gbc.gridx=0;
        gbc.gridy=0;
        add(c7,gbc);
        c7.addActionListener(this);
public void actionPerformed(ActionEvent ae1)
    {
        if(ae1.getSource()==c7)
        {
            value+="7";
            //throw the value to display in the NorthPanel...
        }
    }


Look into Introduction to Event Listeners & specifically the How to Write an Action Listener sections of the Java Tutorial.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号