简体   繁体   中英

Change background and font color of jpanel on button click

I want to change Background color of Jpanel and its font on button click.

Can anyone tell me what i am doing wrong? Can I set JPanel background transparent?if yes How?

On button click test4.action method is called where i need to change Jpanel background color?

Here is the code:

import java.applet.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import javax.swing.*;

public class test3 extends Applet {

    JPanel c;
    JScrollPane s;
    Button connect;
    Panel controls;
    Color back, fore;

    public void init() {
        back = Color.black;
        fore = Color.white;
        setBackground(Color.darkGray);
        setLayout(new BorderLayout());
        s = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        //s.setSize(100, 100);
        add("Center", s);
        c = new myCanvas11(this);
        s.setOpaque(false);
        s.setViewportView(c);
        //s.add(c);
        c.setSize(1000, 16000);
        add("North", controls = new Panel());
        controls.setLayout(new FlowLayout());
        controls.add(connect = new Button("Change Color"));
    }

    public void start() {
        // s.setScrollPosition(100, 100);
    }

    public boolean action(Event e, Object arg) {
        back = Color.magenta;
        fore = Color.blue;
        //setBackground(back);
        //invalidate();
        //repaint();
        c.setBackground(back);
        c.repaint();
        //s.getViewport().setBackground(back);
        // s.getViewport().repaint();
        //c.repaint();
        c.setFocusable(true);
        return true;
    }
}

class myCanvas11 extends JPanel implements KeyListener {

    Image buffImage;
    Graphics offscreen;
    boolean initDone = false;
    int chw, chh; // size of a char (in pixels)
    int chd; // offset of char from baseline
    int width, height; // size of applet (in pixels)
    int w, h; // size of applet (in chars)
    Font fn;
    Graphics gr;
    int nh, nw;
    test3 owner;
    static int counter = 0;

    myCanvas11(test3 t) {
        super();
        owner = t;
        nh = 16000;
        nw = 1000;
        this.setOpaque(true);
        this.setFocusable(true);
        addKeyListener(this);
    }

    public void reshape(int nx, int ny, int nw1, int nh1) {
        if (nw1 != width || nh1 != height) {
            width = nw;
            height = nh;
            gr = getGraphics();
            fn = new Font("Courier", Font.PLAIN, 11);
            if (fn != null) {
                gr.setFont(fn);
            }
            FontMetrics fnm = gr.getFontMetrics();
            chw = fnm.getMaxAdvance();
            chh = fnm.getHeight();
            chd = fnm.getDescent();
            // kludge for Windows NT and others which have too big widths
            if (chw + 1 >= chh) {
                chw = (chw + 1) / 2;
            }
            // work out size of drawing area
            h = nh / chh;
            w = nw / chw;
            buffImage = this.createImage(nw, nh);
            offscreen = buffImage.getGraphics();
            //offscreen.setColor(Color.black);
            //offscreen.fillRect(0, 0, nw, nh);
            offscreen.setColor(Color.blue);
            offscreen.setFont(fn);
            if (initDone) {
                offscreen.drawString("Hello World!", 0, 50);
            } else {
                offscreen.drawString("khushbu", 2, 50);
            }
            initDone = true;
            offscreen.drawImage(buffImage, 0, 0, this);
        }
        super.reshape(nx, ny, nw, nh);
    }

    public void paint(Graphics g) {
//       if (!initDone)
//       initpaint(g);
//       else
        g.drawImage(buffImage, 0, 0, this);
        //g.drawImage(buffImage, 0, 0, owner.back, this);

    }

    public void update(Graphics g) {
        g.drawImage(buffImage, 0, 0, this);
        super.update(g);
        //g.drawImage(buffImage, 0, 0, owner.back, this);
    }

    public void initpaint(Graphics g) {
        try {
            nh = getHeight();
            nw = getWidth();
            gr = getGraphics();
            fn = new Font("Courier", Font.PLAIN, 11);
            if (fn != null) {
                gr.setFont(fn);
            }
            FontMetrics fnm = gr.getFontMetrics();
            chw = fnm.getMaxAdvance();
            chh = fnm.getHeight();
            chd = fnm.getDescent();
            // kludge for Windows NT and others which have too big widths
            if (chw + 1 >= chh) {
                chw = (chw + 1) / 2;
            }
            // work out size of drawing area
            h = nh / chh;
            w = nw / chw;
            buffImage = this.createImage(nw, nh);
            offscreen = buffImage.getGraphics();
            //offscreen.setColor(Color.black);
            //offscreen.fillRect(0, 0, nw, nh);
            offscreen.setColor(Color.white);
            offscreen.setFont(fn);
            if (initDone) {
                offscreen.drawString("Hello World!", 0, 50);
            } else {
                offscreen.drawString("khushbu", 2, 50);
            }
            initDone = true;
            g.drawImage(buffImage, 0, 0, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {
    }

    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
        String s;
        offscreen.setColor(owner.fore);
        offscreen.setFont(fn);
        for (int i = counter; i < counter + 25; ++i) {
            s = Integer.toString(i);
            offscreen.drawString(s, 3, i * chh);
            offscreen.drawLine(10, i * chh, 160, i * chh);
        }
        //owner.s.setScrollPosition(0, counter * 16);
        counter = counter + 25;
        repaint();
    }

    /** Handle the key released event from the text field. */
    public void keyReleased(KeyEvent e) {
    }

    public boolean keyDown(Event e, int k) {
        String s;
        offscreen.setColor(owner.fore);
        offscreen.setFont(fn);
        for (int i = counter; i < counter + 25; ++i) {
            s = Integer.toString(i);
            offscreen.drawString(s, 3, i * chh);
            offscreen.drawLine(10, i * chh, 160, i * chh);
        }
        //owner.s.setScrollPosition(0, counter * 16);
        counter = counter + 25;
        repaint();
        return true;
    }
} 

Can I set JPanel background transparent?if yes How?

Yes, just call setOpaque(false); on that JPanel. On the contrary, if you want the background to be painted, call setOpaque(true); on that panel.

Additional remarks:

  1. public boolean action(Event e, Object arg) is Deprecated. Add the appropriate listeners instead.
  2. Follow Java coding conventions and use an Uppercase letter for the first character of a class
  3. You should almost never call getGraphics(); on a Component
  4. Don't override public void paint(Graphics g) but protected void paintComponent(Graphics g) . Don't forget to call super.paintComponent if you want the background to be painted
  5. Why do you override reshape?
  6. Why do you create an internal buffer? Swing already has built-in double buffering and they do a much better job.
  7. If you overrode already paint() why do you also override update() ? You are performing the same job twice.
  8. Remove that gr class variable, it does not make any sense. When you use Graphics object, use the one provided as a parameter of the paintComponent method but don't keep a reference to it, as it will be disposed later.
  9. counter does not need to be static . Try to avoid static as much as possible.
  10. Try to avoid so much coupling between your classes. It makes your code harder to maintain and less predictable.
  11. Next time, post an SSCCE with something else than an Applet (a JFrame, for example) unless the problem you are having really requires an Applet to be reproduced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM