java - 面板在 Applet 上显示,但在应用程序模式下不显示

标签 java applet jframe jpanel japplet

我正在尝试完成给我的作业,我被要求创建一个“画家”来绘制矩形和圆形,并且能够使用减号按钮等删除它们。 最后一个任务是使应用程序能够同时作为小程序和应用程序运行。 我尝试按照老师关于如何使应用程序既作为小程序又作为应用程序工作的说明进行操作,现在面板仅在小程序模式下显示在框架上。

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

最佳答案

简单的解决方案是:

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. “向框架添加小程序”并不是创建混合体的最佳方法。最好在添加到 JAppletJPanel 中创建 GUI JFrame (或另一个 JPanelJDialog 或..)根据需要。
  2. 我们不应该尝试为小程序创建构造函数,如果这样做,我们应该注意它不会在 EDT 上调用。
  3. 请老师引用Why CS teachers should stop teaching Java applets .

关于java - 面板在 Applet 上显示,但在应用程序模式下不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32889841/

相关文章:

java - H2:如何判断表是否存在?

java - 使用 ehcache 编写自定义 RefreshAheadCacheFactory

firefox - 小程序部署javafx 2.2、firefox、ubuntu

java - 小程序无法在 Firefox 上加载

java 从导入的子类访问父方法

java - 退出两个 JFrame 之一同时退出两个 JFrame

java - 如何配置 Tika 的 pom.xml 以停止获取所有许可证依赖性警告?

java - 如何更改java小程序的消息框标题?

java - 单击按钮时关闭 JFrame Pane

java - 枚举样式工厂作为 Java 中的内部枚举