如何将对象放在JFrame上的特定位置(x,y)?
答案 0 :(得分:10)
在这里找到Absolute Positioning Tutorials。请仔细阅读,为什么不鼓励使用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();
}
});
}
}
答案 1 :(得分:3)
尝试这两个......相互结合......
setLocation()
和setBounds()
使用GroupLayout更好,它是由NetBeans团队在2005年开发的.WindowsBuilder Pro是一个很好的工具,用于在java中构建Gui
答案 2 :(得分:2)
查看此绝对布局代码示例:
答案 3 :(得分:2)
在继承框架的类中:
setLayout(null);
在您的组件中:
setLocation(x,y);