我有一个使用 GridLayout 管理器的简单 gui 容器。我添加了两个从 JComponent 继承的组件,并使用 paintComponent 在屏幕上绘制了一些东西。
现在我添加了 componentListener 以使用 GridLayout 管理器调整 gui 的大小。调整大小后,这两个组件仍然很小,所以没有调整大小。
我通过创建一个简单的 GridLayout 副本来检查这一点,打印 methode layoutContainer 从父容器获取的大小,以查看父容器是否具有新大小(在调整大小事件之后)。它打印的尺寸仍然很小,变化很小,但不是正确的。
我在 layoutContainer 中打印大小,并使用简单的计时器每秒打印父 gui 的大小。
我意识到在 Timer 打印正确的尺寸 (1600x1099) 之前,我的 GridLayout 管理器中的 layoutContainer 会以旧尺寸调用。
我认为 GridLayout 总是根据行和列配置自动调整其所有组件的大小。但似乎没有,layoutContainer 方法被调用得太早了。
有什么方法可以使用 GridLayout 管理器来解决这个问题,还是我必须自己调整组件的大小?
如何检查 LayoutManager 中调用 layoutContainer 方法的时间和内容?
这是一个正确调整大小的模块的代码,但其子类的子组件未正确调整大小(希望它对您来说代码不多):
信息:我在一个 java 文件中为这个模块编写了所有需要的类,所以我在一个 java 文件中拥有我需要的一切。
public class Main extends Module {
// ############### MAIN PAGE COMPONENT ##############
public class MainPage extends ModulePageContainer {
// ############### CLOCK COMPONENT ##############
public class ClockComponent extends JComponent {
private Date currentDateTime;
private SimpleDateFormat dateFormat;
public ClockComponent() {
this.dateFormat = new SimpleDateFormat( "HH:mm");
}
@Override
protected void paintComponent( Graphics g) {
super.paintComponent( g);
//...doing some paint stuff here...
}
public void setDateTime( Date dateTime) {
this.currentDateTime = dateTime;
}
}
// ############### CLOCK COMPONENT END ##############
// ############### MAIN INFO COMPONENT ##############
public class MainInfoComponent extends JComponent {
public MainInfoComponent() {
this.setLayout( null);
}
@Override
protected void paintComponent( Graphics g) {
super.paintComponent( g);
// ... just empty subcomponent ...
}
}
// ############### MAIN INFO COMPONENT END ##############
private ClockComponent clock;
private MainInfoComponent mainInfo;
public MainPage( Module parent) {
super( parent);
this.clock = new ClockComponent();
this.mainInfo = new MainInfoComponent();
this.setLayout( new MyGridLayout( 2, 1));
this.add( this.clock);
this.add( this.mainInfo);
}
public void clockTick( Date date) {
this.clock.setDateTime( date);
this.repaint();
}
}
// ############### MAIN PAGE COMPONENT END ##############
public Main( String name) {
super( name);
}
@Override
public void init() {
// every module has pages, this module has only one page called 'main'
MainPage mainPage = new MainPage( this);
mainPage.setName( "main");
this.addPage( mainPage);
}
}