用窗体的大小减去组件的大小除以2即可活的居中的位置
代码示例,我写的:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame
{
private JButton button;
public Test()
{
super("按钮居中显示示例");
button=new JButton("满意答案");
button.setSize(100,50);
Container rongqi=this.getContentPane();
rongqi.setLayout(null);
rongqi.add(button);
setSize(400,200);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//关键代码,设置按钮位置
button.setBounds((this.getWidth()-button.getWidth()-5)/2,(this.getHeight()-28-button.getHeight())/2,
button.getWidth(),button.getHeight());
setVisible(true);
}
public static void main(String[]args)
{
new Test();
}
}
温馨提示:答案为网友推荐,仅供参考