2014-10-22 43 views
1

我正在为我的高中班级编写一个小型项目,但现在我遇到了一些问题,现在我正在使用框架。我试图找到在java中安排一个面板的内容最简单,最有效的方式7 (注:这意味着SpringUtilities不是一个选项)在面板中排列项目

因为我想它的每个项目的安排有你的名字在顶部的同一行下方的名称框

和我到目前为止的代码输入,然后有3个按钮的选项

private static void userInterface(){ 
     //Declare and assign variables 
     final String[] options = {"Lvl 1", "Lvl 2", "Lvl 3"}; 
     int optionsAmt = options.length; 
     //Create the panel used to make the user interface 
     JPanel panel = new JPanel(new SpringLayout()); 

     //Create the name box 
     JTextField tf = new JTextField(10); 
     JLabel l = new JLabel("Name: "); 
     l.setLabelFor(tf); 
     panel.add(l); 
     panel.add(tf); 

     //Create 3 buttons with corresponding values of String options 
     for(int a = 0; a < optionsAmt; a++){ 
      JButton b = new JButton(options[a]); 
      panel.add(new JLabel()); 
      panel.add(b); 
     } 

     //Layout the panel 


    } 

    public static void main(String[] args) { 

     JFrame f = new JFrame(); 
     f.pack(); 
     f.setTitle("Number Game"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setVisible(true); 


    } 
} 

回答

4

“易”是相对的例如,你可以做类似......

GridLayout

public class TestPane extends JPanel { 

    public TestPane() { 
     setLayout(new GridLayout(2, 1)); 

     JPanel fieldPane = new JPanel(); 
     fieldPane.add(new JTextField(10)); 
     add(fieldPane); 

     JPanel buttonPane = new JPanel(); 
     buttonPane.add(new JButton("1")); 
     buttonPane.add(new JButton("2")); 
     buttonPane.add(new JButton("3")); 
     add(buttonPane); 

    } 

} 

或类似的东西...

GridBagLayout

public class TestPane extends JPanel { 

    public TestPane() { 
     setLayout(new GridBagLayout()); 
     GridBagConstraints gbc = new GridBagConstraints(); 
     gbc.gridwidth = 3; 
     gbc.gridx = 0; 
     gbc.gridy = 0; 

     add(new JTextField(10), gbc); 

     gbc.gridwidth = 1; 
     gbc.gridy = 1; 

     add(new JButton("1"), gbc); 
     gbc.gridx++; 
     add(new JButton("2"), gbc); 
     gbc.gridx++; 
     add(new JButton("3"), gbc); 

    } 

} 

两者都是容易的,都做的工作,但你会用会在你很大程度上取决于想实现...

看看Laying Out Components Within a Container了解更多详情

+0

很好的一个 – 2014-10-22 03:14:04

+0

谢谢你的帮助 – 2014-10-24 02:13:14

+0

很高兴帮助... – MadProgrammer 2014-10-24 02:14:45