为什么Java中可以在不指定类或对象的情况下调用setLayout()?
这是 Java Sound Demo。我的印象是 Java 中的方法总是从对象或类中调用。 setLayout() 方法从何而来?
public class MidiSynth extends JPanel implements ControlContext {
// Fields omitted
public MidiSynth() {
setLayout(new BorderLayout());
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
EmptyBorder eb = new EmptyBorder(5,5,5,5);
BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
CompoundBorder cb = new CompoundBorder(eb,bb);
p.setBorder(new CompoundBorder(cb,eb));
JPanel pp = new JPanel(new BorderLayout());
pp.setBorder(new EmptyBorder(10,20,10,5));
pp.add(piano = new Piano());
p.add(pp);
p.add(controls = new Controls());
p.add(new InstrumentsTable());
add(p);
}
This is the beginning of the MidiSynth class from the Java Sound Demo. I was under the impression that methods in Java were always called from an object or a class. Where does the setLayout() method come from here?
public class MidiSynth extends JPanel implements ControlContext {
// Fields omitted
public MidiSynth() {
setLayout(new BorderLayout());
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
EmptyBorder eb = new EmptyBorder(5,5,5,5);
BevelBorder bb = new BevelBorder(BevelBorder.LOWERED);
CompoundBorder cb = new CompoundBorder(eb,bb);
p.setBorder(new CompoundBorder(cb,eb));
JPanel pp = new JPanel(new BorderLayout());
pp.setBorder(new EmptyBorder(10,20,10,5));
pp.add(piano = new Piano());
p.add(pp);
p.add(controls = new Controls());
p.add(new InstrumentsTable());
add(p);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MidiSynth extends JPanel
因此,
setLayout
调用实际上是在调用this.setLayout
MidiSynth extends JPanel
So the
setLayout
call is actually invokingthis.setLayout
实际上,因为您的类
MidiSynth
继承了JPanel
这意味着您可以像处理MidiSynth
类的本地方法一样处理所有 JPanel 的方法。Actually, because your class
MidiSynth
inheritsJPanel
that means you can deal with all JPanel's methods as you deal with local methods ofMidiSynth
class.此外,
setLayout()
是在 java.awt.ContainerAdditionally,
setLayout()
is defined in java.awt.Container