本文介绍了如何使用 setBorder 和 JFrame 在 Java 中为矩形添加边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 Rectangle 元素添加边框,但由于某种原因它不起作用,它与 JFrame 不兼容吗?我可以将我的整个 JFrame 设置为有一个边框,但它无法在我的矩形中找到 setBorder.这是我的代码:

I am trying to add a border to a Rectangle element and for some reason it will not work, is it not compatible with JFrame? I can set my entire JFrame to having a border, but it can't find setBorder with my rectangles. Here is my code:

package trivia;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.border.Border;

@SuppressWarnings("serial")
public class Main extends JFrame{

boolean mainMenu = true;
static Color tan = Color.decode("#F4EBC3");
static Color darkGreen = Color.decode("#668284");
static Color buttonColor = Color.decode("#A2896B");
Rectangle header = new Rectangle(0, 0, 500, 100);
Rectangle body = new Rectangle(0, 100, 500, 400);
Rectangle start = new Rectangle(150, 150, 200, 40);

public Main() {
    setTitle("Trivia Game!");
    setSize(500, 500);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
}
@Override
public void paint(Graphics g) {
    Dimension d = this.getSize();
    Border blackline;

    blackline = BorderFactory.createLineBorder(Color.black);
    if(mainMenu = true){
        g.setColor(darkGreen);
        g.fillRect(header.x, header.y, header.width, header.height);
        g.setFont(new Font("Courier", Font.BOLD, 24));
        g.setColor(Color.BLACK);
        drawCenteredString("Trivia Game!", d.width, 125, g);
        g.setColor(tan);
        g.fillRect(body.x, body.y, body.width, body.height);
        g.setColor(buttonColor);
        g.fillRect(start.x, start.y, start.width, start.height);


    }
}
public void drawCenteredString(String s, int w, int h, Graphics g) {
    FontMetrics fm = g.getFontMetrics();
    int x = (w - fm.stringWidth(s)) / 2;
    int y = (fm.getAscent() + (h- (fm.getAscent() + fm.getDescent())) / 2);
    g.drawString(s, x, y);
}

public static void main(String[] args) {
    @SuppressWarnings("unused")
    Main m = new Main();
}

}

当我在我的 paint 函数中添加这个时:

And when I add this in my paint function:

start.setBorder(blackline);

它给了我错误:

The method setBorder(Border) is undefined for the type Rectangle

我不确定如何让它识别 setBorder 函数,有人可以帮忙吗?非常感谢所有帮助!

I am not sure how I can make it recognize the setBorder function, can anyone help? All help is much appreciated!

推荐答案

听起来您正在尝试绘制 start 引用的矩形.在这种情况下,您希望在 Graphics 上调用方法,而不是在 Rectangle 上.所以:

Sounds like you're trying to draw the rectangle referenced by start. In that case, you want to be invoking a method on a Graphics, not on a Rectangle. So:

g.drawRect(start.x, start.y, start.width, start.height);

这篇关于如何使用 setBorder 和 JFrame 在 Java 中为矩形添加边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-24 18:14