有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何向按钮添加图像

我正在做一个小游戏。我想显示X和O的图像,而不是在用户单击按钮时仅仅放置一个字符串。在我的actionlister方法中,我添加了图像,但在我运行程序时它没有显示。我不确定我错在哪里。提前谢谢

 public class TTT extends JFrame implements ActionListener {

        private JButton buttons[] = new JButton[9];
        private JButton exitButton;
        public JLabel title;
        public JPanel titlePanel, panel;
        ;
        int count = 0;
        int symbolCount = 0;

        public TTT() {

            title = new JLabel("Welcome to my Tic Tac Toe Game!");
            titlePanel = new JPanel();
            title.setFont(new Font(Font.SERIF, 0, 30));
            titlePanel.add(title);
            this.add(titlePanel, BorderLayout.NORTH);

            panel = new JPanel(new GridLayout(3, 3));
            for (int i = 0; i < buttons.length; i++) {
                buttons[i] = new JButton();
                panel.add(buttons[i]);
                buttons[i].setEnabled(true);
                buttons[i].addActionListener(this);
            }
            this.add(panel, BorderLayout.CENTER);

            JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
            exitButton = new JButton("Quit");
            panel1.add(exitButton);
            this.add(panel1, BorderLayout.SOUTH);
            exitButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(WIDTH);
                }
            });

        }

        public static void main(String[] args) {
            TTT ref1 = new TTT();
            ref1.setTitle("Tic Tac Toe");
            ref1.setVisible(true);
            ref1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ref1.setSize(500, 500);
            ref1.setLocationRelativeTo(null);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            count++;
            for (int i = 0; i < buttons.length; i++) {
                if (buttons[i] == e.getSource()) {
                    if (symbolCount % 2 == 0) {
                    buttons[i].setIcon(new ImageIcon("images.jpg"));
                  //  buttons[i].setText("X");
                    validate();
                    } else {
                        buttons[i].setText("O");
                        buttons[i].setEnabled(false);
                    }

                }
            }
            if (count >= buttons.length) {
                JOptionPane.showMessageDialog(null, "End");
            }
            symbolCount++;
        }
    }

共 (0) 个答案