在JFrame中将绘制的内容居中可以通过以下步骤实现:
以下是一个示例代码:
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CenteredContentExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Centered Content Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(null);
JPanel content = new JPanel();
content.setSize(200, 150);
int frameWidth = frame.getWidth();
int frameHeight = frame.getHeight();
int contentWidth = content.getWidth();
int contentHeight = content.getHeight();
int x = (frameWidth - contentWidth) / 2;
int y = (frameHeight - contentHeight) / 2;
content.setBounds(x, y, contentWidth, contentHeight);
frame.add(content);
frame.setVisible(true);
}
}
这个示例代码创建了一个JFrame对象,并设置其大小为400x300。然后创建了一个JPanel对象作为要绘制的内容,并设置其大小为200x150。通过计算得到JFrame和内容的宽度和高度,并计算出内容的起始坐标。最后将内容添加到JFrame中,并设置JFrame可见。
推荐的腾讯云相关产品:无
领取专属 10元无门槛券
手把手带您无忧上云