如何将对象放置在 JFrame 上的特定位置 (x,y)?
问问题
66325 次
4 回答
10
在这里找到绝对定位教程。请仔细阅读,为什么不鼓励使用LayoutManagers这种方法
要将 JButton 添加到您的 JPanel,您可以使用以下命令:
JButton button = new JButton("Click Me");
button.setBounds(5, 5, 50, 30);
panel.add(button);
在这里尝试这个示例程序:
import java.awt.*;
import javax.swing.*;
public class AbsoluteLayoutExample
{
private void displayGUI()
{
JFrame frame = new JFrame("Absolute Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
JLabel label = new JLabel(
"This JPanel uses Absolute Positioning"
, JLabel.CENTER);
label.setSize(300, 30);
label.setLocation(5, 5);
JButton button = new JButton("USELESS");
button.setSize(100, 30);
button.setLocation(95, 45);
contentPane.add(label);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.setSize(310, 125);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new AbsoluteLayoutExample().displayGUI();
}
});
}
}
于 2012-06-09T16:27:37.467 回答
3
试试这2个……结合起来……
setLocation()
和setBounds()
使用NetBeans团队2005年开发的GroupLayout就更好了。WindowsBuilder Pro是Java构建GUI的好工具
于 2012-06-09T17:08:35.817 回答
2
在继承框架的类中:
setLayout(null);
在您的组件中:
setLocation(x,y);
于 2012-06-09T16:32:37.060 回答
2
查看此绝对布局代码示例:
于 2012-06-09T16:29:43.823 回答