Swing - GridBagLayout按钮添加错误

时间:2014-12-06 15:01:37

标签: java swing grid-layout gridbaglayout jtabbedpane

我使用此功能创建标签。当我想添加按钮“?”这将打开向导,此按钮出现在此JTable的右侧。如何编辑?

comp1 - “1. Dp / Drho”,comp2 - “2. Df2 / Drho”,comp3 - “3. SDSS”,comp4 - “4。帮助”。 name1-4 - 此选项卡的名称。enter image description here

static protected JPanel allocateUniPane(Component comp1,Component comp2,Component comp3, Component comp4,
                                        String name1, String name2, String name3, String name4){
    JPanel resultPane = new JPanel();
    GridBagLayout gridbagforUnionPane = new GridBagLayout();
    GridBagConstraints cUnionPane = new GridBagConstraints();
    resultPane.setLayout(gridbagforUnionPane);

    cUnionPane.fill = GridBagConstraints.BOTH;
    cUnionPane.anchor = GridBagConstraints.CENTER;
    JButton showWizard = new JButton("?");
    cUnionPane.weightx = 0.5;
    cUnionPane.weighty = 0.5;
    JTabbedPane jtp = new JTabbedPane();
    jtp.addTab(name1, comp1);
    jtp.addTab(name2, comp2);
    jtp.addTab(name3, comp3);
    jtp.addTab(name4, comp4);
    cUnionPane.gridx = 0;
    cUnionPane.gridy = 0;
    resultPane.add(jtp,cUnionPane);
    cUnionPane.fill = GridBagConstraints.NORTH;
    cUnionPane.weightx = 0.5;
    cUnionPane.gridx = 1;
    cUnionPane.gridy = 0;
    resultPane.add(showWizard,cUnionPane);

    return resultPane;
}

1 个答案:

答案 0 :(得分:3)

您希望该按钮显示为选项卡式窗格的一部分。您不能使用GridBagLayout(或大多数其他布局),因为它们在面板上布局两个维度的组件。

也许OverlayLayout会做你想要的,因为它在第三维中定位组件。例如:

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;

public class TabbedPaneWithComponent
{
    private static void createAndShowUI()
    {
        JPanel panel = new JPanel();
        panel.setLayout( new OverlayLayout(panel) );

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.add("1", new JTextField("one"));
        tabbedPane.add("2", new JTextField("two"));
        tabbedPane.setAlignmentX(1.0f);
        tabbedPane.setAlignmentY(0.0f);

        JCheckBox checkBox = new JCheckBox("Check Me");
        checkBox.setOpaque( false );
        checkBox.setAlignmentX(1.0f);
        checkBox.setAlignmentY(0.0f);

        panel.add( checkBox );
        panel.add(tabbedPane);

        JFrame frame = new JFrame("TabbedPane With Component");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( panel );
        frame.setLocationByPlatform( true );
        frame.setSize(400, 100);
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}