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);
}
感谢,移动个人“添加”声明,其相应的组件 - 而不是将它们组合一起 - 工作。为什么我在Swing Doc中找不到任何有关它的东西? –
斯科特斯坦奇菲尔德的另一个非常好的LayoutManager教程可以在这里找到(http://javadude.com/articles/layouts/)。他对GridBagLayout的解释是我在1998年阅读过的第一本对我有意义的文章。 –