我正在尝试为一个程序创建一个简单的 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);
}
最佳答案
the problem is that they're all being "drawn" in the same (center) cell.
simpleGUI.add(promptText, gbCons);
simpleGUI.add(readButton, gbCons);
simpleGUI.add(searchButton, gbCons);
您对每个组件使用相同的 GridBagConstraints,因此每个组件的约束都是相同的。
您需要:
- 设置约束
- 使用约束将组件添加到面板
- 重复步骤 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);
我建议您阅读 Swing 教程中关于 How to Use GridBagLayout 的部分。了解更多信息和示例。
下载演示代码并使用该示例作为您的起始代码。演示代码将向您展示如何通过以下方式更好地构建您的类:
- 不扩展 JFrame
- 在事件分派(dispatch)线程上创建 GUI
- 使用 pack() 方法,而不是 setSize(...) 方法
- 在将所有组件添加到框架后使框架可见
关于java - Swing 组件未移动到 GridBagLayout 中所需的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33743103/