2014-12-06 19 views
1

我使用這個函數來創建制表符。當我想添加按鈕「?」時這將打開向導,此按鈕出現在此JTable的右側。如何編輯這個? 「1. Dp/Drho」,comp2 - 「2. Df2/Drho」,comp3 - 「3. SDSS」,comp4 - 「4.幫助」。 name1-4 - 這個標籤的名字。 enter image description hereSwing - GridBagLayout按鈕添加錯誤

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; 
} 

回答

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(); 
      } 
     }); 
    } 
} 
+0

我找到約[重疊佈局](https://docs.oracle.com/javase/7/docs/api/javax/swing/OverlayLayout.html)文檔。但我不明白它是如何工作的。如果我們想要中間的「checkBox」呢?我的意思是你如何處理物品的位置?我知道它畫的是另一個物體。我不確定我是否解釋自己。 – Frakcool 2014-12-06 16:00:56

+0

@Frakcool'如果我們想要中間的複選框怎麼辦?'同意文檔不是很好,佈局不那麼直觀。基本上你需要使用'setAlignmentX()'屬性。我認爲你需要改變兩個組件的對齊爲0.5f。我只能通過試驗和錯誤才能使它工作。 – camickr 2014-12-06 16:21:18

+0

,我需要什麼,謝謝! JCheckBox看起來不錯,但JButton在這裏看起來不太好,因爲它對於製表符來說太大了,並且會關閉下邊框。 – Denis 2014-12-06 20:38:44