JPanel显示在JFrame的右下角

时间:2015-02-15 19:32:17

标签: java swing

我正在尝试添加一个MessagePanel,它将JPanel扩展到JFrame中,以便它只是在中心并占据整个事物,我之前做了很多次但现在由于某种原因它出现在右下角JFrame的四分之一,我无法弄清楚原因。我在它周围添加了一个边框,这样我就可以看到它的位置。有人知道什么是错的吗?

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

public class Book extends JFrame{

    public Book(){
        setLayout(new BorderLayout());
        add(new MessagePanel("My Message"), BorderLayout.CENTER);
    }

    public static void main(String[] args){
        Book f = new Book();
        f.setDefaultCloseOperation(Book.EXIT_ON_CLOSE);
        f.setTitle("Title");
        f.setSize(500, 500);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

//

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;


public class MessagePanel extends JPanel{
    private String message = "";
    private boolean centered;
    private int x = 20;
    private int y = 20;
    private int interval = 10;

    public MessagePanel(){
    }

    public MessagePanel(String message){
        this.message = message;
        this.centered = true;
        setBorder(new LineBorder(Color.BLACK, 2));
    }

    public void setMessage(String message){
        this.message = message;
        repaint();
    }

    public void setCentered(boolean centered){
        this.centered = centered;
        repaint();
    }

    public void setX(int x){
        this.x = x;
        repaint();
    }

    public void setY(int y){
        this.y = y;
        repaint();
    }

    public int getX(){
        return x;
    }

    public int getY(){
        return y;
    }

    public void setInterval(int interval){
        this.interval = interval;
        repaint();
    }

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);

        if(centered){
            FontMetrics fontMetrics = g.getFontMetrics();
            x = (getWidth() / 2) - (fontMetrics.stringWidth(message) / 2);
            y = (getHeight() / 2) + (fontMetrics.getAscent() / 2);

        }
        g.drawString(message, x, y);

    }

    public void moveUp(){
        this.y -= interval;
        repaint();
    }

    public void moveDown(){
        this.y += interval;
        repaint();
    }

    public void moveLeft(){
        this.x -= interval;
        repaint();
    }

    public void moveRight(){
        this.x += interval;
        repaint();
    }
}

1 个答案:

答案 0 :(得分:2)

不要覆盖getX(),setX(...),getY()和setY(...)。

这些是Component类的方法,用于控制组件的位置。

如果要控制文本的位置,请使用不同的变量。