Przemysław Malinowski
Przemysław Malinowski

Reputation: 373

Make graphic button to JPanel

I have a nice problem, because I have 3 classes:

  1. WindowFrame - its a class extends JFrame, which will show one of panels inside;
  2. WindowPanel - it is a class extends JPanel. I have layout BoxLayout there. I want switch between other panels in WindowFrame;
  3. GButton - its a class something like normal button, but with my texture on bg and I want adding them easy to WindowPanel by add():

public class GButton extends JComponent implements MouseMotionListener, MouseListener{

    int x, y , w, h; //the coordinates of button
    Graphics2D g2d;

    public GButton(int x, int y){
        this.x = x; this.y = y;
        this.w = 200; this.h = 100;
        ... //add listeners, loading some information etc
    }

    @Override
    public void paintComponent(Graphics g){
        g2d = (Graphics2D) g;
        ...//loading and draw on g2d
        g2d.drawString("asidoaisjdiajsoidj",x,y);
    }

    //code with using events of mouse and so on
}

And when I add button, the texture of button is 50px below y! Next buttons has grown this difference from y. Why? I know that because I check it with help MouseMove event. It isn't a bad size of images or something like that. Why it isn't working, and it paint things in other places? Is simpler way to get same effect? Please answer :)

Upvotes: 1

Views: 264

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347314

You codes a little thin on the ground, however.

  • Don't maintain a reference to the Graphics context. 1. It is reused; 2. It may change between paint cycles. You are required to paint into the graphics context passed to your component
  • You MUST call super.paintComponent, this is incredibly important.

I can't be 100% sure, but you appear that be under the impression that you are required to paint to the x/y position that the button appears on the screen, this is incorrect. The Graphics context has already being translated so that position 0x0 is the top/left corner of your object.

I'd suggest you need to spend some time reading through

Upvotes: 1

Mordechai
Mordechai

Reputation: 16284

Never keep a global reference to Graphics (and as well 2D).

If you do need, call g2d.dispose() at the end of each drawing, obtaining a new graphical context the next time you want to use it.

Upvotes: 0

Related Questions