Java,将布局设置为null
我一直在使用null布局,我很多人会说它不应该这样做。 有没有更好的办法?
一些代码作为示例:
import javax.swing.*; public class Main{ public static void main(String args[]){ JFrame frame = new JFrame(); JPanel panel = new JPanel(); JButton button = new JButton("Click"); //JFrame, frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setSize(500, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); //JPanel, panel panel.setLayout(null); //<<---- Is this correct? frame.add(panel); //JButton, button button.setBounds(25, 25, 100, 60); //<<---- Is this correct? panel.add(button); } }
有没有更好的办法?
布局管理器,布局管理器,布局管理器。 如果默认提供的布局管理器没有做你想要的,可以使用布局管理器的组合,也可以尝试一些免费提供的布局管理器,比如MigLayout(并根据需要与其他布局管理器结合使用)
用你的代码……
使用GridBagLayout
按钮略大,因为它考虑了按钮的实际要求(文本和字体大小),但总是会在宽度上增加100个像素,在高度上增加60个像素。
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Main { public static void main(String args[]) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); JButton button = new JButton("Click"); //JFrame, frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setSize(500, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); //JPanel, panel panel.setLayout(new GridBagLayout()); frame.add(panel); GridBagConstraints gbc = new GridBagConstraints(); gbc.ipadx = 100; gbc.ipady = 60; gbc.insets = new Insets(25, 25, 0, 0); gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.NORTHWEST; panel.add(button, gbc); } }
现在,如果我所做的只是添加button.setFont(button.getFont().deriveFont(64f));
我们最终……
你的代码在左边,我的代码在右边……
如果你认为这过于戏剧性,那么不同的操作系统会给你带来更糟糕的事情