gpt4 book ai didi

java - 将 JPanel 类放入另一个类的 JFrame 中

转载 作者:行者123 更新时间:2023-11-30 02:31:05 26 4
gpt4 key购买 nike

我必须插入另一个类的 JFrame、JPanel 中。我在 JFrame 中有一个 jMenuItem,我希望当我单击 JMenuItem 时,JPanel 将出现。

 private void searchStudMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                                   
searchStud s = new searchStud();
s.setVisible(true);
changePanel(s);
}

private void changePanel(JPanel panel) {
getContentPane().removeAll();
getContentPane().add(panel);
getContentPane().doLayout();
update(getGraphics());
}

searchStud 是包含 JPanel 的类。当我执行程序并单击 JMenuItem 时,没有任何反应......我尝试在网上搜索,但找到的内容不起作用。

最佳答案

实际组件 - 我认为是 JFrame - 已更改,必须重新验证:

private void changePanel(JPanel panel) {
getContentPane().removeAll();
getContentPane().add(panel);
revalidate();
}

刚刚用这个最少的代码进行了测试:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


@SuppressWarnings("serial")
public class Test extends JFrame {

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


private static class searchStud extends JPanel {
searchStud() {
add(new JLabel("SEARCH STUD"));
}
}


private Test() {
SwingUtilities.invokeLater(this::initGUI);
}

private void initGUI() {
JButton button = new JButton("Search");
button.addActionListener(this::searchStudMenuItemActionPerformed);

setDefaultCloseOperation(DISPOSE_ON_CLOSE);
add(button);
setSize(300, 200);
validate();
setLocationRelativeTo(null);
setVisible(true);
}

private void searchStudMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
searchStud s = new searchStud();
s.setVisible(true);
changePanel(s);
}

private void changePanel(JPanel panel) {
getContentPane().removeAll();
getContentPane().add(panel);
revalidate();
}
}

关于java - 将 JPanel 类放入另一个类的 JFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44260053/

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