0

当我使用 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)还是有点陌生​​,所以请原谅。

4

2 回答 2

0

正如在这个相关问题中所指出的,约束规范的顺序可能很重要,尤其是在结果布局过度约束的情况下。根据版本,您可能必须在EAST/SOUTH约束之前指定约束,如此WEST/NORTH所述。

于 2011-04-06T05:21:28.340 回答
0

为什么要尝试使用面板创建工具栏?使用自己的自定义布局的 JToolBar 有什么问题?

即使您确实创建了自定义工具栏面板,我也不会使用 SpringLayout,它太复杂了。只需使用 FlowLayout 或水平 BoxLayout。

阅读关于布局管理器的 Swing 教程,了解每个布局管理器的工作示例。

于 2011-04-06T04:57:08.223 回答