2015-11-02 38 views
-1

我正在製作一個正在進行的井字遊戲。將圖像加載到JButton時遇到問題。我現在只編寫了一個按鈕。我製作了一個res文件,就像res/image/Cross.png和Circle.png。他們正在構建路徑中。但是,即使點擊按鈕後,將不顯示圖像 我唯一的類無法使用ImageIcons在JButton上繪製圖像

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

它甚至在控制檯中打印1 –

回答

0

使用 ImageIcon circle = new ImageIcon(getClass().getResource("Circle.png")); 代替 ImageIcon circle = new ImageIcon("Circle.png");。如果您的圖標圖像不在默認包裝內,則必須使用路徑圖標,如"/res/image/Circle.png"