java - 自定义 JPanel 未添加到 JFrame
问题描述
我正在创建一个使用自定义 JPanel 的 GUI,该 JPanel 在 JPanel 上连续显示三次,然后将其添加到 JFrame。出于某种原因,自定义 JPanel 在添加到JFrame时不会显示。
我设法让 JPanel 显示的唯一方法是将以下行添加到自定义 JPanel 类的底部:
this.add(myPanel); // myPanel 是 JPanel 实例
我确定这不是正确的方法
带主方法的类驱动程序
public class Driver {
public static void createAndShowGUI() {
JFrame frame = new JFrame("Test");
JPanel mainPanel = new JPanel(new GridLayout(1, 3));
MyPanel firstPanel = new MyPanel();
MyPanel secondPanel = new MyPanel();
MyPanel thirdPanel = new MyPanel();
mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
mainPanel.add(thirdPanel);
frame.getContentPane().add(mainPanel);
// show the window.
frame.setSize(MyPanel.WIDTH, MyPanel.HEIGHT);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} // createAndShowGUI
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
} // run
}); // Runnable
} // main
} // Driver
自定义 JPanel 类
@SuppressWarnings("serial")
public class MyPanel extends JPanel {
public MyPanel() {
JPanel myPanel = new JPanel();
// inner panel
JPanel innerPanel = new JPanel();
innerPanel.setBorder(BorderFactory.createEtchedBorder());
innerPanel.setBackground(Color.red);
innerPanel.setPreferredSize(new Dimension(WIDTH / 3, HEIGHT - 100));
myPanel.add(innerPanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.MAGENTA);
myPanel.add(buttonPanel);
} // constructor
} // class
有些行已被编辑掉
解决方案
这个类是错误的:
public MyPanel() {
JPanel myPanel = new JPanel();
myPanel.setBorder(BorderFactory.createEtchedBorder());
myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));
// inner panel
JPanel innerPanel = new JPanel();
innerPanel.setBorder(BorderFactory.createEtchedBorder());
innerPanel.setBackground(Color.red);
innerPanel.setPreferredSize(new Dimension(WIDTH / 3, HEIGHT - 100));
myPanel.add(innerPanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.MAGENTA);
myPanel.add(buttonPanel);
} // constructor
} // class
我猜它扩展了 JPanel,这意味着在创建此类时会创建两个 JPanel,一个 myPanel 变量将组件添加到其中,但从未添加到 GUI 中,而 MyPanel 实例没有添加任何内容到它,并且它确实被添加到 GUI 中。
建议:不要让此类扩展 JPanel,而是将 myPanel 局部变量设为实例字段。为类提供getMyPanel()
返回此字段的方法并将其添加到 GUI。
选项 2:摆脱myPanel
局部变量,而是将所有内容添加到this
.
推荐阅读
- reactjs - 使用类制作组件并在返回后使用标签html时是否有错误
- c# - 将具有多个数据表的数据集导出到 Excel 中的单个工作表
- c++ - 一个应用程序中两个不同版本的库
- ios - 重构的用户获取功能不会将信息加载到集合视图单元格
- mysql - 如何在mysql中使用for循环,因为我想从输入中搜索给定经理的层次结构中的员工。?
- python - 通过click()找到超链接后如何使用find_element
- reactjs - How to prevent arrow key selecting behavior in Material UI auto suggest?
- types - Coq:创建 boolean 和 nat 的超类型
- algorithm - 为什么这里使用 temp 而不是 vtx(在第 3 行)?
- python - get_object_or_404 上的循环在条件失败后停止