gpt4 book ai didi

java - 单击 Gridlayout 按钮,然后在按钮下加载一个 Java 表单

转载 作者:行者123 更新时间:2023-12-01 23:16:24 25 4
gpt4 key购买 nike

我现在真的不知道如何提出问题,我有一个带有 4 个按钮的网格布局。当用户按下“添加模块”时,如果可能的话,我希望按钮下有一个表单而不是新窗口。

frame = new JFrame("ModuleViewer");
makeMenu(frame);

Container contentPane = frame.getContentPane();

// Specify the layout manager with nice spacing
contentPane.setLayout(new GridLayout(0, 2));

addModule = new JButton("Toevoegen Module");
contentPane.add(addModule);

overview = new JButton("Overzicht Modules");
contentPane.add(overview);

addSchoolweeks = new JButton("Aapassen schoolweken");
contentPane.add(addSchoolweeks);

weekheavy = new JButton("Weekbelasting");
contentPane.add(weekheavy);

frame.pack();

Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
frame.setVisible(true);

我知道我首先需要为按钮添加 een 操作方法,我知道如何做到这一点,所以这并不重要。我只想知道如何在按钮下创建布局,以便当用户单击时将绘制布局。

最佳答案

每个面板只能有一种布局,但您可以使用多个面板来达到所需的效果:顶部面板使用 GridLayout 来容纳按钮,底部面板使用 CardLayout 来容纳多个其他面板,每个按钮单击一个面板。每个面板都可以使用您想要的任何布局,具体取决于其内容。

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

public class CardLayoutDemo implements Runnable
{
final static String CARD1 = "Red";
final static String CARD2 = "Green";
final static String CARD3 = "Blue";

JPanel cards;
CardLayout cardLayout;

public static void main(String[] args)
{
SwingUtilities.invokeLater(new CardLayoutDemo());
}

public void run()
{
JButton btnRed = createButton("Red");
JButton btnGreen = createButton("Green");
JButton btnBlue = createButton("Blue");

JPanel buttons = new JPanel(new GridLayout(1,3));
buttons.add(btnRed);
buttons.add(btnGreen);
buttons.add(btnBlue);

JPanel card1 = new JPanel();
card1.setBackground(Color.RED);

JPanel card2 = new JPanel();
card2.setBackground(Color.GREEN);

JPanel card3 = new JPanel();
card3.setBackground(Color.BLUE);

cardLayout = new CardLayout();
cards = new JPanel(cardLayout);
cards.add(card1, CARD1);
cards.add(card2, CARD2);
cards.add(card3, CARD3);

JFrame f = new JFrame("CardLayout Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(buttons, BorderLayout.NORTH);
f.add(cards, BorderLayout.CENTER);
f.setSize(300, 200);
f.setLocationRelativeTo(null);
f.setVisible(true);
}

private JButton createButton(final String name)
{
JButton button = new JButton(name);
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
cardLayout.show(cards, name);
}
});

return button;
}
}

关于java - 单击 Gridlayout 按钮,然后在按钮下加载一个 Java 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21140774/

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