首页 > 解决方案 > Java swing:如果我不调用 setLayout 方法,setBounds 方法不起作用?

问题描述

我是编程新手,但我对 OOP 有点了解,我想了解更多。

在学习 Java swing 时,我意识到如果不调用 setLayout 方法, setBounds 方法将无法工作。这是为什么?

import javax.swing.*;  
public class FirstSwingExample {  

public static void main(String[] args) {  
    JFrame f=new JFrame();//creating instance of JFrame  
          
    JButton b=new JButton("click");//creating instance of JButton  
    b.setBounds(130,100,100, 40);//x axis, y axis, width, height  
          
    f.add(b);//adding button in JFrame  
          
    f.setSize(400,500);//400 width and 500 height  
   // f.setLayout(null);//using no layout managers-> setBounds won't work without calling setLayout
    f.setVisible(true);//making the frame visible  
}  
}  

现在是另一个问题,如果我在另一个程序中使用相同的概念,比如将 Animal 继承作为超类。

如果我有一个带有 run 方法的 Cat 类...如何创建依赖于 Animal 类的 eat 方法的 run 方法?

我的意思是,你怎么能在 Cat 类中调用一个只有在你也调用eat 方法时才会起作用的 run 方法?

 Animal class -> superclass (method: eat())
     |    
     Feline class -> subclass of Animal
         |
         Cat class -> subclass of Feline (method: run())

标签: javaswingoop

解决方案


推荐阅读