[英]How to add a menu bar for loading/saving files in a class that extends JPanel?
考慮以下代碼:
/**
* Main class
* @author X2
*
*/
class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener ,KeyListener
{
/**
* private variables
*/
// dimensions of the window
private static final long serialVersionUID = 1L;
private static final Dimension MIN_DIM = new Dimension(300, 300);
private static final Dimension PREF_DIM = new Dimension(500, 500);
/**
* Setting the dimensions of the window
*/
public Dimension getMinimumSize() { return MIN_DIM; }
public Dimension getPreferredSize() { return PREF_DIM; }
/**
* The constructor
*/
DrawingPanel()
{
super();
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
setFocusable(true);
requestFocusInWindow();
}
public void paintComponent(Graphics g)
{
// code
}
public void mouseClicked(MouseEvent evt)
{ // code
}
// more code
如何在我的窗口中添加一個面板,需要在其中打開和保存文件的選項。
此刻窗口看起來像這樣:
謝謝
這取決於。
您可以使用BorderLayout
,將JMenuBar
放置在NORTH
位置
然后問題歸結為如何布局任何子組件? 您需要一種內容窗格,這將允許在CENTRE
位置為容器設置不同的布局管理器
另外,您也可以使用SwingUtilities.getAncestorOfClass
找到的第一個實例JFrame
在父組件層次或SwingUtilities.getWindowAncestor
如果你不介意鑄造的結果。
更新
這只是發生在我身上,如果您要使用getAncestorOfClass
,那么最好去尋找JRootPane
的實例,該實例具有setJMenuBar
。 JRootPane
負責布局菜單欄和內容窗格(以及其他一些事情)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.