Java 与BorderLayout对象的使用有关的一些疑问
我正在学习Java Swing,我对BorderLayout对象的使用有疑问 我有一个创建工具栏的简单示例程序:Java 与BorderLayout对象的使用有关的一些疑问,java,swing,border-layout,Java,Swing,Border Layout,我正在学习Java Swing,我对BorderLayout对象的使用有疑问 我有一个创建工具栏的简单示例程序: package com.andrea.menu; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; impor
package com.andrea.menu;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class ToolBar extends JFrame {
public ToolBar() {
initUI();
}
public final void initUI() {
JMenuBar menubar = new JMenuBar(); // The menu bar containing the main menu voices
JMenu file = new JMenu("File"); // Creo un menu a tendina con etichetta "File" e lo aggiungo
menubar.add(file);
setJMenuBar(menubar); // Sets the menubar for this frame.
JToolBar toolbar = new JToolBar();
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
JButton exitButton = new JButton(icon);
toolbar.add(exitButton);
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
add(toolbar, BorderLayout.NORTH);
setTitle("Simple toolbar");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ToolBar ex = new ToolBar();
ex.setVisible(true);
}
});
}
}
因此,它通过以下行创建一个JToolBar对象:
JToolBar toolbar = new JToolBar();
add(toolbar, BorderLayout.NORTH);
然后将其放置在BorderLayout对象的NORTH位置,按以下直线:
JToolBar toolbar = new JToolBar();
add(toolbar, BorderLayout.NORTH);
阅读文档后,我知道:
边框布局布局容器,排列并调整其大小
组件以适合五个区域:北、南、东、西和
居中
我的疑问是:BorderLayout
对象指的是谁?在外部JFrame容器上
这意味着它将工具栏对象放在我的JFrame的北位置?或者什么?您将工具栏放在名为
ex
的工具栏的北位置
您的工具栏
类扩展了JFrame
。add
方法由ToolBar
从JFrame
继承。在main
中调用ToolBar
构造函数,该构造函数创建ToolBar
的新实例,并保存对ex
的引用。它还调用ex
上的initUI
方法,在ex
上调用add
你的工具栏是一个JFrame
mmm是的,我的意思是:我的工具栏是一个JFrame(因为它扩展了JFrame),所以工具栏对象是一个容器,我把JToolBar工具栏对象放在这个容器的北部,是吗?@AndreaNobili是的!它们不是直接添加到jframe中,而是从java 5开始添加到contentPane中。我想我不确定javax.swing.jframe
:“作为一种惯例add
及其变体,remove
和setLayout
已经被覆盖,以便在必要时转发到contentPane。”请检查此项。很好地澄清了我的一些疑问。