2014-07-23 26 views
-1

我有空佈局的問題。 PROGRAMM有這樣的結構:零布局的元素放置

窗口(JFrame的)
        - 卡式窗格(JTabbedPane中)
            - ..某些選項卡..
            - 包裝在JScrollPane中的重載JPanel(類表)

另外我有一個覆蓋JLabel(類看板)。

我嘗試在表中添加看板的一些實例並且什麼也沒有。如果我將Table的佈局從null更改爲BorderLayout(例如),則會顯示元素並且工作良好。 Oracle文檔中提到了3個步驟:1)設置空佈局,2)在子元素上調用setBounds(),3)在具有空佈局的元素上調用repaint()。這對我來說並不合適(非常非常好,真的)。

表放置代碼(窗口的構造函數):

Table table = new Table(); 
JScrollPane panel = new JScrollPane(table); 

tabbedPanel.addTab("New tab", panel); 
tabbedPanel.setSelectedIndex(tabbedPanel.getTabCount() - 1); 

table.setPreferredSize(new Dimension(600, 400)); 
table.setSize(600, 400); 

表的構造:

setDoubleBuffered(true); 
setLayout(null); 
setBounds(0,0,600,400); 

Kanban kanban = new Kanban("Label text"); 
kanban.setBounds(10, 10, kanban.getWidth(), kanban.getHeight()); 

add(kanban); 

有什麼不對?爲什麼元素不能繪製空佈局?

--- Add 我需要一個空佈局,因爲我需要標籤的點位置。

+5

*我有一個空的問題佈局。*毫無疑問。 – Braj

+1

如果(*我有一個空佈局問題。*),那麼不要使用空佈局 –

回答

2

kanban.getWidth(), kanban.getHeight()他們是0.但我同意上面的所有意見。不要使用空白布局。定義一個面板GridLayout並將您的所有標籤放在那裏

+0

你有固定的大小,它在Kanben構造函數中定義。 – Ivan

0

NUllLayout是最有效的佈局管理器,因爲它具有自由度,您可以明確指定元素的放置位置。但要真正有效地使用它,您需要以像素爲單位在您的Frame上繪製位置。在你的編碼中應用一些幾何考慮下面的代碼。

package com.samuTech.DialogBoxes; 

import javax.swing.JFrame; 
import javax.swing.JTextField; 
import javax.swing.JPasswordField; 
import javax.swing.JButton; 
import java.awt.Color; 
import java.awt.Font; 
import java.awt.Graphics; 
import javax.swing.JLabel; 

public class NullLayout2 extends JFrame { 

private static JLabel nameLabel; 
private static JLabel passwordLabel; 
private static JTextField userName; 
private static JPasswordField pass; 
private static JButton ok; 

public NullLayout2(){ 

    super("Null Layout"); 

    setSize(getMaximumSize().width,getMaximumSize().height); 
    setLocation(getLocation().x,getLocation().y); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setVisible(true); 
    getContentPane().setBackground(Color.BLUE); 
    setLayout(null); 

    nameLabel = new JLabel("User Name"); 
    passwordLabel = new JLabel("Password"); 
    userName = new JTextField(20); 
    pass = new JPasswordField(20); 
    ok = new JButton("Ok"); 

    userName.setBounds(200,100,200,30); 
    pass.setBounds(200,150,200,30); 
    ok.setBounds(300,200,100,30); 
    nameLabel.setBounds(5,100,150,30); 
    passwordLabel.setBounds(5,150,150,30); 

    add(userName); 
    add(passwordLabel); 
    add(nameLabel); 
    add(pass); 
    add(ok); 

} 

public void pain(Graphics g){ 

    g.drawString("Graphitii trials ", 55, 400); 
} 
public static void main(String[]args){ 
    javax.swing.SwingUtilities.invokeLater(

      new Runnable(){ 

       @Override 
       public void run(){ 
        new NullLayout2(); 
       } 
      } 

    ); 
} 

}

而不是放棄一個工具,你顯然會在軟件開發生命特殊的GUI設計需要,請在官方文件中查閱了空佈局here