我尝试将按钮定位在框架到中心,或者,如果说实话,使我的布局更灵活。但是当我像 .setBounds
一样设置属性时,我的按钮没有反应。为什么?感谢任何帮助!
import com.sun.beans.editors.ColorEditor;
import javax.swing.*;
import java.awt.*;
public class windowsInterface extends JFrame{
windowsInterface(){
super("When the nearest HB");
setSize(800, 800);
JPanel panelForAddDel = new JPanel();
panelForAddDel.setSize(800, 100);
panelForAddDel.setLocation(0, 0);
panelForAddDel.setBackground(Color.gray);
JTextField nameOfStaff = new JTextField();
JTextField dateOfBirth = new JTextField();
JButton addRec = new JButton("Добавить");
addRec.setBounds(100, 100, 200, 50);
JButton delRec = new JButton("Удалить");
delRec.setBounds(100, 100, 200, 50);
addRec.setBounds(320, 125, 200, 50);
delRec.setBounds(420, 125, 200, 50);
JPanel panelForWatch = new JPanel();
panelForWatch.setLocation(0, 100);
panelForWatch.setSize(800, 600);
panelForWatch.setBackground(Color.BLUE);
add(panelForAddDel);
add(panelForWatch);
panelForAddDel.add(nameOfStaff);
panelForAddDel.add(dateOfBirth);
panelForAddDel.add(addRec);
panelForAddDel.add(delRec);
}
}
但是当我设置像 .setBounds 这样的属性时,我的按钮没有任何反应。为什么?
因为 Java 组件中有一个默认布局。例如,JFrame 使用默认的 BorderLayout 管理器,它确定您在 JFrame 中添加的组件将如何定位和否决您的setBounds()
方法,从而给您一种它不起作用的印象。
您将意识到,如果通过将它设置为 null this.setLayout(null)
来删除此布局,setBounds()
似乎会再次起作用。
但是,建议您根据需要选择合适的布局,而不是使用 null 布局。
-
我建议您将组件添加到 JPanel 并将 JPanel 添加到 JFrame 中,而不是直接添加到 JFrame 中。
-
为您的 JPanel 设置适当的布局
-
如果需要,您可以使用嵌套的 JPanels 每个都有不同的布局以满足您的需求。
这可能是因为面板的默认布局是流布局。阅读有关它的信息 http://www.javatpoint.com/FlowLayout。更灵活的布局是GridBagLayout,您可以根据自己的选择更改面板或JFrames的布局。要了解 GridBagLayout: https://www.tutorialspoint.com/swing/swing_gridbaglayout.htm