面板显示在Applet上但不在应用程序模式上

时间:2015-10-01 14:15:05

标签: java applet jframe jpanel japplet

我试图完成给我的作业,我被要求创作一个"画家"绘制矩形和圆形,能够使用减号按钮等删除它们。 最后一项任务是使应用程序能够作为applet和应用程序运行。 我尝试按照老师的说明,了解如何使应用程序同时作为applet和应用程序工作,现在面板仅在applet模式下显示在框架上。

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");
}
}

1 个答案:

答案 0 :(得分:1)

简单的解决方案是:

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();
}

请注意:

  1. '向框架添加applet'不是创建混合的最佳方式。最好在JPanel中创建添加到JApplet JFrame(或其他JPanel的GUI根据需要,或者JDialog或..)。
  2. 我们不应该尝试为applet创建一个构造函数,如果我们这样做,我们应该注意它没有在EDT上调用。
  3. 请将教师推荐给Why CS teachers should stop teaching Java applets