我正在尝试向该程序添加菜单,但遇到问题。我认为菜单本身的代码没问题,但我不知道如何将它实际插入到我的 GUI 中。在这个项目中我有 4 节课。一个用于一些 JRadioButton,一个用于添加大文本字段,一个用于菜单,最后一个用于将所有内容组合在一起。当我在没有菜单类的情况下运行程序时,这就是输出。 Output of program without menu class
这也是一些代码。
JRadioButton encrypt1 = new JRadioButton("Reverse Word" );
JRadioButton encrypt2 = new JRadioButton("+1");
ButtonGroup group1 = new ButtonGroup();
JRadioButton decrypt1 = new JRadioButton("Reverse Word");
JRadioButton decrypt2 = new JRadioButton("+1");
ButtonGroup group2 = new ButtonGroup();
public chooseEncryption(){
setLayout(new GridLayout(3, 4));
panel1 = new JPanel(); panel2 = new JPanel(); panel3 = new JPanel();
panel4 = new JPanel(); panel5 = new JPanel(); panel6 = new JPanel();
panel7 = new JPanel(); panel8 = new JPanel(); panel9 = new JPanel();
panel10 = new JPanel(); panel11 = new JPanel(); panel12 = new JPanel();
encryptionLabel = new JLabel("Encryption");
decryptionLabel = new JLabel("Decryption");
group1.add(encrypt1);
group1.add(encrypt2);
group2.add(decrypt1);
group2.add(decrypt2);
panel2.add(encryptionLabel);
panel4.add(decryptionLabel);
panel6.add(encrypt1);
panel8.add(decrypt1);
panel10.add(encrypt2);
panel12.add(decrypt2);
add(panel1); add(panel2); add(panel3); add(panel4); add(panel5);
add(panel6); add(panel7); add(panel8); add(panel9); add(panel10);
add(panel11); add(panel12);
}
这是单选按钮类,然后我使用这个 putTogether 类集成它。
public putTogether(){ //Constructor of putTogether class
setTitle("Encryption Program");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel = new chooseEncryption(); //object of radio button class
panel2 = new textField(); //object of text field class
add(panel, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);
pack();
setVisible(true);
}
这是菜单类的一部分。
public class menu extends JFrame{
public void buildMenuBar(){
menuBar = new JMenuBar();
buildFileMenu();
buildEditMenu();
buildHelpMenu();
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
}
我如何设置菜单,使其成为 GUI 的一部分。我知道这与为其创建构造函数有关,但我无法取得任何进展。我很感谢您对此的帮助!
最佳答案
使用卡片布局。 如何使用卡片布局 - https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
希望!它有帮助。
关于java - 如何将菜单集成到布局 (Java GUI) 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61330745/