0

我正在制作一个绘制形状的程序。单击菜单中的形状后,它会根据 jSlider 中的值绘制下面的形状。

我正在尝试创建一个异常,以便当用户尝试将框架调整为小于 DrawPanel 上绘制的形状时。

为此,我想创建一个 if 语句,因此如果框架的宽度或高度小于 xy 位置加上滑块的值,它将引发异常。

绘图:

package ShapesProgram;
//adding the imports
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;

/**
 *
 * @
 */
public class DrawShape extends JPanel {

//Declaring variables 
private boolean isCircle;
private boolean isSquare;
private boolean isTriangle;
private int xPosition = 50;
private int yPosition = 50;
MyFrame shapeFrame;
int length;

//making the frame
public DrawShape(MyFrame f) {
    shapeFrame = f;
    initComponents();
    isCircle = false;
    isSquare = false;
    isTriangle = false;
    this.setBackground(Color.LIGHT_GRAY);
    repaint();
}

public void setLength(int length) {
    this.length = length;
}

//setting the shapes to false
public void setIsCircle(boolean isCircle) {
    this.isCircle = isCircle;
    this.isSquare = false;
    this.isTriangle = false;

}

public void setIsSquare(boolean isSquare) {
    this.isSquare = isSquare;
    this.isCircle = false;
    this.isTriangle = false;
}

public void setIsTriangle(boolean isTriangle) {
    this.isTriangle = isTriangle;
    this.isSquare = false;
    this.isCircle = false;
}

@Override
public void paintComponent(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g);

    if (isSquare == true) {
        // draw a Square
        g2.drawRect(xPosition, yPosition, length, length);
        repaint();
    } else if (isCircle == true) {

        // draw a Circle
        g2.drawOval(xPosition, yPosition, length, length);
        repaint();
    } else if (isTriangle == true) {

        // draw a Trianlge
        int[] xPoints = new int[3];
        int[] yPoints = new int[3];
        xPoints[0] = xPosition;
        xPoints[1] = xPoints[0];
        xPoints[2] = xPoints[1] + length;
        yPoints[0] = yPosition;
        yPoints[1] = yPoints[0] + length;
        yPoints[2] = yPoints[1];
        g2.drawPolyline(xPoints, yPoints, xPoints.length);
        g2.drawLine(xPoints[0], yPoints[0], xPoints[2], yPoints[2]);

        repaint();
    }

}

/**
 * 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.
 */
@SuppressWarnings("unchecked")
// <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                   
}

我的控制面板:

package ShapesProgram;
//adding the imports
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.text.DecimalFormat;
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 JPanel {

//making a new slider
private ChangeListener sliderAction = new MyChangeAction();
JSlider thejSlider = new JSlider(0, 100);
//creating the labels for Boundary Length, Slider and Area
JLabel lblLenght = new JLabel("Boundary Length");
JLabel lblSlider = new JLabel("Slider");
JLabel lblArea = new JLabel("Area");
//creating the textFields for the Area and Boundary Lengrth
JTextField txtArea = new JTextField(8);
JTextField txtBLength = new JTextField(8);
MyFrame MyControlPanelFrame;
//Constraints required for GridBagLayout
GridBagConstraints gbc = new GridBagConstraints();

public MyControlPanel(MyFrame f) {

    MyControlPanelFrame = f;
    initComponents();

    //setting background color and layout for the frame
    this.setBackground(Color.gray);
    this.setLayout(new GridBagLayout());


    //setting up slider and adding it to the frame 
    thejSlider.setMajorTickSpacing(10);
    thejSlider.setPaintLabels(true);
    thejSlider.setPaintTicks(true);
    gbc.gridx = 14;
    gbc.gridy = 11;
    this.add(thejSlider, gbc);

    //addig the label for the slider to the frame
    this.add(lblSlider, gbc);
    gbc.gridx = 4;
    gbc.gridy = 11;

    //adding the label for the area to the frame
    this.add(lblArea, gbc);
    gbc.gridx = 10;
    gbc.gridy = 11;

    //adding the textField for area to the frame
    this.add(txtArea, gbc);
    gbc.gridx = 2;
    gbc.gridy = 10;
    gbc.gridwidth = 4;

    //adding the label for boundary length to the frame
    this.add(lblLenght, gbc);
    gbc.gridx = 10;
    gbc.gridy = 10;

    //adding the textField for boundary length to the frame
    this.add(txtBLength, gbc);
    gbc.gridx = 14;
    gbc.gridy = 10;


    linkEventHandler();


}
//creating the event handler for the slider action

public void linkEventHandler() {
    thejSlider.addChangeListener(sliderAction);

}

class MyChangeAction implements ChangeListener {

    @Override
    public void stateChanged(ChangeEvent e) {

        //obtain jslider value
        int currentValue = thejSlider.getValue();
        //passing the value of the slider to the draw panel
        MyControlPanelFrame.getDrawPanel().setLength(currentValue);
        //setting the format for the numbers
        DecimalFormat df = new DecimalFormat("0.0");


        //obtain the shape
        //calculate Area
        double x = MyControlPanelFrame.getMyShape().computeArea(currentValue);
        //display area
        txtArea.setText(df.format(x));

        //obtain the shape
        //calculate boundary length
        double y = MyControlPanelFrame.getMyShape().computeBLength(currentValue);
        //display boundary length
        txtBLength.setText(df.format(y));



        //repaint the shape
        MyControlPanelFrame.getDrawPanel().repaint();



    }

}

/**
 * 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.
 */
@SuppressWarnings("unchecked")
// <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                   
}

我的框架:

package ShapesProgram;
//adding the imports
import MyShape.Circle;
import MyShape.MyShape;
import MyShape.Square;
import MyShape.Triangle;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/**
*
* @
*/
public final class MyFrame extends javax.swing.JFrame {

MyShape myShape = new MyShape();

//creating a new JMenuBar
JMenuBar jMenuBar1 = new JMenuBar();
JMenu shape = new JMenu("Shape");

//creating new JMenuItems dor the shapes
JMenuItem circle = new JMenuItem("Circle");
JMenuItem square = new JMenuItem("Square");
JMenuItem triangle = new JMenuItem("Triangle");

MyControlPanel panel1 = new MyControlPanel(this);
DrawShape drawPanel = new DrawShape(this);

//Creates new form MyFrame
public MyFrame() {

    //setting the size, title and minimum size of the frame
    this.setSize(400, 400);
    this.setMinimumSize(new Dimension(400, 400));
    this.setTitle("Shapes Program");

    initComponents();
    linkListeners();

    //setting the layout for the frame
    this.setLayout(new BorderLayout());

    //adding the components to the frame
    shape.add(square);
    shape.add(circle);
    shape.add(triangle);
    jMenuBar1.add(shape);

    setJMenuBar(jMenuBar1);

    //adding the panels to the frame 
    this.add(panel1, BorderLayout.SOUTH);
    this.add(drawPanel, BorderLayout.CENTER);

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}



//creating a new action listener for the shapes
public void linkListeners() {
    MyActionListener l = new MyActionListener();
    circle.addActionListener(l);
    square.addActionListener(l);
    triangle.addActionListener(l);

}

class MyActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {


        Object obj = e.getSource();

        //when square is selected, it is set to visable 
        //and outputs "Square Selected
        if ((JMenuItem) obj == square) {
            myShape = new Square();
            drawPanel.setIsSquare(true);
            System.out.println("Square Selected");

            //when circle is selected, it is set to visable 
            //and outputs "Circle Selected
        } else if ((JMenuItem) obj == circle) {
            myShape = new Circle();
            drawPanel.setIsCircle(true);
            System.out.println("Circle Selected");

            } 

            //when triangle is selected, it is set to visable 
            //and outputs "Triangle Selected
          else if ((JMenuItem) obj == triangle) {
            myShape = new Triangle();
            drawPanel.setIsTriangle(true);
            System.out.println("Triangle Selected");

        }
    }
}

public DrawShape getDrawPanel() {
    return drawPanel;

}

public MyShape getMyShape() {
    return myShape;
}

/**
 * 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.
 */
@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);
            DecimalFormat oneDigit = new DecimalFormat("#,##0.0");

        }
    });
}
// Variables declaration - do not modify                     
// End of variables declaration                   
}

我的框架:

package ShapesProgram;
//adding the imports
import MyShape.Circle;
import MyShape.MyShape;
import MyShape.Square;
import MyShape.Triangle;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/**
*
* @
*/
public final class MyFrame extends javax.swing.JFrame {

MyShape myShape = new MyShape();

//creating a new JMenuBar
JMenuBar jMenuBar1 = new JMenuBar();
JMenu shape = new JMenu("Shape");

//creating new JMenuItems dor the shapes
JMenuItem circle = new JMenuItem("Circle");
JMenuItem square = new JMenuItem("Square");
JMenuItem triangle = new JMenuItem("Triangle");

MyControlPanel panel1 = new MyControlPanel(this);
DrawShape drawPanel = new DrawShape(this);

//Creates new form MyFrame
public MyFrame() {

    //setting the size, title and minimum size of the frame
    this.setSize(400, 400);
    this.setMinimumSize(new Dimension(400, 400));
    this.setTitle("Shapes Program");

    initComponents();
    linkListeners();

    //setting the layout for the frame
    this.setLayout(new BorderLayout());

    //adding the components to the frame
    shape.add(square);
    shape.add(circle);
    shape.add(triangle);
    jMenuBar1.add(shape);

    setJMenuBar(jMenuBar1);

    //adding the panels to the frame 
    this.add(panel1, BorderLayout.SOUTH);
    this.add(drawPanel, BorderLayout.CENTER);

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}



//creating a new action listener for the shapes
public void linkListeners() {
    MyActionListener l = new MyActionListener();
    circle.addActionListener(l);
    square.addActionListener(l);
    triangle.addActionListener(l);

}

class MyActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {


        Object obj = e.getSource();

        //when square is selected, it is set to visable 
        //and outputs "Square Selected
        if ((JMenuItem) obj == square) {
            myShape = new Square();
            drawPanel.setIsSquare(true);
            System.out.println("Square Selected");

            //when circle is selected, it is set to visable 
            //and outputs "Circle Selected
        } else if ((JMenuItem) obj == circle) {
            myShape = new Circle();
            drawPanel.setIsCircle(true);
            System.out.println("Circle Selected");

            } 

            //when triangle is selected, it is set to visable 
            //and outputs "Triangle Selected
          else if ((JMenuItem) obj == triangle) {
            myShape = new Triangle();
            drawPanel.setIsTriangle(true);
            System.out.println("Triangle Selected");

        }
    }
}

public DrawShape getDrawPanel() {
    return drawPanel;

}

public MyShape getMyShape() {
    return myShape;
}

/**
 * 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.
 */
@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);
            DecimalFormat oneDigit = new DecimalFormat("#,##0.0");

        }
    });
}
// Variables declaration - do not modify                     
// End of variables declaration                   
}

圆圈:

package MyShape;

/**
*
* @
*/
public class Circle extends MyShape {


@Override
public double computeArea(int length) {
    return length*length*Math.PI;
}


@Override
public double computeBLength(int length) {
    return 2*length*Math.PI;
}

}

正方形:

package MyShape;

/**
*
* @
*/
public class Square extends MyShape {

@Override
public double computeArea(int length) {
  return length*length;
}

@Override
public double computeBLength(int length) {
   return 4*length;
}

}

三角形:

package MyShape;

/**
*
* @
*/
public class Triangle extends MyShape {

@Override
public double computeArea(int length) {
    return length * 2 + Math.sqrt (2 * length * length);
}

@Override
public double computeBLength(int length) {
    return length * length / 2;
}

}
4

0 回答 0