无法测试操作,因此无法更新Applet

时间:2016-10-14 23:27:02

标签: java swing applet

我的主要问题是我对实现侦听器类的位置感到困惑,因此无论何时进行操作(无论是按键还是鼠标单击),applet都会更新。我意识到我的编译问题来自我的CanvasPanel类中的CanvasPanel方法,而且我的actionPerformed方法中没有参数。但是在这一点上,我不确定这些听众应该如何正确实施。尝试查看已发布的不同问题,如果它是重复的话,请对不起。

这是我的代码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class WholePanel extends JPanel
{
   private Color foregroundColor, backgroundColor;
   private int currentDiameter, x1, y1;
   private CanvasPanel canvas;
   private JPanel buttonPanel;

   private JRadioButton filledRadio, unfilledRadio;
   private JRadioButton redRadio, greenRadio;
   private boolean fill;
   private Graphics myCircle;

   public WholePanel()
   {
      backgroundColor = Color.CYAN;
      foregroundColor = Color.RED;

      currentDiameter = 100;
      x1 = 200; y1 = 100;

      unfilledRadio = new JRadioButton("Unfilled", true);
      filledRadio = new JRadioButton("Filled", false);
      redRadio = new JRadioButton("Red", true);
      greenRadio = new JRadioButton("Green", false);

      buttonPanel = new JPanel();
      buttonPanel.add(unfilledRadio);
      buttonPanel.add(filledRadio);
      buttonPanel.add(redRadio);
      buttonPanel.add(greenRadio);

      canvas = new CanvasPanel();

      JSplitPane sPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, buttonPanel, canvas);

      setLayout(new BorderLayout());
      add(sPane, BorderLayout.CENTER);
    }

   private class ColorListener implements ActionListener
    {
     public void actionPerformed(ActionEvent event)
      {
          if (redRadio.isSelected()) {
              greenRadio.setSelected(false);
              backgroundColor = Color.RED;
          }
          else if (greenRadio.isSelected()) {
              redRadio.setSelected(false);
              backgroundColor = Color.GREEN;
          }
          // ...extra else/if statements
      }
    } // end of ColorListener


   private class FillListener implements ActionListener
    {
     private boolean fill;

     public void actionPerformed(ActionEvent event)
      {
            if (filledRadio.isSelected()) {
                unfilledRadio.setSelected(false);
                fill = true;
                paintComponent(myCircle);
            }
            else if (unfilledRadio.isSelected()) {
                filledRadio.setSelected(false);
                fill = false;
                paintComponent(myCircle);
            }
      }
    }

   private class CanvasPanel extends JPanel
    {
     public CanvasPanel( )
      {
        addKeyListener(new DirectionListener());
        addMouseListener(new PointListener());

        setBackground(backgroundColor);

        //This method needs to be called for this panel to listen to keys
        //When panel listens to other things, and go back to listen
        //to keys, this method needs to be called again.

        ColorListener.actionPerformed();
        FillListener.actionPerformed();
        requestFocus();
      }


     public void paintComponent(Graphics page)
      {
          super.paintComponent(page);
          setBackground(backgroundColor);

          page.setColor(foregroundColor);
          page.drawOval(x1, y1, currentDiameter, currentDiameter);
          if (fill == true) { 
              page.fillOval(x1, y1, currentDiameter, currentDiameter);
          }
      }

     /** This method is overriden to enable keyboard focus */
     public boolean isFocusable()
      {
        return true;
      }

     private class DirectionListener implements KeyListener 
       {
         public void keyReleased(KeyEvent e) {}
         public void keyTyped(KeyEvent e) {}
         public void keyPressed(KeyEvent e)
          {
            currentDiameter = 100;
            x1 = 200; y1 = 100;
            int keyCode = e.getKeyCode();
            // switch statement here

            }
          }
       } // end of DirectionListener


     public class PointListener implements MouseListener
       {
         public void mousePressed (MouseEvent event)
          {
            canvas.requestFocus();
          }

         public void mouseClicked (MouseEvent event) {}
         public void mouseReleased (MouseEvent event) {}
         public void mouseEntered (MouseEvent event) {}
         public void mouseExited (MouseEvent event) {}

       } // end of PointListener

    } // end of Canvas Panel Class

} // end of Whole Panel Class

1 个答案:

答案 0 :(得分:2)

该代码中的一些主要问题:

  • 您直接调用paintComponent,这是您永远不应该做的事情。而是更改类的状态字段,调用repaint()然后让paintComponent使用state字段来决定它应该绘制什么。
  • 使用图形字段相同 - 不要。而是仅使用JVM为paintComponent方法指定的Graphics对象。 Swing Graphics tutorial will explain this
  • https://jsfiddle.net/ze8pwk1z/
  • 您试图直接调用您的侦听器回调方法,这与侦听器的工作方式完全相反,并否定了使用侦听器的好处。而是 ADD 您将使用它们的组件的侦听器 - 包括将ActionListeners添加到需要它们的按钮,KeyListeners到需要它们的组件,MouseListeners ..等等...

例如,让我们看一个很多更简单的例子,一个使用两个JRadioButton的例子:&/ p>

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

@SuppressWarnings("serial")
public class PartialPanel extends JPanel {
    private static final int PREF_W = 800;
    private static final int PREF_H = 650;
    private static final int CIRC_W = 200;
    private int circleX = 300;
    private int circleY = 200;
    private Color circleColor = null;
    private ButtonGroup buttonGroup = new ButtonGroup();
    private JRadioButton blueButton = new JRadioButton("Blue");
    private JRadioButton redButton = new JRadioButton("Red");

    public PartialPanel() {
        ColorListener colorListener = new ColorListener();
        blueButton.addActionListener(colorListener);
        redButton.addActionListener(colorListener);

        buttonGroup.add(blueButton);
        buttonGroup.add(redButton);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(blueButton);
        buttonPanel.add(redButton);

        add(buttonPanel);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (circleColor != null) {
            g.setColor(circleColor);
            g.fillOval(circleX, circleY, CIRC_W, CIRC_W);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        } else {
            return new Dimension(PREF_W, PREF_H);
        }
    }

    private class ColorListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == blueButton) {
                circleColor = Color.BLUE;
            } else if (e.getSource() == redButton) {
                circleColor = Color.RED;
            }
            repaint();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        PartialPanel mainPanel = new PartialPanel();
        JFrame frame = new JFrame("PartialPanel");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

这里我们将一个ColorListener添加到JRadioButtons。在监听器中,我们改变类的circColor字段的状态,然后调用repaint()。然后paintComponent方法使用circColor的值来决定绘制圆时使用的颜色。