Drawing with paintComponent in Applet Upon Event

佐手、 提交于 2019-12-06 09:43:51

A JApplet class does not have a paintComponent method to override. Note that your compiler won't let you call the actual super method (you think you may be doing this, but you're actually calling super.paintComponents(...), a completely different method).

A bad solution is to override the JApplet's paint method, but I strongly advise you not to do this. Instead you should draw in the paintComponent method of a JPanel and then have the JApplet display that JPanel. Also, you'll want to get into the habit of using the @Override annotation to be sure that you're actually overriding methods you think are.

Sudip Kumar De
/*  * <Applet code=PressButton2 width=600 height=600>  * </Applet> 
*/

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


class MyPanel extends JPanel {
    static String s="n";

    public void paintComponent(Graphics g)  { 
        super.paintComponent(g);

        if(s.equals("g"))
            setBackground(Color.green);
        if(s.equals("b"))
            setBackground(Color.blue);
        if(s.equals("c"))
            setBackground(Color.white);
     }
}

public class PressButton2 extends JApplet {
    MyPanel panel;
    MyPanel screen;
    String s="n";

    JButton green, clear, blue;

    public void init() {
        Container container = getContentPane();
        panel = new MyPanel();
        screen = new MyPanel();
        panel.setLayout(new GridLayout(1, 3));

        green = new JButton("Green");
        blue = new JButton("Blue");
        clear = new JButton("Clear");
        green.addActionListener(new ActionEventHandler1());
        blue.addActionListener(new ActionEventHandler1());
        clear.addActionListener(new ActionEventHandler1());

        panel.add(green);
        panel.add(blue);
        panel.add(clear);

        container.add(panel, BorderLayout.SOUTH);
        container.add(screen);
    }

class ActionEventHandler1 implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        String temp = e.getActionCommand(); 

        if (temp.equals("Green")) {
            MyPanel.s = "g";

            screen.repaint();
        }
        if (temp.equals("Blue")) {
            MyPanel.s = "b";
            screen.repaint();
        }
        if (temp.equals("Clear")) {
            MyPanel.s = "c";
            screen.repaint();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!