Java-子类中的调用方法通过在基类中按下JButton

时间:2018-07-31 07:47:08

标签: java swing inheritance

我可以通过按下JButton从扩展类中调用方法吗? 我知道在按下JButton时如何显示消息等,但是我想知道是否可以这样做?

我想从Activate_and_Deactivate类调用方法,以用作通过按下单选按钮ON和OF来执行的操作。我可以将语句直接放在actionevent参数中,但是老师说我必须至少使用继承。

这是我的代码。

package Calculators;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Button;
import java.awt.Color;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.JRadioButton;
public class UIFrame {
    Activate_and_Deactivate act = new Activate_and_Deactivate();
    JButton button0 = new JButton("0");
    JButton button2 = new JButton("2");
    JButton button1 = new JButton("1");
    JButton button3 = new JButton("3");
    JButton button4 = new JButton("4");
    JButton button5 = new JButton("5");
    JButton button6 = new JButton("6");
    JButton button7 = new JButton("7");
    JButton button8 = new JButton("8");
    JButton button9 = new JButton("9");
    JButton button_Div = new JButton("/");
    JButton button_C = new JButton("C");
    JButton button_Mul = new JButton("*");
    JButton button_Add = new JButton("+");
    JButton button_Sub = new JButton("-");
    JButton button_Dot = new JButton(".");
    JButton button_rec = new JButton("1/x");
    JButton button_Sqr = new JButton("\u221A");
    JButton button_neg = new JButton("±");  
    JButton button_per = new JButton("%");
    JButton button_equal = new JButton("=");
    JButton button_undo = new JButton("\u2190");
    JButton btnExit = new JButton("exit");      
    JRadioButton rdbtnOn = new JRadioButton("On");
    JRadioButton rdbtnOff = new JRadioButton("Off");

    private JFrame frmCalculator;
    private JTextField screen;
    private JTextField value1;
    private JTextField value2;
    private JLabel operation;


    double fNumber = 0;
    double sNumber = 0;
    double result = 0;



    String ope;
    String answer;


    public static void main(String[] args) {

        try 
        {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");       //Motif, and Windows packages that it requires are shipped with the Java SDK this way
        }
        catch(Exception e){}

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIFrame window = new UIFrame();
                    window.frmCalculator.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public UIFrame() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmCalculator = new JFrame();
        frmCalculator.setTitle("Java calculator ver 3.1.6 by Muhammad Haroon");
        frmCalculator.getContentPane().setBackground(new Color(0, 0, 0));
        frmCalculator.getContentPane().setForeground(Color.DARK_GRAY);
        frmCalculator.setBounds(100, 100, 326, 422);
        frmCalculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmCalculator.getContentPane().setLayout(null);

        value1 = new JTextField();
        value1.setForeground(Color.DARK_GRAY);
        value1.setFont(new Font("Tahoma", Font.PLAIN, 19));
        value1.setHorizontalAlignment(SwingConstants.RIGHT);
        value1.setBorder(null);
        value1.setBounds(151, 52, 141, 31);
        frmCalculator.getContentPane().add(value1);
        value1.setColumns(10);

        value2 = new JTextField();
        value2.setFont(new Font("Tahoma", Font.PLAIN, 24));
        value2.setHorizontalAlignment(SwingConstants.RIGHT);
        value2.setBorder(null);
        value2.setBounds(71, 90, 218, 37);
        frmCalculator.getContentPane().add(value2);
        value2.setColumns(10);

        operation = new JLabel("");
        operation.setForeground(new Color(144, 238, 144));
        operation.setHorizontalAlignment(SwingConstants.LEFT);
        operation.setFont(new Font("Tahoma", Font.PLAIN, 20));
        operation.setBounds(20, 97, 50, 31);
        frmCalculator.getContentPane().add(operation);

        screen = new JTextField();
        screen.setBorder(new CompoundBorder(new EtchedBorder(EtchedBorder.RAISED, null, null), new EtchedBorder(EtchedBorder.LOWERED, null, null)));
        screen.setEditable(false);
        screen.setHorizontalAlignment(SwingConstants.RIGHT);
        screen.setBounds(10, 48, 289, 82);
        frmCalculator.getContentPane().add(screen);
        screen.setColumns(10);


        rdbtnOn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                act.activate();
            }
        });
        rdbtnOn.setFont(new Font("Cambria Math", Font.PLAIN, 12));
        rdbtnOn.setForeground(new Color(255, 255, 255));
        rdbtnOn.setBounds(11, 18, 38, 23);
        frmCalculator.getContentPane().add(rdbtnOn);


        rdbtnOff.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                act.deactivate();
            }
        });
        rdbtnOff.setFont(new Font("Cambria Math", Font.PLAIN, 12));
        rdbtnOff.setForeground(new Color(255, 255, 255));
        rdbtnOff.setBounds(51, 18, 38, 23);
        frmCalculator.getContentPane().add(rdbtnOff);


        button0.setBackground(new Color(135, 206, 250));
        button0.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String num = value2.getText() + button0.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button0.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button0.setBounds(11, 306, 110, 31);
        frmCalculator.getContentPane().add(button0);


        button2.setBackground(new Color(135, 206, 250));
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num = value2.getText() + button2.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });


        button1.setBackground(new Color(135, 206, 250));
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num = value2.getText() + button1.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button1.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button1.setBounds(11, 264, 50, 31);
        frmCalculator.getContentPane().add(button1);
        button2.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button2.setBounds(71, 264, 50, 31);
        frmCalculator.getContentPane().add(button2);


        button3.setBackground(new Color(135, 206, 250));
        button3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num = value2.getText() + button3.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button3.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button3.setBounds(131, 264, 50, 31);
        frmCalculator.getContentPane().add(button3);


        button4.setBackground(new Color(135, 206, 250));
        button4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num = value2.getText() + button4.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button4.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button4.setBounds(11, 222, 50, 31);
        frmCalculator.getContentPane().add(button4);


        button5.setBackground(new Color(135, 206, 250));
        button5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num = value2.getText() + button5.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button5.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button5.setBounds(71, 222, 50, 31);
        frmCalculator.getContentPane().add(button5);


        button6.setBackground(new Color(135, 206, 250));
        button6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num = value2.getText() + button6.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button6.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button6.setBounds(131, 222, 50, 31);
        frmCalculator.getContentPane().add(button6);


        button7.setBackground(new Color(135, 206, 250));
        button7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String num = value2.getText() + button7.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button7.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button7.setBounds(11, 180, 50, 31);
        frmCalculator.getContentPane().add(button7);


        button8.setBackground(new Color(135, 206, 250));
        button8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num = value2.getText() + button8.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button8.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button8.setBounds(71, 180, 50, 31);
        frmCalculator.getContentPane().add(button8);


        button9.setBackground(new Color(135, 206, 250));
        button9.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String num = value2.getText() + button9.getText();          //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button9.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button9.setBounds(131, 180, 50, 31);
        frmCalculator.getContentPane().add(button9);


        button_Div.setBackground(new Color(192, 192, 192));
        button_Div.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                value1.setText(value2.getText());
                operation.setText("/");
                value2.setText(null);

            }
        });


        button_C.setBackground(new Color(60, 179, 113));
        button_C.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                value2.setText(null);
                value1.setText(null);
                operation.setText(null);
            }
        });
        button_C.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button_C.setBounds(71, 138, 50, 31);
        frmCalculator.getContentPane().add(button_C);
        button_Div.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button_Div.setBounds(191, 180, 50, 31);
        frmCalculator.getContentPane().add(button_Div);


        button_Mul.setBackground(new Color(192, 192, 192));
        button_Mul.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                value1.setText(value2.getText());
                operation.setText("*");
                value2.setText(null);
            }
        });
        button_Mul.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button_Mul.setBounds(191, 222, 50, 31);
        frmCalculator.getContentPane().add(button_Mul);


        button_Add.setBackground(new Color(192, 192, 192));
        button_Add.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                value1.setText(value2.getText());
                operation.setText("+");
                ope = "+";
                value2.setText(null);

            }
        });
        button_Add.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button_Add.setBounds(191, 306, 50, 31);
        frmCalculator.getContentPane().add(button_Add);


        button_Sub.setBackground(new Color(192, 192, 192));
        button_Sub.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                value1.setText(value2.getText());
                operation.setText("-");
                value2.setText(null);
            }
        });
        button_Sub.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button_Sub.setBounds(191, 264, 50, 31);
        frmCalculator.getContentPane().add(button_Sub);


        button_Dot.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String num = value2.getText() + button_Dot.getText();           //value.setText(value.getText()+Button)
                value2.setText(num);
            }
        });
        button_Dot.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button_Dot.setBounds(131, 306, 50, 31);
        frmCalculator.getContentPane().add(button_Dot);


        button_rec.setBackground(new Color(192, 192, 192));
        button_rec.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                double ops1 = Double.parseDouble(String.valueOf(value2.getText()));
                double ops2 = Double.parseDouble(String.valueOf(value2.getText()));
                ops1 = 1/ops2;
                value2.setText(String.valueOf(ops1));
                value1.setText("reciproc("+String.valueOf(ops2)+")");
            }
        });

                                                //ALT+251
        button_Sqr.setBackground(new Color(192, 192, 192));
        button_Sqr.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                double ops = Double.parseDouble(String.valueOf(value2.getText()));
                ops = Math.sqrt(ops);
                value2.setText(String.valueOf(ops));
                value1.setText("sqrt("+String.valueOf(ops*ops)+")");
            }
        });
        button_Sqr.setFont(new Font("Cambria Math", Font.PLAIN, 13));
        button_Sqr.setBounds(131, 138, 50, 31);
        frmCalculator.getContentPane().add(button_Sqr);
        button_rec.setFont(new Font("Cambria Math", Font.PLAIN, 11));
        button_rec.setBounds(249, 222, 50, 31);
        frmCalculator.getContentPane().add(button_rec);

                                                //ALT+0177
        button_neg.setBackground(new Color(192, 192, 192));
        button_neg.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                double ops = Double.parseDouble(String.valueOf(value2.getText()));
                ops = ops * (-1);
                value2.setText(String.valueOf(ops));
                value1.setText("negate("+String.valueOf(ops*-1)+")");
            }
        });
        button_neg.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button_neg.setBounds(191, 138, 50, 31);
        frmCalculator.getContentPane().add(button_neg);


        button_per.setBackground(new Color(192, 192, 192));
        button_per.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                double ops = Double.parseDouble(String.valueOf(value2.getText()));
                ops = ops * (100);
                value2.setText(String.valueOf(ops));
                value1.setText(String.valueOf(ops));
            }
        });
        button_per.setBounds(249, 180, 50, 31);
        frmCalculator.getContentPane().add(button_per);


        button_equal.setBackground(new Color(60, 179, 113));
        button_equal.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fNumber = Double.parseDouble(value1.getText());
                sNumber = Double.parseDouble(value2.getText());

                if(operation.getText().equals("+"))
                {
                    result = fNumber + sNumber ; 
                    value1.setText(null);
                    value2.setText(String.valueOf(result));
                }
                else if(operation.getText().equals("-"))
                {
                    result = fNumber - sNumber ; 
                    value1.setText(null);
                    value2.setText(String.valueOf(result));
                }
                else if(operation.getText().equals("*"))
                {
                    result = fNumber * sNumber ; 
                    value1.setText(null);
                    value2.setText(String.valueOf(result));
                }
                else if(operation.getText().equals("/"))
                {
                    result = fNumber / sNumber ; 
                    value1.setText(null);
                    value2.setText(String.valueOf(result));
                }

            }
        });

                                    //ALT+8592
        button_undo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                String bkspace = null;
                if(value2.getText().length() > 0)
                {

                    StringBuilder strB = new StringBuilder(value2.getText());
                    strB.deleteCharAt(value2.getText().length() - 1);
                    bkspace = strB.toString();
                    value2.setText(bkspace);
                }               
            }
        });
        button_undo.setFont(new Font("Cambria Math", Font.PLAIN, 19));
        button_undo.setBounds(10, 138, 50, 31);
        frmCalculator.getContentPane().add(button_undo);
        button_equal.setFont(new Font("Cambria Math", Font.PLAIN, 18));
        button_equal.setBounds(249, 264, 50, 73);
        frmCalculator.getContentPane().add(button_equal);


        btnExit.setBackground(new Color(255, 99, 71));
        btnExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });
        btnExit.setFont(new Font("Cambria Math", Font.PLAIN, 12));
        btnExit.setBounds(11, 348, 51, 23);
        frmCalculator.getContentPane().add(btnExit);

    }

    /**
     * @return the activate_and_Deactivate
     */
    public Object getActivate_and_Deactivate() {
        return Activate_and_Deactivate;
    }

    /**
     * @param activate_and_Deactivate the activate_and_Deactivate to set
     */
    public void setActivate_and_Deactivate(Object activate_and_Deactivate) {
        Activate_and_Deactivate = activate_and_Deactivate;
    }


}














package Calculators;

import javax.swing.JButton;
import javax.swing.JRadioButton;

public class Activate_and_Deactivate extends UIFrame 
{
    public void activate()
    {
        button0.setEnabled(true);
        button1.setEnabled(true);
        button2.setEnabled(true);
        button3.setEnabled(true);
        button4.setEnabled(true);
        button5.setEnabled(true);
        button6.setEnabled(true);
        button7.setEnabled(true);
        button8.setEnabled(true);
        button9.setEnabled(true);
        button_Div .setEnabled(true);
        button_C .setEnabled(true);
        button_Mul.setEnabled(true);
        button_Add.setEnabled(true);
        button_Sub.setEnabled(true);
        button_Dot.setEnabled(true);
        button_rec.setEnabled(true);
        button_Sqr.setEnabled(true);
        button_neg.setEnabled(true);
        button_per .setEnabled(true);
        button_equal.setEnabled(true);
        button_undo .setEnabled(true);
        btnExit .setEnabled(true);
        rdbtnOff.setEnabled(true);
        rdbtnOn.setEnabled(false);
    }

    public void deactivate()
    {
        button0.setEnabled(false);
        button1.setEnabled(false);
        button2.setEnabled(false);
        button3.setEnabled(false);
        button4.setEnabled(false);
        button5.setEnabled(false);
        button6.setEnabled(false);
        button7.setEnabled(false);
        button8.setEnabled(false);
        button9.setEnabled(false);
        button_Div .setEnabled(false);
        button_C .setEnabled(false);
        button_Mul.setEnabled(false);
        button_Add.setEnabled(false);
        button_Sub.setEnabled(false);
        button_Dot.setEnabled(false);
        button_rec.setEnabled(false);
        button_Sqr.setEnabled(false);
        button_neg.setEnabled(false);
        button_per .setEnabled(false);
        button_equal.setEnabled(false);
        button_undo .setEnabled(false);
        btnExit .setEnabled(false);
        rdbtnOn.setEnabled(true);
        rdbtnOff.setEnabled(false);


    }

}

它不起作用。有人能帮我吗。 非常感谢。

1 个答案:

答案 0 :(得分:0)

据我所知,您不能将基类用作派生类的实例。

但是,您可以将派生类的实例存储在基类中,然后在需要时将其强制转换回派生类。有关示例,请参见按钮上的ActionListener

基础

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class SimpleClass extends JFrame {
    public SimpleClass(String title) {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout());
        setUp();
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public SimpleClass() {

    }

    public void setUp() {
        JPanel panel = new JPanel();

        ExtendedClass e = new ExtendedClass();
        SimpleClass s = new ExtendedClass();
        SimpleClass thisInstance = this;

        JButton button = new JButton("Press Me");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                System.out.println(e instanceof ExtendedClass);
                e.printLn();

                System.out.println(s instanceof ExtendedClass);
                ((ExtendedClass)s).printLn();

                System.out.println(thisInstance instanceof ExtendedClass);
                //Returns an exception as it is not an instance of ExtendedClass
                ((ExtendedClass)thisInstance).printLn();
            }
        });

        panel.add(button);
        getContentPane().add(panel);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new SimpleClass("Title"));
    }
}

扩展

@SuppressWarnings("serial")
public class ExtendedClass extends SimpleClass {
    public void printLn() {
        System.out.println("Printed A Line To The Console :)");
    }
}