gpt4 book ai didi

Java Swing : How to change GUI dynamically

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:49:43 25 4
gpt4 key购买 nike

我需要动态添加组件。此外,我需要动态更改布局。

最佳答案

作为引用,这里有一个 sscce显示基本方法,validate() .这个更详细example显示了两个要求:它更改布局并动态添加组件。

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;

/** @see http://stackoverflow.com/questions/5750068 */
public class DynamicLayout extends JPanel {

private static final LayoutManager H = new GridLayout(1, 0);
private static final LayoutManager V = new GridLayout(0, 1);

public DynamicLayout() {
this.setLayout(H);
this.setPreferredSize(new Dimension(320, 240));
for (int i = 0; i < 3; i++) {
this.add(new JLabel("Label " + String.valueOf(i), JLabel.CENTER));
}
}

private void display() {
JFrame f = new JFrame("DynamicLayout");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
JPanel p = new JPanel();
p.add(new JButton(new AbstractAction("Horizontal") {

@Override
public void actionPerformed(ActionEvent e) {
DynamicLayout.this.setLayout(H);
DynamicLayout.this.validate();
}
}));
p.add(new JButton(new AbstractAction("Vertical") {

@Override
public void actionPerformed(ActionEvent e) {
DynamicLayout.this.setLayout(V);
DynamicLayout.this.validate();
}
}));
f.add(p, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
new DynamicLayout().display();
}
});
}
}

关于Java Swing : How to change GUI dynamically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5750068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com