0

I'm currently struggling with the fact, that my the background of my frame is bleeding-trough. As result of that, the "background image" of my frame is always what was behind the frame at the moment it got opened.

How the problem looks like

How the frame does look

Code

import java.awt.Button;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;

import javax.swing.JFrame;

public class launcher extends JFrame{

    Button btn;

    public launcher() {
        this.setSize(400, 300);
        this.setLocationRelativeTo(null);

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                launcher l = new launcher();
                l.setVisible(true);
            }
        });
    }

    public void paint(Graphics g) {     
        String s = "Dieser String steht in der Mitte des Fensters";
        int breite = getSize().width - getInsets().left - getInsets().right;
        int hoehe = getSize().height - getInsets().bottom - getInsets().top;
        Font font = new Font("Serif", Font.BOLD + Font.ITALIC, 15);
        FontMetrics fmetrics = getFontMetrics(font);
        int zeilenMitte = fmetrics.getAscent() - (fmetrics.getAscent() + fmetrics.getDescent()) / 2;

        g.setFont(font);
        g.drawString(s, getInsets().left + (breite - fmetrics.stringWidth(s)) / 2,
                getInsets().top + hoehe / 2 + zeilenMitte);

        g.drawRect(this.getInsets().left + 20, 
                this.getInsets().top + 20, 
                (int)this.getSize().getWidth() - this.getInsets().left - this.getInsets().right - 40,
                (int)this.getSize().getHeight() - this.getInsets().top -  this.getInsets().bottom -40);
        g.setColor(Color.yellow);
        g.fillRect(45, 55, 200, 50);
        g.setColor(Color.blue);

        g.setFont(font);
        g.drawString("gefülltes Rechteck", 50, 80);

    }

}

What I have already tried

I deleted some parts of my code, to see where the problem itself is located. After the tests, I'm pretty sure that the problem is somewhere here (Line 42):

g.drawString(s, getInsets().left + (breite - fmetrics.stringWidth(s)) / 2,
            getInsets().top + hoehe / 2 + zeilenMitte);

After I removed the line, it looks like this (how it should look).

How the frame should look

But of course it isn't my goal, to just remove the line and forget about it...

Note

Please don't complain about the structure of my code. I'm currently learning this new language with following book:

Java 2 SDK v 1.4.0 book of Vorcon

So I'm just trowing some commands together and will mind the structure later.

GreenAtomic
  • 96
  • 11

0 Answers0