2012-06-09 66 views

回答

9

這裏找到Absolute Positioning Tutorials。請你仔細閱讀,至於爲什麼採用這種方法,在使用LayoutManagers

要添加說一個JButton您的JPanel,您可以使用此:

JButton button = new JButton("Click Me"); 
button.setBounds(5, 5, 50, 30); 
panel.add(button); 

這裏嘗試這個例子程序:

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

public class AbsoluteLayoutExample 
{ 
    private void displayGUI() 
    { 
     JFrame frame = new JFrame("Absolute Layout Example"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     JPanel contentPane = new JPanel(); 
     contentPane.setOpaque(true); 
     contentPane.setBackground(Color.WHITE); 
     contentPane.setLayout(null); 

     JLabel label = new JLabel(
      "This JPanel uses Absolute Positioning" 
            , JLabel.CENTER); 
     label.setSize(300, 30); 
     label.setLocation(5, 5); 

     JButton button = new JButton("USELESS"); 
     button.setSize(100, 30); 
     button.setLocation(95, 45); 

     contentPane.add(label); 
     contentPane.add(button); 

     frame.setContentPane(contentPane); 
     frame.setSize(310, 125); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new AbsoluteLayoutExample().displayGUI(); 
      } 
     }); 
    } 
} 

Absolute Positioning Output

+0

什麼是「窗格」?我可以使用JPanel嗎? – whiteberryapps

+0

它不起作用... – whiteberryapps

+0

@ user1441845:請看這個最新的編輯,你如何使用它'JPanel' :-)我以前忘了告訴你,你必須寫'panel.setLayout(null) ',雖然我已經提到在這個代碼示例現在:-)爲AbsoluteLayout的 –

2

看看這個絕對佈局代碼示例:

Absolute Layout demo

+0

+1,我看過這個教程的其他地方,只是不能記住在哪裏:-) –

2

在類繼承的幀:

setLayout(null); 

在您的組件:

setLocation(x,y); 
+0

不起作用... – whiteberryapps

+0

+1,很好的提示:-) –

+0

關注:1 )您需要設置JFrame的contentPane的佈局,而不是JFrame本身。 2)如果容器的佈局爲空,則編碼器完全負責所添加的組件的位置*和*大小。 3)你應該添加一個關於避免使用空佈局和絕對定位的警告。 –

3

嘗試這些2 ...在彼此組合...

setLocation() and setBounds()

它更好地使用由NetBeans團隊在2005年開發的GroupLayout。WindowsBuilder Pro是一個很好的工具,用於在java中構建Gui

+0

+1,希望我能掌握GroupLayout,無疑是 –

+1

附近的最佳版式管理器之一@nIcEcOw:在NetBeans GUI編輯器中修改並檢查生成的代碼是一個以'GroupLayout'實驗的方式。 – trashgod

+0

@trashgod:有意思的想法,在IDE上拖/放,用通常的方式進行試驗和玩代碼。這是一個很棒的建議,謝謝:-) –

相關問題