如何在Java中使用setBorder和JFrame向矩形添加边框
我正在尝试向如何在Java中使用setBorder和JFrame向矩形添加边框,java,swing,jframe,border,rectangles,Java,Swing,Jframe,Border,Rectangles,我正在尝试向矩形元素添加边框,但由于某些原因,它无法工作,是否与JFrame不兼容?我可以将我的整个JFrame设置为有边框,但它无法用我的矩形找到setboorder。这是我的密码: package trivia; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.a
矩形
元素添加边框,但由于某些原因,它无法工作,是否与JFrame
不兼容?我可以将我的整个JFrame
设置为有边框,但它无法用我的矩形找到setboorder
。这是我的密码:
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
我不知道如何让它识别
setboorder
功能,有人能帮忙吗?非常感谢您的帮助 听起来像是在试图绘制由start
引用的矩形。在这种情况下,您希望调用图形上的方法,而不是矩形上的方法。因此:
g.drawRect(start.x, start.y, start.width, start.height);
Rectangle
没有setBorder
方法,而是使用Graphics\setColor(color)
设置Graphics
上下文的颜色,并使用Graphics\drawRect(int,int,int,int)
或Graphics2D\draw(Shape)
super.paint
就是在阻止你这样做,并且可能会导致任何严重的副作用,而这些都不是你真正想要的paint
,如JFrame
;它们不是双缓冲的;框架顶部还有一堆其他部件,可能会在上面喷漆;等等。相反,创建一个自定义组件,从类似JPanel
的东西扩展,并覆盖它的paintComponent
方法(确保首先调用super.paintComponent
)有关创建矩形后的更多详细信息,我将如何添加边框?只需使用
g.setboorder()
还是什么?哦,我明白了,drawRect
方法实际上在它周围创建了一个边框,谢谢!