2015-11-16 40 views
0

我想创建一个程序,可以读取文件,写入文件和搜索文件中的文本的简单用户界面。我创建了大部分组件,问题在于它们都在同一个(中心)单元中“绘制”。我尝试过应用重量,宽度等等都无济于事。摆动组件不移动到所需的单元GridBagLayout

这里的UI我的基本代码:

public void GUI(){ 

    //Create main window for Program 
    JFrame mainWindow = new JFrame("Simple Data Base");  //Init frame 
    mainWindow.setSize(500, 400);  //Set frame size 
    mainWindow.setVisible(true);  //Make frame visible 

    //Create panel for the main window of the GUI 
    JPanel simpleGUI = new JPanel(new GridBagLayout()); 
    GridBagConstraints gbCons = new GridBagConstraints(); 
    simpleGUI.setBackground(Color.cyan); 

    //Create button linking to read function 
    JButton readButton = new JButton("Read");  //Init button, and give text 
    gbCons.fill = GridBagConstraints.BOTH; 
    gbCons.gridx = 0; 
    gbCons.gridy = 1; 

    //Create button linking to the search function 
    JButton searchButton = new JButton("Search"); 
    gbCons.fill = GridBagConstraints.BOTH; 
    gbCons.gridx = 1; 
    gbCons.gridy = 1; 

    //Create label prompting user to specify desired function 
    JLabel promptText = new JLabel("Click 'Read' to read a file, 'Search' to search within a file, 'Write' to write to a file:"); 
    gbCons.fill = GridBagConstraints.BOTH; 
    gbCons.gridx = 0; 
    gbCons.gridy = 0; 

    //Add components to Main window 
    mainWindow.getContentPane().add(simpleGUI); 
    simpleGUI.add(promptText, gbCons); 
    simpleGUI.add(readButton, gbCons); 
    simpleGUI.add(searchButton, gbCons); 
} 

回答

4

的问题是,他们都被以相同的(中心)细胞“绘制”。

simpleGUI.add(promptText, gbCons); 
simpleGUI.add(readButton, gbCons); 
simpleGUI.add(searchButton, gbCons); 

您正在使用相同的GridBagConstraints每个组件所以约束上是为每个组件是相同的。

您neeed到:

  1. 设置的约束
  2. 使用约束
  3. 重复步骤1和2。

例如,该组件添加到面板:

JButton readButton = new JButton("Read"); 
gbCons.fill = GridBagConstraints.BOTH; 
gbCons.gridx = 0; 
gbCons.gridy = 1; 
simpleGUI.add(readButton, gbCons); 

JButton searchButton = new JButton("Search"); 
gbCons.fill = GridBagConstraints.BOTH; 
gbCons.gridx = 1; 
gbCons.gridy = 1; 
simpleGUI.add(searchButton, gbCons); 

我建议y请阅读How to Use GridBagLayout的Swing教程中的部分以获取更多信息和示例。

下载演示代码并将该示例用作启动代码。演示代码将告诉你如何更好地组织你的类:

  1. 不延长JFrame的
  2. 创建在事件指派线程
  3. 使用pack()方法,而不是的setSize(图形用户界面.. 。)方法
  4. 使框架可见毕竟组件已被添加到帧
+0

感谢,移动个人“添加”声明,其相应的组件 - 而不是将它们组合一起 - 工作。为什么我在Swing Doc中找不到任何有关它的东西? –

+0

斯科特斯坦奇菲尔德的另一个非常好的LayoutManager教程可以在这里找到(http://javadude.com/articles/layouts/)。他对GridBagLayout的解释是我在1998年阅读过的第一本对我有意义的文章。 –