java怎么让图形界面中的组件居中
3个回答
展开全部
用窗体的大小减去组件的大小除以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();
}
}
代码示例,我写的:
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();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询