简体   繁体   English

在Java Swing中预装组件?

[英]Prepend components in Java Swing?

The .add method appends components to the end of another component. .add方法将组件附加到另一个组件的末尾。 I'm trying to prepend a component to the beginning of another component. 我正在尝试将组件添加到另一个组件的开头。 How would I accomplish that? 我怎么做到这一点?

I think you could use the add(Component, int) method, where the int specifies the insertion position. 我认为你可以使用add(Component,int)方法,其中int指定插入位置。 An insertion position of zero should do the trick to prepend a component. 插入位置为零应该可以预先设置组件。


(I don't know if this is the right approach though. Maybe a layout manager would be better.) (我不知道这是否是正确的方法。也许布局管理器会更好。)

Component has an add method that takes two params - the object to be added and the index for it to be inserted at. Component有一个add方法,它接受两个参数 - 要添加的对象和要插入的索引。 With that in mind, you can attempt to prepend you component by doing the following: 考虑到这一点,您可以通过执行以下操作尝试在组件前添加:

 comp.add(newPanel, 0);
 comp.validate();

You should use a layout manager to accomplish that. 您应该使用布局管理器来实现这一目标。 The standard layout manager, which is the one with which every container starts by default, just adds items at the end. 标准布局管理器是默认情况下每个容器启动的布局管理器,只是在最后添加项目。

Something like this, for example, would do the trick: 例如,像这样的东西可以解决这个问题:

JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(lowComponent,BorderLayout.CENTER);
panel.add(highComponent,BorderLayout.NORTH);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM