gpt4 book ai didi

java - 如何使用 setBorder 和 JFrame 在 Java 中为矩形添加边框

转载 作者:行者123 更新时间:2023-12-03 18:59:05 26 4
gpt4 key购买 nike

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

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 函数中添加它时:

start.setBorder(blackline);

它给我错误:

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

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

最佳答案

  1. Rectangle 没有 setBorder 方法,而是使用 Graphics#setColor(Color ) 并使用 Graphics#drawRect(int, int, int, int)Graphics2D#draw(Shape)
  2. 你正在打破油漆链。绘画由一系列链式方法调用组成,当调用正确时,绘制当前组件及其子组件。通过不调用 super.paint,您可以防止这样做,并可能导致许多令人讨厌的副作用,这些都不是您真正想要的......
  3. 出于多种原因,您应该避免覆盖顶级容器的 paint,例如 JFrame;它们不是双缓冲的;框架顶部还有许多其他组件可能会在其上绘制(paint);等。相反,创建一个自定义组件,从类似 JPanel 的东西扩展并覆盖它的 paintComponent 方法(确保您首先调用 super.paintComponent )...

参见 Painting in AWT and Swing , Performing Custom Painting2D Graphics了解更多详情

关于java - 如何使用 setBorder 和 JFrame 在 Java 中为矩形添加边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com