Java 如何将按钮置于右上角og jpane
根据您的指示,我决定使用GridBagLayout,但我在面板中定位按钮时也遇到了一个问题按钮应该位于右上角,但它显示在中间,请告诉我代码中的问题是什么`Java 如何将按钮置于右上角og jpane,java,swing,layout,Java,Swing,Layout,根据您的指示,我决定使用GridBagLayout,但我在面板中定位按钮时也遇到了一个问题按钮应该位于右上角,但它显示在中间,请告诉我代码中的问题是什么` import java.awt.ComponentOrientation; import java.awt.EventQueue; import java.awt.GridBagConstraints; import javax.swing.JButton; import javax.swing.JFrame; import javax.s
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
public class Test extends JFrame {
private JPanel contentPane;
private JButton button2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 573, 410);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new GridBagLayout());
contentPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
setContentPane(contentPane);
button2 = new JButton("button2");
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
contentPane.add(button2, c);
}
}
这就是输出
这正是不推荐绝对布局的原因 最好的方法是使用
GridBagLayout
之类的工具,它将定位元素,然后让它们随着屏幕大小和形状的改变而移动
关于
GridBagLayout
的在线文档和教程很多,可以帮助您入门。您还可以使用某些IDE中内置的工具(例如NetBeans有一个很好的工具)让您以图形方式布局。因为答案只是要求布局-现在是布局推荐时间
我最喜欢的-它满足了我上一个Swing项目的所有布局需求<代码>换行,
span x
和中心
布局参数应该是实现图片功能所需的全部参数。NetBeans IDE有一个很好的GUI编辑器,可以生成如上所述的代码。谢谢你,但是我尝试了很多次GridBagLayout,但是我失败了,尽管我读了很多教程,但还是有一些困难