Java,听众建议,摇摆组合

时间:2012-10-22 17:34:30

标签: java swing compiler-errors jframe jpanel

感谢你为我看这个,这是我的问题:

我的MyFrame类中的我的If语句说“MyShape是抽象的,无法实例化” 我也不知道如何完成我的actionlistener,以便它创建一个我从jmenu中选择的形状的实例。最后将我的Jslider的尺寸设置为我的sqaure的大小和面积,并将其添加到JtextField。

  1. 如何修复错误“MyShape是抽象的,无法实例化”?
  2. 有关如何完成if语句的任何提示,以便我选择的形状链接到我的Jslider,所以它的值是否添加到该形状,即方形或圆形类?
  3. 我如何将2种方法放在找到该类的长度和面积上,即方形或圆形到2个Jtext字段?
  4. 我很乐意为你提供任何帮助,如果你能解释我需要做什么,这对于像我这样可以理解的编程菜鸟来说是一个简单的方法:)


    MyFrame


        package assignment;
    
        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;
        import javax.swing.JMenu;
        import javax.swing.JMenuBar;
        import javax.swing.JMenuItem;
    
    
        public class MyFrame extends javax.swing.JFrame {
    
    
        public MyFrame() {
    
    
        // Create the menu
        JMenuBar topMenu = new JMenuBar();
        this.setJMenuBar(topMenu);
    
        //create the menu button "shapes"
        JMenu shapes = new JMenu("Shapes");
        topMenu.add(shapes);
        //Create the 3 shapes for the menu
        JMenuItem square = new JMenuItem("Square");
    
        JMenuItem circle = new JMenuItem("Circle");
        JMenuItem triangle = new JMenuItem("Triangle");
    
        //add shapes to menu
        shapes.add(circle);
        shapes.add(triangle);
        shapes.add(square);
    
        //add the menu
        setJMenuBar(topMenu);
    
    
        MyControlPanel pane = new MyControlPanel();
        this.add(pane);
        }
    
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    
        pack();
        }// </editor-fold>                        
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
    
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyFrame().setVisible(true);
            }
        });
    
        class squareAction implements ActionListener {
    
            public void actionPerformed(ActionEvent e) {
    
                JMenuItem clickedMenu = (JMenuItem) e.getSource();
                if (clickedMenu.getText().equals("Square")) {
                    MyShape ASquare = new MyShape() {
                    };
                } else if (clickedMenu.getText().equals("Circle")) {
                    MyShape Circle = new MyShape();
                } else if (clickedMenu.getText().equals("Triangle")) {
                    MyShape Triangle = new MyShape();
                }
            }
        }
        }
        }
    

    Jpanel - MyControlPanel

        package assignment;
    
        //import java.awt.FlowLayout;
        import java.awt.BorderLayout;
        import java.awt.FlowLayout;
        import javax.swing.GroupLayout;
        import javax.swing.GroupLayout.Alignment;
        import javax.swing.JLabel;
        import javax.swing.JPanel;
        import javax.swing.JSlider;
        import javax.swing.JTextField;
        import javax.swing.event.ChangeEvent;
        import javax.swing.event.ChangeListener;
    
        public class MyControlPanel extends javax.swing.JPanel {
    
    JSlider slider;
    JLabel sliderLabel;
    JLabel sliderdimension;
    JLabel blank;
    JLabel dl;
    JLabel area1;
    
    /**
     * Creates new form MyControlPanel
     */
    public MyControlPanel() {
    
    
        slider = new JSlider();
        slider.setValue(50);
        slider.addChangeListener(new MyChangeAction());
        slider.setMajorTickSpacing(10);
        slider.setPaintLabels(true);
        slider.setPaintTicks(true);
        slider.setBounds(300, 50, 100, 50);
    
        sliderLabel = new JLabel("50");
        blank = new JLabel("     ");
        sliderdimension = new JLabel("Shape Dimension:");
    
        JTextField boundary_length = new JTextField("Boundary Length");
        JTextField area = new JTextField("Area");
    
        dl = new JLabel("Boundary Length =");
        area1 = new JLabel("Area =");
    
        setLayout(new BorderLayout());
    
    
        JPanel sliderPanel = new JPanel();
        sliderPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 0));
    
    
        sliderPanel.add(sliderdimension);
        sliderPanel.add(sliderLabel);
        sliderPanel.add(slider);
        sliderPanel.add(dl);
        sliderPanel.add(boundary_length);
        sliderPanel.add(area1);
        sliderPanel.add(area);
        this.add(sliderPanel, BorderLayout.PAGE_END);
    
    
    
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
    
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>                        
    // Variables declaration - do not modify                     
    // End of variables declaration                   
    
    public class MyChangeAction implements ChangeListener {
    
        //complete code here
        public void stateChanged(ChangeEvent ce) {
            int value = slider.getValue();
            String str = Integer.toString(value);
            sliderLabel.setText(str);
    
    
        }
        } // end class
        }
    

    MyShape的


        package assignment;
    
        public abstract class MyShape
     {
    
    double thelength;
    double thearea;
    
    
    
    public abstract double computeBoundaryLength(double Length);
    
    public abstract double computeArea (double Length);
     }
    

    ASquare


        package assignment;
    
        public class ASquare extends MyShape {
    
    @Override
    public double computeBoundaryLength(double Length) 
    {
        thelength=(4*Length);
        return thelength;
    }
    
    @Override
    public double computeArea(double Length) 
    {
        thearea=(Length*Length);
        return thearea;
    }
    
    }
    

    class shapeAction实现ActionListener {             public void actionPerformed(ActionEvent e){

                JMenuItem clickedMenu = (JMenuItem)e.getSource();
                if (clickedMenu.getText().equals("Square")){
                     //implement abstract methods
                MyShape ASquare = new ASquare();  
                ASquare.addActionListener(new shapeAction());
                }
                else if (clickedMenu.getText().equals("Circle")){ 
                     //implement abstract methods
                    MyShape ACircle = new ACircle();
                ACircle.addActionListener(new shapeAction());
                }
                else if (clickedMenu.getText().equals("Triangle")){ 
                     //implement abstract methods
                    MyShape ATriangle = new ATriangle();
                ATriangle.addActionListener(new shapeAction());   
    

4 个答案:

答案 0 :(得分:3)

  • 您的squareAction应该是听取所有可能的菜单选择(每种形状一个)的类,所以它应该被命名为ShapeMenuAction或类似的东西。如果您希望在选择菜单选项时执行ShapeMenuAction的{​​{1}},您可以创建一个实例并使用actionPerformed方法将其添加到每个MenuItem他们。否则,什么都不会发生。

在MyFrame中:

addActionListener
  • JMenuItem square = new JMenuItem("Square"); square.addActionListener(new ShapeAction()); JMenuItem circle = new JMenuItem("Circle"); circle.addActionListener(new ShapeAction()); JMenuItem triangle = new JMenuItem("Triangle"); triangle.addActionListener(new ShapeAction()); 内,您必须实例化actionPerformed的具体子类。现在除了实例化一个形状之外你什么也没做,你必须在方法结束之前对对象做些什么,对吗?在MyShape中创建一个setShape方法,然后从actionPerformed中调用它,将新创建的形状传递给它。

在ShapeAction中:

MyControlPanel

您必须在MyFrame中创建一个名为myControlPanel的MyControPanel:

    public void actionPerformed(ActionEvent e) {
       JMenuItem clickedMenu = (JMenuItem) e.getSource();
       if (clickedMenu.getText().equals("Square")) {
           MyShape aSquare = new ASquare();
           myControlPanel.setShape(aSquare);
       } else if (clickedMenu.getText().equals("Circle")) {
           MyShape aCircle = new ACircle();
           myControlPanel.setShape(aCircle);             
       } else if (clickedMenu.getText().equals("Triangle")) {                 
           MyShape aTriangle = new MyShape();  
           myControlPanel.setShape(aTriangle);           
       }         
    } 

并添加

private MyControlPanel myControlPanel

之前

myControlPanel = new MyControlPanel();
getContentPane().add(myControlPanel);
  • 现在pack(); ,您可以根据滑块值和所选形状更新标签,每次更改时都会更新。

    私人MyShape造型; public void set Shape(MyShape shape){    this.shape =形状;    updateLabels(); }

答案 1 :(得分:2)

您可能想写:

   MyShape circle = new ASquare();
   MyShape triangle = new ASquare();

取代:

    MyShape circle = new MyShape();

MyShape triangle = new MyShape();

如果您尝试为circletriangle实施新的内联类,您可能需要写一下:

   MyShape circle = new MyShape (){
      //implement abstract methods
   }

   MyShape triangle = new MyShape (){
      //implement abstract methods
   }

答案 2 :(得分:2)

编译器没有谎言 - 你需要使用具体的类。抽象类类型本身无法实例化,因此您可以使用:

MyShape aSquare = new ASquare();

但不是这样:

MyShape aSquare = new MyShape ();

同样如果你有混凝土圈&amp;可用的三角形:

MyShape circle = new MyCircle();
...
MyShape triangle = new MyTriangle();

答案 3 :(得分:2)

该消息表明MyShapeabstract,因此您无法对其进行实例化:

它被定义为抽象的:

public abstract class MyShape {

这意味着你无法做到

new MyShape(); //compilation error

永远记住你不能在Java中实例化抽象类和接口。

您可以实例化既不是抽象也不是接口的具体类。