当我使用 Java 的 SpringLayout 管理器时,我遇到了一个非常奇怪的问题。我正在尝试让工具栏出现在我的程序中。它在我的程序的早期工作,现在它不起作用。基本上,如果我从 JPanel 的实例化中删除布局参数,我在 JPanel 中添加的元素就会显示出来,尽管没有我的自定义。如果我在实例化中有该参数,则工具栏根本不会出现。我不知道我做了什么或做错了什么。JPanel 将进入一个中央 JFrame,我已经将它从一个 BorderLayout 更改为另一个 SpringLayout 到什么都没有,它似乎不会影响这个问题。
public class purchaserApp
{
static JFrame mainWindow; //Main window
static JFrame addView = new JFrame ("Add An Item..."); //Add item window
static JFrame aboutView = new JFrame ("About Purchaser"); //About window
static JFrame helpView = new JFrame ("Purchaser Help"); //Help window
static JPanel toolBar, contentArea, previewPane; //Panels for GUI
static JRootPane root;
static JToolBar toolBar2;
//SpringLayout mainLayout;
JTable table;
public purchaserApp()
{
makemainWindow();
makeMenu();
makeToolbar();
// makeMainContentView();
mainWindow.setVisible(true);
}
public void makeToolbar()
{
SpringLayout tbLayout = new SpringLayout();
toolBar = new JPanel(tbLayout); //this is the offending line of code, if I remove "tbLayout" the buttons show up in the GUI but obviously without the customizations I made below...
JButton toolBarButtons[];
String buttonNames[] = {"Add", "Edit", "Delete"};
//Instantiate buttons for toolbar
toolBarButtons = new JButton[3];
//Resize
Dimension d = new Dimension (40,55);
//Add/modify/whatever
for (i = 0; i < 3; i++)
{
toolBarButtons[i] = new JButton(buttonNames[i]);
toolBarButtons[i].setPreferredSize(d);
tbLayout.putConstraint(SpringLayout.NORTH, toolBarButtons[i], 5, SpringLayout.NORTH, toolBar);
}
//Adjust constraints
tbLayout.putConstraint(SpringLayout.WEST, toolBarButtons[0], 5, SpringLayout.WEST, toolBar);
tbLayout.putConstraint(SpringLayout.WEST, toolBarButtons[1], 5, SpringLayout.EAST, toolBarButtons[0]);
tbLayout.putConstraint(SpringLayout.EAST, toolBarButtons[2], -5, SpringLayout.EAST, toolBar); //due to x-axis, we must go negative to get inside the frame
for (i = 0; i < 3; i++)
toolBar.add(toolBarButtons[i]);
mainWindow.add(toolBar,BorderLayout.NORTH); //Lies! Does not add
}
我在这里包括了类和有问题的方法。任何帮助将不胜感激,因为我确信我不是第一个遇到这个问题的人。如果这是一个相对简单的修复并且我没有看到它,我也很抱歉。我对 Java GUI(和一般的 Java)还是有点陌生,所以请原谅。