[英]Swing components not moving to desired cell in GridBagLayout
我正在尝试为程序创建一个简单的UI,该程序可以读取文件,写入文件以及在文件中搜索文本。 我已经创建了大多数组件,问题是它们都被“绘制”在同一(中心)单元中。 我尝试将重量,宽度等全部应用都无济于事。
这是我的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);
}
问题在于它们都被“绘制”在同一个(中心)单元格中。
simpleGUI.add(promptText, gbCons);
simpleGUI.add(readButton, gbCons);
simpleGUI.add(searchButton, gbCons);
每个组件都使用相同的GridBagConstraints,因此每个组件的约束都相同。
您需要:
例如:
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);
我建议您阅读Swing教程中有关如何使用GridBagLayout的部分, 以获取更多信息和示例。
下载演示代码并将该示例用作您的起始代码。 演示代码将向您展示如何通过以下方法更好地构建类结构:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.