我正在努力制作正在进行的Tic Tac Toe游戏。我在将图像加载到JButton时遇到问题。我刚刚编写了一个按钮。我做了一个res文件,就像res / image / Cross.png和Circle.png。它们位于构建路径中。但即使单击按钮,也不会显示图像 我唯一的课程
package com.arjav.tictactoe ;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TTT implements ActionListener{
JFrame frame ;
int turn = 0 ;
ImageIcon cross = new ImageIcon("Cross.png");
ImageIcon circle = new ImageIcon("Circle.png");
public JButton x1y1 = new JButton("Click me");
public JButton x2y1 = new JButton("Click me");
public JButton x3y1 = new JButton("Click me");
public JButton x1y2 = new JButton("Click me");
public JButton x2y2 = new JButton("Click me");
public JButton x3y2 = new JButton("Click me");
public JButton x1y3 = new JButton("Click me");
public JButton x2y3 = new JButton("Click me");
public JButton x3y3 = new JButton("Click me");
public TTT(){
frame = new JFrame();
frame.setTitle("Let's Play Tic Tac Toe ?? YES!!");
frame.setSize(300 , 300);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
}
public void init(){
GridLayout layout = new GridLayout(3 , 3);
frame.setLayout(layout);
frame.add(x1y1);
frame.add(x2y1);
frame.add(x3y1);
frame.add(x1y2);
frame.add(x2y2);
frame.add(x3y2);
frame.add(x1y3);
frame.add(x2y3);
frame.add(x3y3);
x1y1.addActionListener(this);
x2y1.addActionListener(this);
x3y1.addActionListener(this);
x1y2.addActionListener(this);
x2y2.addActionListener(this);
x3y2.addActionListener(this);
x1y3.addActionListener(this);
x2y3.addActionListener(this);
x3y3.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == x1y1){
if(turn == 0) {x1y1.setIcon(circle);
turn++ ;
System.out.println(turn);
}
}
}
public static void main(String[] args)
{
TTT main = new TTT();
}
}
答案 0 :(得分:0)
使用
ImageIcon circle = new ImageIcon(getClass().getResource("Circle.png"));
代替
ImageIcon circle = new ImageIcon("Circle.png");
。如果您的图标图像不在默认包中,则必须使用"/res/image/Circle.png"