gpt4 book ai didi

java - 用于根据 JComboBox 选择确定要执行的操作的 JButton

转载 作者:行者123 更新时间:2023-12-01 17:11:17 26 4
gpt4 key购买 nike

我开发了一个简单的 JFrame,它由一个包含标签、组合框和按钮的面板组成。我想要的只是根据用户从组合框中的选择将用户重定向到不同的面板。我在让按钮检查所选项目时似乎出现错误。这是我到目前为止所做的...

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test
{

public static void main(String [] args)
{

// The Frame Design Part...
final JFrame ApplicationFrame=new JFrame("Bounceable Ball Game");
ApplicationFrame.setVisible(true);
ApplicationFrame.setSize(600,600);
ApplicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ApplicationFrame.setLocationRelativeTo(null);
JMenuBar ApplicationMenuBar=new JMenuBar();
JMenu File=new JMenu("File");
JMenu Edit=new JMenu("Edit");
JMenu Play=new JMenu("Play");
ApplicationMenuBar.add(File);
JMenuItem Exit=new JMenuItem("Exit");
File.add(Exit);
ApplicationMenuBar.add(Edit);
ApplicationMenuBar.add(Play);
ApplicationFrame.setJMenuBar(ApplicationMenuBar);
JPanel ApplicationPanel =new JPanel(new GridBagLayout());
GridBagConstraints DesignConstraints=new GridBagConstraints();
DesignConstraints.insets=new Insets(10,10,10,10);
DesignConstraints.gridx=0;
DesignConstraints.gridy=1;
JLabel GameChoiceLabel=new JLabel("Please Select The Game That You Want To Play...");
ApplicationPanel.add(GameChoiceLabel,DesignConstraints);
DesignConstraints.gridx=0;
DesignConstraints.gridy=2;
ApplicationPanel.add(GameChoiceComboBox,DesignConstraints);
DesignConstraints.gridx=0;
DesignConstraints.gridy=3;
JButton GameChoiceButton=new JButton("Play Game");
GameChoiceButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
JComboBox comboBox = (JComboBox) e.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("TennisBall"))
{
ApplicationMenuBar.add(File);
JMenuItem Exit=new JMenuItem("Exit");
File.add(Exit);
ApplicationMenuBar.add(Edit);
ApplicationMenuBar.add(Play);
ApplicationFrame.setJMenuBar(ApplicationMenuBar);
JPanel ApplicationPanel1 =new JPanel(new GridBagLayout());
ApplicationFrame.setContentPane(ApplicationPanel1);
}
}
});
ApplicationPanel.add(GameChoiceButton,DesignConstraints);
ApplicationFrame.setContentPane(ApplicationPanel);
}
}

提前致谢:)

最佳答案

问题出在这一行:

JComboBox 组合框 = (JComboBox) e.getSource();

这是单击 GameChoiceButton 时的操作。但随后您获取源(即按钮)并尝试将其转换为 JComboBox。

要使您的代码正常工作,请进行以下更改:

final JComboBox GameChoiceComboBox=new JComboBox();  //MAKE THIS FINAL
...

GameChoiceButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//USE THE COMBO BOX DIRECTLY and getSelectedItem()
if(GameChoiceComboBox.getSelectedItem().equals("TennisBall"))

{
JMenuBar ApplicationMenuBar=new JMenuBar();
JMenu File=new JMenu("File");
JMenu Edit=new JMenu("Edit");

关于java - 用于根据 JComboBox 选择确定要执行的操作的 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23680161/

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