java是否使用action listener将5x5网格布局添加到JComboBox?
我必须显示一个下拉菜单,当选择新游戏时,会显示一个5x5区域,我正在为学校项目创建的游戏会显示刺客游戏的位置实例。但我无法在选择新游戏时显示网格,但Jcombobox和动作监听器尽我所知工作正常。我该如何解决这个问题?如果有任何方法可以使它更简单、更高效
package GUI;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class mainView {
private static JPanel newGame;
private static JFrame main;
protected static void newGamePanel() {
// TODO Auto-generated method stub
GridLayout lay = new GridLayout(5,5);
newGame = new JPanel();
newGame.setLayout(lay);
newGame.setVisible(true);
newGame.setLocation(200, 300);
newGame.setSize(200,200);
main.add(newGame);
}
public static void codeNameView(){
main = new JFrame("CodeNames");
main.setSize(400, 600);
main.setVisible(true);
//dropdown menu for quit and new game
String[] choice = {" " , "New Game" , "Quit"};
final JComboBox<String> dropDown = new JComboBox<String>(choice);
//below is the panel where we add new game and quit too
JPanel dropDownPanel = new JPanel();
dropDownPanel.add(dropDown);
main.add(dropDownPanel);
//ok button stuff
//action listener for dropdown combobox
dropDown.addActionListener(new ActionListener(){
//functionality for combobox
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JComboBox cb = (JComboBox) e.getSource();
Object selectedOption = dropDown.getSelectedItem();
// Object command = e.getActionCommand();
if (selectedOption == "Quit") {
main.dispose();
}else if(selectedOption == "New Game"){
newGamePanel();
}
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
codeNameView();
}
});
}
}
# 1 楼答案
首先,不要在类中使用静态变量和方法。这表明设计不当
将组件添加到可见GUI时,基本代码为:
您需要重新验证才能调用布局管理器,以便为添加到面板的组件指定尺寸/位置。否则,组件的大小为(0,0),因此没有要绘制的内容
或者,问题是您的代码从未执行过。你如何验证这一点
你添加了一个系统吗。出来println(…)语句,以验证执行了哪段代码
不要使用“==”进行字符串比较
要比较字符串的值,请使用等于(…)方法:
编辑:
此外,您的代码只是继续向框架添加组件。Swing实际上会绘制首先添加的最后一个组件。因此,如果在框架中添加多个游戏面板,则添加的第一个面板将始终绘制在添加的最后一个面板的顶部
因此,更好的解决方案是在帧上使用
CardLayout
。这将允许您交换面板,以便一次只显示一个面板。阅读Swing教程中关于How to Use CardLayout的部分,了解更多信息和工作示例