为什么我必须在第一次运行时使用overMouse使JButton可见?

时间:2015-04-29 10:53:04

标签: java swing jbutton

我正在构建2d棋盘游戏,当我运行主类时,框架打开正常,但是JButton不可见,只有当我用鼠标按下按钮时它们才会变为可见。一些想法?

鼠标悬停图片前的

http://postimg.org/image/iyzvmvz6t

鼠标悬停图片后的

http://postimg.org/image/80om4palh

编辑:现在我发现如果我最小化窗口,所有JButton都会再次消失,希望它能为你们说些什么..

PanelTest.java:

  import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.imageio.*;
import javax.swing.*;

import sun.audio.*;

public class PanelTest
{  


    public static void main(String[] args)
    {  
        ImageFrame frame = new ImageFrame();
        frame.setResizable(false);

    }
}

class ImageFrame extends JFrame
{

    public ImageFrame()
    {   
        super();
        setTitle("Jumping Beans");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        Container C=getContentPane();
        C.setLayout(new BorderLayout());
        ImagePanel panel = new ImagePanel();
        panel.setPreferredSize(new Dimension(650, 650));
        C.add(panel,BorderLayout.CENTER);
        panel.whoStart();

        JPanel sideBar = new JPanel();
        sideBar.setPreferredSize(new Dimension(200, 650));
        panel.setAlignmentX(Component.CENTER_ALIGNMENT);
        JButton exit=new JButton("exit");
        exit.addActionListener(new ActionListener() 
        {   
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                System.exit(DISPOSE_ON_CLOSE);
            }
        });
        JButton MusicStart=new JButton("play music");
        MusicStart.addActionListener(new ActionListener() 
        {   

            @Override
            public void actionPerformed(ActionEvent e) 
            {
                panel.music();

            }
        });

        sideBar.setBackground(Color.lightGray);
        sideBar.add(exit);
        sideBar.add(MusicStart);
        C.add(sideBar, BorderLayout.EAST);

        JPanel bottom = new JPanel();
        bottom.setBackground(Color.lightGray);
        panel.turn = new JLabel();
        bottom.add(panel.turn);
        C.add(bottom, BorderLayout.SOUTH);  

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel.changeLabel();
        this.setVisible(true);



    }

    public static final int DEFAULT_WIDTH = 850;
    public static final int DEFAULT_HEIGHT = 650; 
}

class ImagePanel extends JPanel
{  
    public ImagePanel()
    {  
        super();
        this.setLayout(new GridLayout(11,11));
        AL=new ActionListener()
        {
            int numClicks =0 ;
            Slot source;
            Slot target;
            SlotButton sourceButton;
            SlotButton targetButton;

            @Override
            public void actionPerformed(ActionEvent e) 
            {

                if(numClicks==0)
                {
                    if(boardi.whoWins(boardi.getS()))
                    {
                        sourceButton=(SlotButton) e.getSource();
                        source=new Slot(sourceButton.getX(),sourceButton.getY(),sourceButton.getColor());
                        if(boardi.getTor()!=source.getColor())
                            numClicks--;
                        System.out.println("source num "+source.getRow()+","+source.getCol()+" clicked");
                        numClicks++;
                    }
                }
                else if(numClicks==1)
                {

                    targetButton=(SlotButton) e.getSource();
                    target=new Slot(targetButton.getX(),targetButton.getY(),targetButton.getColor());
                    System.out.println("target num "+target.getRow()+","+target.getCol()+" clicked");
                    if(boardi.LogiisMoving(source,target))
                    {
                        updateLogi(source,target);
                        updateGraphFromLogi(Buttons, boardi);
                        changeTor();
                        changeLabel();
                        //boardi.printBoard();


                    }
                    else if(boardi.LogiisEating(source,target))
                    {
                        System.out.println("Doing IsEating");
                        updateLogiEat(source, target);
                        updateGraphFromLogi(Buttons, boardi);
                        changeTor();
                        changeLabel();
                        if(!boardi.whoWins(boardi.getS()))
                            EndGame();
                        //boardi.printBoard();

                    }
                    else
                        if(target==source)numClicks++;
                    numClicks--;
                }


            }


        };


        try
        {
            image = ImageIO.read(new File("Images/background.png"));
            blueBean = ImageIO.read(new File("Images/blue_bean.png"));
            redBean = ImageIO.read(new File("Images/red_bean.png"));
            empty = ImageIO.read(new File("Images/Empty.png"));
            safeWall = ImageIO.read(new File("Images/safeWall.bmp"));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        Buttons=new SlotButton[11][11];

        for(int i=0;i<11;i++)
        {
            for(int j=0;j<11;j++)
            {
                Buttons[i][j]=new SlotButton(i,j,boardi.getS()[i][j].getColor());
                Buttons[i][j].addActionListener(AL);
                this.add(Buttons[i][j]);

            }
        }
        //repaint();

    }

public SlotButton [][] getButtons() 
{
    return Buttons;
}
public void EndGame()
{
    char winner=boardi.whoWinner(boardi.getS());
    for(int i=0;i<11;i++)
        for(int j=0;j<11;j++)
            Buttons[i][j].setEnabled(false);
    WinnerLabel(winner);
}

public void updateLogi(Slot source,Slot target)
{
    boardi.getS()[target.getRow()][target.getCol()].setColor(source.getColor());
    boardi.getS()[source.getRow()][source.getCol()].setColor('e');
}

public void updateLogiEat(Slot source,Slot target)
{
    boardi.getS()[target.getRow()][target.getCol()].setColor(source.getColor());
    boardi.getS()[source.getRow()][source.getCol()].setColor('e');
    boardi.getS()[boardi.getXofMiddle(source, target)][boardi.getYofMiddle(source, target)].setColor('e');
    System.out.println("middle row= "+boardi.getS()[boardi.getXofMiddle(source, target)][boardi.getYofMiddle(source, target)].getRow()+", middle col= "+boardi.getS()[boardi.getXofMiddle(source, target)][boardi.getYofMiddle(source, target)].getCol()+",middle color= "+boardi.getS()[boardi.getXofMiddle(source, target)][boardi.getYofMiddle(source, target)].getColor());
}

public void updateGraphFromLogi(SlotButton[][] buttons,board boardi) 
{
    char color='e';
    for(int i=0;i<11;i++)
        for(int j=0;j<11;j++)
        {
            color=boardi.getS()[i][j].getColor();
            buttons[i][j].setColor(color);
        }
}


//======================until here its logi rules======================================



public void changeLabel() 
{
    char t=boardi.getTor();
    System.out.println("changeLabel="+t);
    switch(t)
    {
    case 'r': turn.setText("Its turn of red player");
    break;

    case 'b': turn.setText("Its turn of blue player");
    break;
    }
}
public void WinnerLabel(char winner) 
{
    switch(winner)
    {
    case 'r': turn.setText("Its Winning of red player!");
    break;

    case 'b': turn.setText("Its Winning of blue player!");
    break;

    case 'd': turn.setText("Its a Draw!");
    break;

    case 'o': turn.setText("You Have To Finish The Game In One Move!");
    break;

    case 'x':break;
    }
}

public void printBordi(board a)
{
    for(int i=0;i<7;i++)
    {
        System.out.printf("-----------------------------------");
        System.out.printf("\n");
        for(int j=0;j<7;j++)
            System.out.printf("| %c |",a.getS()[i][j].getColor());
        System.out.printf("\n");
    }
    System.out.printf("-----------------------------------");
}

public board getBoard()
{
    return boardi;
}
public void changeTor()
{
    char tor=boardi.getTor();
    if(tor=='b')
    {
        boardi.setTor('r');
    }

    else
        boardi.setTor('b');
    System.out.println("ChangedTor="+boardi.getTor());
}

public void whoStart()
{
    String input="";
    input=JOptionPane.showInputDialog("Enter the color of the first player, b for Blue and r for Red");
    System.out.println("input="+input);
    if((input.equals("b"))||(input.equals("B")))
        boardi.setTor('b');
    else if((input.equals("r"))||(input.equals("R")))
        boardi.setTor('r');
    System.out.println("tor="+boardi.getTor());
}

//=================================from here its finish game rules===========================


public int getTurn()
{
    return comOrHum;
}
public void setTurn(int num)
{
    this.comOrHum+=num;
}
JLabel turn;
private ActionListener AL;
private Image image;
public int comOrHum=1;
public static Image redBean;
public static Image blueBean;
public static Image empty;
public static Image safeWall;
private int numClicks=0;
private board boardi = new board();
private SlotButton[][] Buttons;

//=================Music===================
public static void music() 
{   
    AudioStream BGM=null;

    AudioPlayer  MGP = AudioPlayer.player;

    AudioData MD;

    ContinuousAudioDataStream loop = null;

    try
    {
        InputStream test = new FileInputStream("Music/gameMusic.wav");
        BGM = new AudioStream(test);
        AudioPlayer.player.start(BGM);
    }
    catch(FileNotFoundException e){
        System.out.print(e.toString());
    }
    catch(IOException error)
    {
        System.out.print(error.toString());
    }
    MGP.start(loop);

}
//============Side Bar Buttons========================================

}

board.java:

     import java.awt.Image;
     import java.util.ArrayList;

public class board extends PanelTest
{

    private Slot[][] s = new Slot[11][11];
    private char tor='b';
    public board()
    {
        super();
        for(int i=0;i<2;i++)
            for(int j=0;j<11;j++)
                s[i][j]=new Slot(i,j,'x');
        for(int i=9;i<11;i++)
            for(int j=0;j<11;j++)
                s[i][j]=new Slot(i,j,'x');
        for(int i=0;i<2;i++)
            for(int j=2;j<9;j++)
                s[j][i]=new Slot(i,j,'x');
        for(int i=9;i<11;i++)
            for(int j=2;j<9;j++)
                s[j][i]=new Slot(i,j,'x');
        for(int i=2;i<5;i++)
            for(int j=2;j<9;j++)
                s[i][j]=new Slot(i,j,'b');
        for(int i=6;i<9;i++)
            for(int j=2;j<9;j++)
                s[i][j]=new Slot(i,j,'r');
        for(int j=2;j<5;j++)
            s[5][j]=new Slot(5,j,'b');
        for(int j=6;j<9;j++)
            s[5][j]=new Slot(5,j,'r');
        s[5][5]=new Slot(5,5,'e');

    }


    public board newBoard(Slot[][] b) 
    {

        board f=new board();
        f.s=b;
        return f;
    }


    public Slot[][] getS() 
    {
        return s;
    }

    public Slot getSlot(int i,int j)
    {
        return s[i][j];
    }

    public void printBoard()
    {
        for(int i=0;i<11;i++)
        {
            System.out.printf("-----------------------------------");
            System.out.printf("\n");
            for(int j=0;j<11;j++)
                System.out.printf("| %c |",s[i][j].getColor());
            System.out.printf("\n");
        }
        System.out.printf("-----------------------------------");
    }

    //==================================================================

    public boolean LogicheckMove(Slot source,Slot target)
    {
        if((source.getRow()==target.getRow())&&(source.getCol()==target.getCol())) // source and target are the same slot
            return false;       
        if((target.getColor()!='e')||(source.getColor()=='e'))
            return false;   
        System.out.println("LogicheckMove is true");
        return true;
    }

    public boolean LogiemptyNei(Slot source,Slot target)
    {
        int row=source.getRow();
        int col=source.getCol();
        if(row<=8)
        {
            if(s[row+1][col].getColor()=='e')
                //if(s[row+1][col]==target)
                return true;
        }
        if(row>=2)
        {
            if(s[row-1][col].getColor()=='e')
                //if(s[row-1][col]==target)
                return true;
        }
        if(col<=8)
        {
            if(s[row][col+1].getColor()=='e')
                //if(s[row][col+1]==target)
                return true;
        }
        if(col>=2)
        {
            if(s[row][col-1].getColor()=='e')
                //if(s[row][col-1]==target)
                return true;
        }
        return false;
    }

    public boolean LogiisMoving(Slot source,Slot target)
    {
        int row=source.getRow();
        int col=source.getCol();
        System.out.println("source x="+source.getRow()+"y="+source.getCol());
        System.out.println("target x="+target.getRow()+"y="+target.getCol());
        if(!LogicheckMove(source,target))
        {   
            System.out.println("The Move Is illigel");
            return false;
        }
        if(!LogiemptyNei(source,target))
        {   
            System.out.println("The Move Is illigel2");
            return false;
        }
        if(!distanceIsOkForMoving(source,target))
            return false;
        System.out.println("The Move Is ligel");

        return true;
    }

    public boolean distanceIsOkForMoving(Slot source,Slot target)
    {
        if((distanceOfRow(source,target)!=1)||(distanceOfCol(source,target)!=1))
            return false;
        return true;
    }
    public int distanceOfRow(Slot source, Slot target) 
    {

        return Math.abs(source.getRow()-target.getRow());
    }
    public int distanceOfCol(Slot source, Slot target) 
    {

        return Math.abs(source.getCol()-target.getCol());
    }


    public boolean LogiisEating(Slot source,Slot target)
    {
        System.out.println("Inside IsEating");
        int row=source.getRow();
        int col=source.getCol();
        if(!LogicheckMove(source,target))
        {   
            System.out.println("The Eating Is illigel");
            return false;
        }
        if(!LogirightEat(source,target))
        {
            System.out.println("Not rightEat");
            return false;
        }

        return true;

    }
    public boolean LogirightEat(Slot source, Slot target) 
    {   

        //not wrote yet
        return true;
    }

    public boolean whoWins(Slot [][] board)
    {
        int bluecount=0,redcount=0;
        for(int i=2;i<9;i++)
            for(int j=2;j<9;j++)
                if(board[i][j].getColor()=='r')
                    redcount++;
                else  if(board[i][j].getColor()=='b')
                    bluecount++;
        if(redcount==0)
        {
            System.out.println("Blue Wins!");
            return false;
        }
        else if(bluecount==0)
        {
            System.out.println("Red Wins!");
            return false;
        }
        else if((bluecount==1)&&(redcount==1))
        {
            Slot source=null;
            Slot target=null;
            for(int i=2;i<9;i++)
                for(int j=2;j<9;j++)
                    if(board[i][j].getColor()=='r')
                        source=s[i][j];
                    else  if(s[i][j].getColor()=='b')
                        target=s[i][j];
            if(LogiisEating(source,target))
            {
                System.out.println("You Have To Finish The Game In One Move!");
            }
            else
            {
                System.out.println("Draw!");
                return false;
            }

        }
        return true;
    }

    public char whoWinner(Slot [][] board)
    {
        int bluecount=0,redcount=0;
        for(int i=2;i<9;i++)
            for(int j=2;j<9;j++)
                if(board[i][j].getColor()=='r')
                    redcount++;
                else  if(board[i][j].getColor()=='b')
                    bluecount++;
        if(redcount==0)
        {
            return 'b';
        }
        else if(bluecount==0)
        {
            return 'r';
        }
        else if((bluecount==1)&&(redcount==1))
        {
            Slot source=null;
            Slot target=null;
            for(int i=2;i<9;i++)
                for(int j=2;j<9;j++)
                    if(board[i][j].getColor()=='r')
                        source=s[i][j];
                    else  if(s[i][j].getColor()=='b')
                        target=s[i][j];
            if(LogiisEating(source,target))
            {
                return 'o';
            }
            else
            {
                return 'd';
            }

        }
        return 'x';
    }



    public int getXofMiddle(Slot source,Slot target)
    {
        int row=source.getRow();
        if(target.getRow()-2==row)
            return row+1;
        else if(target.getRow()+2==row)
            return row-1;
        return row;
    }

    public int getYofMiddle(Slot source,Slot target)
    {
        int col=source.getCol();
        if(target.getCol()-2==col)
            return col+1;
        else if(target.getCol()+2==col)
            return col-1;
        return col;
    }

    public char getTor() {
        return tor;
    }


    public void setTor(char tor) {
        this.tor = tor;
    }



    }

1 个答案:

答案 0 :(得分:0)

与您的问题无关,但是:

  1. 变量名称不应以大写字母开头。你的大部分名字都是正确的,但很多都没有。保持一致!

  2. 方法名称不应以大写字母开头。同样,大多数都是正确的,但很多都不是。没有理由不一致!

  3. 类名应该以大写字符开头。同样,大多数人都会这样做。但

  4. 在使框架可见之前,应调用setResizable(true)语句。 (它甚至可能需要在setSize()方法之前调用,我不确定)。在任何情况下都不应该在框架可见之后执行。