gpt4 book ai didi

java - 有没有办法以简短的方式编写这段代码?

转载 作者:行者123 更新时间:2023-11-30 03:00:38 26 4
gpt4 key购买 nike

我一直在制作一个程序,其中我制作了一个comboBox,然后向其中添加一个actionlistener,如果我单击它,就会出现一个框架。

代码:

String menulist [] = {"", "Array", "BubbleSort" ," - Selection Sort"," - Insertion Sort"," - Merge Sort","Recursion"," - Factorial"," - Anagramming"," - Towers of Hanoi","Stacks","Trees"," - Types of Trees","Binary Tree","Shell Sort","Quick Sort","Hash Table","Graphs"};
final JComboBox SelectMenu = new JComboBox(menulist);
SelectMenu.setFont(new Font("Tahoma", Font.PLAIN, 17));

SelectMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int list = SelectMenu.getSelectedIndex();



if(list == 1){

//Array
JFrame frameArray = new JFrame();
frameArray.setBounds(100, 100, 830, 601);
frameArray.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frameArray.getContentPane().setLayout(null);
frameArray.setVisible(true);

JLabel lblArray = new JLabel("Array");
lblArray.setFont(new Font("Lucida Bright", Font.BOLD | Font.ITALIC, 25));
lblArray.setBounds(368, 63, 122, 41);
frameArray.getContentPane().add(lblArray);

JLabel AnArrayIs = new JLabel();
AnArrayIs.setBackground(Color.WHITE);
AnArrayIs.setText("An array is a systematic arrangement of similar objects, usually in rows and columns.");
AnArrayIs.setBounds(46, 103, 357, 432);
frameArray.getContentPane().add(AnArrayIs);

我会使用 if-else 在这种情况下我会使用很多 if 几乎 16 个示例。有没有一种方法可以为框架编写更短的代码?所以我会继续执行 if-else 直到 16 索引?

先谢谢你了!! (:

最佳答案

如果您唯一要更改的是标签和文本,则创建如下方法:

      public Jframe getJframe(String label, String text){    
JFrame frameArray = new JFrame();
frameArray.setBounds(100, 100, 830, 601);
frameArray.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frameArray.getContentPane().setLayout(null);
frameArray.setVisible(true);

JLabel lblArray = new JLabel(label);
lblArray.setFont(new Font("Lucida Bright", Font.BOLD | Font.ITALIC, 25));
lblArray.setBounds(368, 63, 122, 41);
frameArray.getContentPane().add(lblArray);

JLabel AnArrayIs = new JLabel();
AnArrayIs.setBackground(Color.WHITE);
AnArrayIs.setText(text);
AnArrayIs.setBounds(46, 103, 357, 432);
frameArray.getContentPane().add(AnArrayIs);
return frameArray;
}

那么你的 if 语句或 switch 语句只需如下所示:

Jframe myJframe = null;
if(list==1){
myJframe = getJframe(menuList[1],"An array is.....")
} else if(list ==2){
myJframe = getJframe(menuList[2],"BubbleSort is ...")
}....

我可能会为定义创建常量,以便您可以轻松更改它们,例如:

public static final String ARRAY_DEFINITION = "An array is a ....";

关于java - 有没有办法以简短的方式编写这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36097908/

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