5

我正在尝试创建一个前面带有 GroupLayout 的小型 Jpanel。在尽可能多地遵循文档并查看了一些 StackOverflow 问题之后,我仍然陷入困境。

错误如下:

线程“AWT-EventQueue-0”中的异常 java.lang.IllegalStateException: javax.swing.JButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5,border=com.apple.laf.AquaButtonBorder$Dynamic @5eef2e7c,flags=288,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=0,left=2,bottom=0,right=2 ],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Invest,defaultCapable=true] 未附加到垂直组

我知道问题与按钮的连接位置有关。毕竟错误明确地说明了这一点。但是,我只是无法弄清楚我应该以什么方式附加它们。有任何想法吗?

    JPanel panel = new JPanel();

    GroupLayout layout = new GroupLayout(panel);
    panel.setLayout(layout);


    panel.setMinimumSize(new Dimension(2000,100));      
    panel.setBorder(BorderFactory.createTitledBorder((cdo.getTicker()) + " : (" + cdo.getCurrency() + ")"));


    layout.setVerticalGroup(
            layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(new JButton("Invest")))                       
                    .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                            .addComponent(new JButton("Ignore")))
                            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(new JButton("Article")))

            );


    layout.setHorizontalGroup(
            layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(new JButton("Invest"))
                    .addComponent(new JButton("Ignore"))
                    .addComponent(new JButton("Article"))
                    )
            );
4

1 回答 1

8

new JButton("Invest")创建一个新按钮,该按钮与之前使用 new 创建的按钮不同JButton("Invest")

在布局之前移动按钮的初始化:

JButton investButton = new JButton("Invest");
JButton articleButton = new JButton("Article");
JButton ignoreButton = new JButton("Ignore");

layout.setVerticalGroup(
    layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
            .addComponent(investButton))                       
        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
            .addComponent(ignoreButton))
        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
            .addComponent(articleButton)));

layout.setHorizontalGroup(
    layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(investButton)
            .addComponent(ignoreButton)
            .addComponent(articleButton)));
于 2013-08-10T08:16:59.367 回答