gpt4 book ai didi

具有隐藏和显示功能的 Java Swing 表单菜单

转载 作者:太空宇宙 更新时间:2023-11-04 10:29:28 24 4
gpt4 key购买 nike

我对 GUI 编程有点陌生,我一直在努力弄清楚如何实现如下所示的东西:

/image/zvWsH.png

基本上我想要一些文本条目,侧面有一个箭头。单击箭头或文本时,其下方会出现一个表单。

如有任何建议,我们将不胜感激,先谢谢您。

最佳答案

从概念上讲,这只是使容器(如 JPanel)隐藏或显示,并让布局管理器完成其工作

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

JPanel panel = new JPanel(new GridBagLayout());
panel.add(new JLabel("Pecka-boo"));

JButton btn = new JButton("Show");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel.setVisible(!panel.isVisible());
btn.setText(panel.isVisible() ? "Hide" : "Show");
}
});

gbc.gridx = 0;
gbc.gridy = 0;
add(btn, gbc);

gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
add(panel, gbc);
panel.setVisible(false);
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

}

}

看一下:

了解更多详细信息。

仅供引用:更复杂的 UI 会将子表单作为单独的类,这将减少(各个类的)复杂性并解耦代码

关于具有隐藏和显示功能的 Java Swing 表单菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50183161/

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