【发布时间】:2013-12-01 03:18:08
【问题描述】:
当用户单击标题为“规则”的菜单按钮时,我试图在框架中显示一段文本。当我单击规则时,不知何故没有显示任何内容。
所以我的问题是,为什么当我点击规则时没有显示任何内容。 我认为将 ActionListener 添加到规则意味着当单击规则时,它将弹出一个标题为“规则”的新框架,并且在框架内会有一条消息说“在此处编写规则...”。
这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CheckerProgram{
public static int rows = 8;
public static int columns = 8;
public static Color color1 = Color.BLACK;
public static Color color2 = Color.RED;
public static void main( String[] args ){
JFrame window = new JFrame("Checkers");
window.setSize( 800, 800 );
window.setTitle("Checkers!");
Container pane = window.getContentPane();
pane.setLayout(new GridLayout(rows, columns));
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
Color temp;
for( int i=0; i<rows; i++ ){
if( i%2 == 0 ){
temp = color1;
}
else{
temp = color2;
}
for( int j=0; j<columns; j++ ){
JPanel panel = new JPanel();
panel.setBackground(temp);
if( temp.equals(color1)){
temp = color2;
}
else{
temp = color1;
}
pane.add(panel);
}
}
window.setVisible(true);
JMenuBar menuBar = new JMenuBar();
window.setJMenuBar(menuBar);
// Display options ex, new game, surrender, close game.
JMenu options = new JMenu("Options");
menuBar.add(options);
JMenuItem newGame = new JMenuItem("New Game");
JMenuItem surrender = new JMenuItem("Surrender");
JMenuItem closeGame = new JMenuItem("Close Game");
options.add(newGame);
options.add(surrender);
options.add(closeGame);
// Action button for Close Game under Options menu
class closeGameAction implements ActionListener{
public void actionPerformed( ActionEvent e ){
System.exit(0);
}
}
closeGame.addActionListener( new closeGameAction() );
// Display scores for both players
JMenu scores = new JMenu("Scores");
menuBar.add(scores);
// Display rules for game
JMenu rules = new JMenu("Rules");
menuBar.add(rules);
rules.addActionListener( new rulesAction() );
} // End of main
static class rulesAction implements ActionListener{
public void actionPerformed( ActionEvent e ){
JFrame displayRules = new JFrame("Rules");
displayRules.setVisible(true);
displayRules.setSize( 300, 300 );
JLabel label = new JLabel("Write rules here...");
JPanel panel = new JPanel();
panel.add(label);
displayRules.add(panel);
}
}
}
这是主框架的屏幕截图。因此,当我单击它时,有一个名为“规则”的菜单选项没有任何反应。
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖 SSCCE。无需在标题中包含主要标签,并注意拼写为“Java”而不是“JAVA”(无需 SHOUT)。 “任何帮助将不胜感激:)” 任何问题。你有问题吗?这是什么?
-
贴出完整的代码,方便大家理解
-
@peeskillet 试过了,没用。当我点击规则时没有任何反应
标签: java swing jframe actionlistener jmenu