繁体   English   中英

对SpringLayout有帮助吗?

[英]Help with SpringLayout?

使用Java的SpringLayout管理器时,我遇到一个非常奇怪的问题。 我想让工具栏出现在我的程序中。 它在我的程序的较早版本上可以正常工作,但现在不起作用。 基本上,如果我从JPanel的实例中删除layout参数,则即使没有自定义,我在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)还是陌生的,所以请原谅。

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

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

阅读有关布局管理器的Swing教程,以获取每个布局管理器的工作示例。

如该相关问题中所述,约束条件指定的顺序可能很重要,尤其是在结果布局过于受限的情况下 根据版本的不同,您可能需要指定EAST/SOUTH的约束之前WEST/NORTH的约束,如所描述这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM