Ely*_*deh 3 java swing jframe layout-manager null-layout-manager
我试图做两个按钮JFrame,我调用setBounds它们的方法来设置它们的位置和大小,我也传递null给setLayout1 because I want to use组件的setBounds`方法.
现在我想用我的代码做一些事情,每当我调整框架按钮时,装饰将以适当的形式改变,如下面的图片:

我知道可以使用从JPanel类中创建一个对象并向其添加按钮,最后将创建的面板对象添加到框架中,但由于某种原因(由教授指定),我现在不允许这样做.
有什么办法或者你有什么建议吗?
我的代码是这样的:
public class Responsive
{
public static void main(String[] args)
{
JFrame jFrame = new JFrame("Responsive JFrame");
jFrame.setLayout(null);
jFrame.setBounds(0,0,400,300);
JButton jButton1 = new JButton("button 1");
JButton jButton2 = new JButton("button 2");
jButton1.setBounds(50,50,100,100);
jButton2.setBounds(150,50,100,100);
jFrame.add(jButton1);
jFrame.add(jButton2);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
A FlowLayout没有水平间距,一些垂直间距和大边框可以轻松实现.一个null布局管理器是永远的答案,"响应"稳健的GUI.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ResponsiveGUI {
private JComponent ui = null;
ResponsiveGUI() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 8));
ui.setBorder(new EmptyBorder(10,40,10,40));
for (int i=1; i<3; i++) {
ui.add(getBigButton(i));
}
}
public JComponent getUI() {
return ui;
}
private final JButton getBigButton(int number) {
JButton b = new JButton("Button " + number);
int pad = 20;
b.setMargin(new Insets(pad, pad, pad, pad));
return b;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ResponsiveGUI o = new ResponsiveGUI();
JFrame f = new JFrame("Responsive GUI");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Run Code Online (Sandbox Code Playgroud)