如何在JFrame中设置对象的位置?
我有标签和JButtons我想在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中管理对象的位置?
使用适当的LayoutManager。 例如GridBagLayout。
或者,您可以组合多个嵌套面板,为每个面板分配自己的LayoutManager。
最糟糕的方法是将layout设置为null并使用setBounds()
FlowLayout
为您提供了一些选择。 看这里
例如
FlowLayout layout = new FlowLayout(); layout.setAlignment(FlowLayout.CENTER); c.setLayout(layout); c.add(panel);
我总是使用这个: http : //download.oracle.com/javase/tutorial/uiswing/layout/using.html
🙂
Netbeans GUI Builder非常棒。 我建议你调查一下。
使用Netbeans GUI Builder。 它确实有缺点。 如您无法删除自动创建的ActionListeners。