2011-11-04 70 views
3

我有標籤和JButton我想要在JFrame中定義位置。如何在JFrame中設置對象的位置?

import java.awt.*; 
import java.net.InetAddress; 
import java.net.UnknownHostException; 
import javax.swing.*; 

public class GuiFrame extends JFrame { 

    public static void main(String[] args) throws UnknownHostException { 

     JFrame f = new JFrame("This is a test"); 
     f.setSize(400, 150); 
     JRadioButton ButtonServer = new JRadioButton("Server"); 
     JRadioButton ButtonClient = new JRadioButton("Client"); 

     InetAddress thisIp = InetAddress.getLocalHost(); 

     Label lip = new Label("Your IP is : " + thisIp.getHostAddress()); 
     Label setup = new Label("Setup as "); 
     JButton ButtonOk = new JButton("OK"); 

     Container content = f.getContentPane(); 
     content.setBackground(Color.white); 
     content.setLayout(new FlowLayout()); 
     content.add(lip); 
     content.add(setup); 
     content.add(ButtonServer); 
     content.add(ButtonClient); 
     content.add(ButtonOk); 
     // f.addWindowListener(new ExitListener()); 
     f.setVisible(true); 
    } 
} 

setLocation()在這裏似乎不起作用。如何在JFrame中管理對象的位置?

+4

請參見[課程:放置容器內的組件](http://download.oracle.com/javase/tutorial/uiswing/layout/index.html)。 – trashgod

回答

4

使用合適的LayoutManager。例如。 GridBagLayout的。

或者您可以將多個嵌套面板組合爲每個面板分配自己的LayoutManager。

最可怕的方式就是設置佈局爲空和使用的setBounds()

+0

同意,setLayout null是一個不好的方法來做到這一點! – Handsken

+0

我已經看到了一些LayoutManager,但是沒有一個LayoutManager似乎具有在JFrame中設置位置(x,y)的功能。有沒有? – nebula

3

FlowLayout給你一些選項。看看here

對於實例

FlowLayout layout = new FlowLayout(); 
    layout.setAlignment(FlowLayout.CENTER); 
    c.setLayout(layout); 
    c.add(panel); 
0

使用NetBeans GUI Builder中。但它確實有缺點。比如你不能刪除自動創建的ActionListeners。