Search code examples
javaappletjframejpaneljapplet

Panels showing on Applet but not on Application mode


I'm trying to finish homework given to me, I was asked to create a "painter" that paints rectangles and circles, with the ability to remove them using the minus button etc.. The last task was to make the application able to run both as an applet and an application.. I tried to follow my teacher's instructions on how to make an application to work both as an applet and an application and now the panels show on the frame only in the applet mode.

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
public class HW4 extends JApplet {
private final String[] EraseComboBoxList = { "None", "All", "Rect",
        "Circle" };
private final Dimension EraseShapeColorPanelDim = new Dimension(130, 65);
private final Dimension ControlPanelDim = new Dimension(200, 600);
private final int PanelsBorderThickness = 3;
private final int ControlPanelHGap = 50;
private final int ControlPanelVGap = 20;
private final static int FrameHGap = 10;
private final static int FrameVGap = 0;
private final static Dimension FramePanelDim = new Dimension(800, 600);
private JTextArea drawnShapes = new JTextArea(11, 12);
private ArrayList<Shape> shapeList = new ArrayList<Shape>();
private static Shape tempShape;
private boolean draw = false;
ControlPanel controlPanel = new ControlPanel(); 
PainterPanel paintPanel = new PainterPanel();

public HW4() {
    tempShape = new Shape();
    setBackground(Color.LIGHT_GRAY);
    add(paintPanel, BorderLayout.CENTER);
    setANDrequestFocus();
    add(controlPanel, BorderLayout.EAST);
}
public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new HW4());
    frame.setSize(FramePanelDim);
    frame.setTitle("My Painter");
    frame.setLayout(new BorderLayout(FrameHGap, FrameVGap));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setAlwaysOnTop(true);
    frame.setVisible(true);
}

private class PainterPanel extends JPanel {

    private PainterPanel() {
        setBorder(new LineBorder(Color.GRAY, PanelsBorderThickness));
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent mouseRelease) {
                if ((Math.abs(tempShape.startX - tempShape.width) + Math
                        .abs(tempShape.startY - tempShape.height)) != 0) {
                    Shape shape = new Shape();
                    shape.color = tempShape.color;
                    shape.shape = tempShape.shape;
                    shape.filled = tempShape.filled;
                    shape.startX = tempShape.startX;
                    shape.startY = tempShape.startY;
                    shape.width = tempShape.width;
                    shape.height = tempShape.height;
                    shapeList.add(shape);
                    appendToTextArea(shape);
                }
                draw = false;
            }

            @Override
            public void mousePressed(MouseEvent mousePress) {

                tempShape.startX = mousePress.getX();
                tempShape.startY = mousePress.getY();
                tempShape.width = mousePress.getX();
                tempShape.height = mousePress.getY();
                draw = true;
            }
        });
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent mouseDrag) {
                tempShape.width = mouseDrag.getX();
                tempShape.height = mouseDrag.getY();
                repaint();
            }
        });
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        int startX, startY, width, height;
        setANDrequestFocus();
        for (int i = 0 ; i < shapeList.size() ; i++) {
            startX = Math.min(shapeList.get(i).startX, shapeList.get(i).width);
            startY = Math.min(shapeList.get(i).startY, shapeList.get(i).height);
            width = Math.abs((shapeList.get(i).startX - shapeList.get(i).width));
            height = Math.abs((shapeList.get(i).startY - shapeList.get(i).height));
            g2d.setColor(shapeList.get(i).color);
            g2d.setStroke(new BasicStroke(3));
            if ((width != 0) && (height != 0)) {
                if (shapeList.get(i).shape.equals("Rect")) {
                    if (shapeList.get(i).filled) {
                        g2d.fillRect(startX, startY, width, height);
                    } 
                    else {
                        g2d.drawRect(startX, startY, width, height);
                    }
                } 
                else {
                    if (shapeList.get(i).filled) {
                        g2d.fillOval(startX, startY, width, height);
                    } 
                    else {
                        g2d.drawOval(startX, startY, width, height);
                    }
                }
            }
        }
        if (draw) {
        startX = Math.min(tempShape.startX, tempShape.width);
        startY = Math.min(tempShape.startY, tempShape.height);
        width = Math.abs(tempShape.startX - tempShape.width);
        height = Math.abs(tempShape.startY - tempShape.height);
        g2d.setColor(tempShape.color);
        g2d.setStroke(new BasicStroke(3));
        if ((width != 0) && (height != 0)) {
            if (tempShape.shape.equals("Rect")) {
                if (tempShape.filled) {
                    g2d.fillRect(startX, startY, width, height);
                } 
                else {
                    g2d.drawRect(startX, startY, width, height);
                }
            } 
            else {
                if (tempShape.filled) {
                    g2d.fillOval(startX, startY, width, height);
                } 
                else {
                    g2d.drawOval(startX, startY, width, height);
                }
            }
        }
    }
    }
}

private class ControlPanel extends JPanel implements ActionListener {
    private JComboBox<String> eraseComboBox = new JComboBox<String>(EraseComboBoxList);
    private JPanel erasePanel;
    private JScrollPane scrollPane = new JScrollPane(drawnShapes,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    private JPanel shapePanel;
    private JRadioButton shapeRect = new JRadioButton("Rect", true);
    private JRadioButton shapeCircle = new JRadioButton("Circle");
    private JPanel colorPanel;
    private JRadioButton colorRed = new JRadioButton("Red");
    private JRadioButton colorBlue = new JRadioButton("Blue", true);
    private JCheckBox fillCheckBox = new JCheckBox("Fill");
    private ControlPanel() {
        createControlPanel();
    }
    public void createControlPanel() {
        setLayout(new FlowLayout(FlowLayout.CENTER, ControlPanelHGap,
                ControlPanelVGap));
        setPreferredSize(ControlPanelDim);
        createErasePanel();
        createShapePanel();
        createColorPanel();
        createFillCheckBox();
        addKeyListeners();
        drawnShapes.setEditable(false);
        add(erasePanel);
        add(shapePanel);
        add(colorPanel);
        add(fillCheckBox);
        add(scrollPane);
        setBorder(new LineBorder(Color.GRAY, PanelsBorderThickness));
    }
    public void createErasePanel() {
        erasePanel = new JPanel();
        erasePanel.setBorder(new TitledBorder("Erase"));
        eraseComboBox.setToolTipText("Please select which type of shapes you would like to remove");
        eraseComboBox.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (eraseComboBox.getSelectedItem().equals("Rect")) {
                    for (int i = 0; i < shapeList.size(); i++) {
                        if ((shapeList.get(i).shape).equals("Rect")) {
                            shapeList.remove(i);
                            --i;
                        }
                    }
                    removeReWriteTextArea();
                    paintPanel.repaint();
                }
                if (eraseComboBox.getSelectedItem().equals("Circle")) {
                    for (int i = 0; i < shapeList.size(); i++) {
                        if ((shapeList.get(i).shape).equals("Circle")) {
                            shapeList.remove(i);
                            --i;
                        }
                    }
                    removeReWriteTextArea();
                    paintPanel.repaint();
                }
                if (eraseComboBox.getSelectedItem().equals("All")) {
                    for (int i = 0; i < shapeList.size(); i++) {
                            shapeList.remove(i);
                            --i;
                    }
                    removeReWriteTextArea();
                    paintPanel.repaint();
                }
            }
        });
        erasePanel.add(eraseComboBox);
        erasePanel.setPreferredSize(EraseShapeColorPanelDim);
    }
    public void createShapePanel() {
        shapePanel = new JPanel();
        shapePanel.setBorder(new TitledBorder("Shape"));
        ButtonGroup shapeGroup = new ButtonGroup();
        shapeGroup.add(shapeRect);
        shapeGroup.add(shapeCircle);
        shapeRect.setMnemonic('R');
        shapeCircle.setMnemonic('C');
        shapeRect.addActionListener(this);
        shapeCircle.addActionListener(this);
        shapePanel.add(shapeRect);
        shapePanel.add(shapeCircle);
        shapePanel.setPreferredSize(EraseShapeColorPanelDim);
    }
    public void createColorPanel() {
        colorPanel = new JPanel();
        colorPanel.setBorder(new TitledBorder("Color"));
        ButtonGroup colorGroup = new ButtonGroup();
        colorGroup.add(colorRed);
        colorGroup.add(colorBlue);
        colorRed.setMnemonic('e');
        colorBlue.setMnemonic('B');
        colorBlue.addActionListener(this);
        colorRed.addActionListener(this);
        colorPanel.add(colorRed);
        colorPanel.add(colorBlue);
        colorPanel.setPreferredSize(EraseShapeColorPanelDim);
    }
    public void createFillCheckBox() {
        fillCheckBox.setMnemonic('F');
        fillCheckBox.addActionListener(this);
    }
    public void addKeyListeners() {
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_MINUS) {
                    if (shapeList.size() > 0) {
                    shapeList.remove(shapeList.size()-1);
                    shapeList.trimToSize();
                    removeReWriteTextArea();
                    paintPanel.repaint();
                    }
                }
            }
        });
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        tempShape.shape = "Rect";
        if (shapeCircle.isSelected()) {
            tempShape.shape = "Circle";
        }
        tempShape.color = Color.BLUE;
        if (colorRed.isSelected()) {
            tempShape.color = Color.RED;
        }
        tempShape.filled = false;
        if (fillCheckBox.isSelected()) {
            tempShape.filled = true;
        }
    }
}

private class Shape {
    private boolean filled = false;
    private Color color = Color.BLUE;
    private String shape = "Rect";
    private int startX, startY, width, height;
    public String getColorString() {
        if (color == Color.RED) {
            return "Red";
        }
        else {
            return "Blue";
        }
    }
}
private void setANDrequestFocus() {
    controlPanel.setFocusable(true);
    controlPanel.requestFocusInWindow();
}
public void removeReWriteTextArea() {
    drawnShapes.setText(null);
    for(int i = 0; i < shapeList.size(); i++) {
        appendToTextArea(shapeList.get(i));
    }
}
public void appendToTextArea(Shape shape) {
    String append = shape.shape + ", " + shape.getColorString() + ", " + "fill = " + shape.filled;
            drawnShapes.append(append + "\n");
}
}

Solution

  • The simplistic solution is:

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JApplet hw4 = new HW4();
        hw4.init();
        hw4.start();
        frame.add(hw4);
        frame.setSize(FramePanelDim);
        frame.setTitle("My Painter");
        //frame.setLayout(new BorderLayout(FrameHGap, FrameVGap));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        //frame.setResizable(false);
        //frame.setAlwaysOnTop(true);
        frame.setVisible(true);
        frame.pack();
    }
    

    Note that:

    1. 'adding an applet to a frame' is not the best way to go about creating an hybrid. It is better to create the GUI in a JPanel that is added to the JApplet or JFrame (or another JPanel or a JDialog or..) as needed.
    2. We should not try to create a constructor for an applet, and if we do, we should beware the fact that it is not called on the EDT.
    3. Please refer the teacher to Why CS teachers should stop teaching Java applets.