试图了解javax.swing的细节

时间:2012-02-04 22:13:08

标签: java swing jframe jpanel jcomponent

所以我一直在尝试获取javax.swing的句柄并且遇到了一些麻烦。我正在尝试实现'8拼图',其中在3x3网格中设置了8个拼贴和一个打开点,当点击与打开点相邻的拼块时,它与空位交易空间。我的结构包含一个JFrame,它包含一个JPanel,而JPanel包含9个tile作为JComponents,但是只有JPanel渲染,并且找不到任何图块。任何有关此问题的帮助将不胜感激。

    import javax.swing.*;



    public class MainFrame{

        public static void main(String[] args){
            JFrame frame = new JFrame("8 Puzzle");
            frame.setVisible(true);
            frame.setSize(600, 600);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            PieceManager pm = new PieceManager();
            frame.add(pm);

        }
   }

    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Random;

    import javax.swing.*;

第二课

    public class PieceManager extends JPanel{

        int[] possmoves;
        GameTile[] pieces;
        int openSpot;

        public PieceManager(){
            this.setSize(600,600);
            this.setBackground(new Color(255,255,255));
            this.setLayout(new GridLayout(3,3));
            pieces = new GameTile[9];
            this.init();
            this.addMouseListener(new ClickAction());
        }

        public void init(){
            ArrayList<Integer> nums = new ArrayList<Integer>();
            Random rand = new Random();
            for(int i=0;i<9;i++){
                nums.add(i);
            }
            for(int i=0,j=8;i<8;i++,j--){
                int p = rand.nextInt(j);
                GameTile x = new GameTile(i,nums.remove(p));
                pieces[i]=x;
                nums.removeAll(Collections.singleton(null));
            }
            GameTile z = new GameTile(8,nums.get(0));
            pieces[8]=z;
            possmoves = new int[4];
            boolean found = false;
            for(int i=0;i<9||found;i++){
                if(pieces[i].getID()==0){
                    openSpot = pieces[i].getPos();
                }
            }
            setOpenSpot();
            paint();
        }

        public void paint(){
            this.removeAll();
            for(int i=0;i<9;i++){
                this.add(pieces[i]);
                pieces[i].setVisible(true);
            }
        }

        public void setOpenSpot(){
            Arrays.fill(possmoves,-1);
            if(openSpot==0){
                possmoves[0]=1;
                possmoves[1]=3;
            } else if(openSpot==1){
                possmoves[0]=0;
                possmoves[1]=2;
                possmoves[3]=4;
            } else if(openSpot==2){
                possmoves[0]=1;
                possmoves[1]=5;
            } else if(openSpot==3){
                possmoves[0]=0;
                possmoves[1]=4;
                possmoves[2]=6;
            } else if(openSpot==4){
                possmoves[0]=1;
                possmoves[1]=3;
                possmoves[2]=5;
                possmoves[3]=7;
            } else if(openSpot==5){
                possmoves[0]=2;
                possmoves[1]=4;
                possmoves[3]=8;
            } else if(openSpot==6){
                possmoves[0]=3;
                possmoves[1]=7;
            } else if(openSpot==7){
                possmoves[0]=6;
                possmoves[1]=4;
                possmoves[2]=8;
            } else if(openSpot==8){
                possmoves[0]=5;
                possmoves[1]=7;
            }

        }

        public void checkCorrect(){

        }

        public class ClickAction implements MouseListener{


            @Override
            public void mouseClicked(MouseEvent e) {

                int x = e.getX();
                int y = e.getY();
                int pX=(int)Math.floor(x/200);
                int pY=(int)Math.floor(y/200);
                int piecepressed=(pY*3)+pX;
                boolean moveable = false;
                int toBeMoved = -1;
                for(int i=0;i<4;i++){
                    if(piecepressed==possmoves[i]){
                        moveable=true;
                        toBeMoved=possmoves[i];
                    }
                }
                if(moveable){
                    GameTile saved=pieces[openSpot];
                    pieces[openSpot]=pieces[toBeMoved];
                    pieces[toBeMoved]=saved;
                    openSpot=toBeMoved;
                    setOpenSpot();
                    paint();
                    checkCorrect();
                }
            }

            @Override
            public void mouseEntered(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }

            @Override
            public void mouseExited(MouseEvent arg0) {
                // TODO Auto-generated method stub
        }

            @Override
            public void mousePressed(MouseEvent arg0) {
                // TODO Auto-generated method stub  
            }

            @Override
                public void mouseReleased(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }   
        }
   }

瓷砖等级(第3和最后)

    import java.awt.*;
    import javax.swing.JComponent;

    public class GameTile extends JComponent{

private int id;
private int position;

public GameTile(int id, int initpos){
    if(id==0){
        this.id=id;
        this.position=initpos;
    } else{
        this.id=id;
        this.position = initpos;
        String label = Integer.toString(id);
        setSize(200,200);
        setBackground(new Color(0,0,0));
        Label l = new Label(label,Label.CENTER);
        this.add(l);
        l.setVisible(true);
    }
}

public void setPos(int position){
    this.position=position;
}

public int getPos(){
    return position;
}

public int getID(){
    return id;
}
    }

1 个答案:

答案 0 :(得分:5)

使用JComponent很好,但您可能希望将其设置为不透明。

另外

  • 不要将AWT(即Label)与Swing组件混合使用。
  • 不要setSize(...)。而是处理preferredSize。最好覆盖getPreferredSize()并返回适当的维度。我已经用了setPreferredSize(...),但是冒着kleopatra的愤怒。
  • 不要在没有充分理由的情况下覆盖JComponent或其任何子代(包含JPanel)绘制方法(您没有)。而是覆盖paintComponent编辑:我看到你的绘画方法不是真正的覆盖,所以这没关系 - 对不起我的误解。
  • 您几乎从不直接致电paintpaintComponent。而是调用repaint()并让JVM为您调用绘制方法。 编辑:同上,因为这是我对您的代码的误解。在删除和替换JPanel中的组件后,想要调用'revalidate()and repaint()`。
  • 如果你给它们边框,你可以看到你的JComponents存在并被计算在内。
  • 编辑2 :如果您希望轻松放置和可视化添加的组件,则需要为JComponents提供布局。在这个例子中,我给了我一个BorderLayout

为了方便编译,我将一堆类合并到一个文件中 我已经通过// !!评论表明了重大变化。

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

import javax.swing.*;

public class MainFrame {

   public static void main(String[] args) {
      JFrame frame = new JFrame("8 Puzzle");
      frame.setVisible(true);
      frame.setSize(600, 600);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      PieceManager pm = new PieceManager();
      frame.add(pm);

   }
}

class PieceManager extends JPanel {

   int[] possmoves;
   GameTile[] pieces;
   int openSpot;

   public PieceManager() {
      this.setSize(600, 600);
      this.setBackground(new Color(255, 255, 255));
      this.setLayout(new GridLayout(3, 3));
      pieces = new GameTile[9];
      this.init();
      this.addMouseListener(new ClickAction());
   }

   public void init() {
      ArrayList<Integer> nums = new ArrayList<Integer>();
      Random rand = new Random();
      for (int i = 0; i < 9; i++) {
         nums.add(i);
      }
      for (int i = 0, j = 8; i < 8; i++, j--) {
         int p = rand.nextInt(j);
         GameTile x = new GameTile(i, nums.remove(p));
         pieces[i] = x;
         nums.removeAll(Collections.singleton(null));
      }
      GameTile z = new GameTile(8, nums.get(0));
      pieces[8] = z;
      possmoves = new int[4];
      boolean found = false;
      for (int i = 0; i < 9 || found; i++) {
         if (pieces[i].getID() == 0) {
            openSpot = pieces[i].getPos();
         }
      }
      setOpenSpot();
      paint();
   }

   public void paint() {
      this.removeAll();
      for (int i = 0; i < 9; i++) {
         this.add(pieces[i]);
         pieces[i].setVisible(true);
      }
      revalidate(); // !!
      repaint(); // !!
   }

   public void setOpenSpot() {
      Arrays.fill(possmoves, -1);
      if (openSpot == 0) {
         possmoves[0] = 1;
         possmoves[1] = 3;
      } else if (openSpot == 1) {
         possmoves[0] = 0;
         possmoves[1] = 2;
         possmoves[3] = 4;
      } else if (openSpot == 2) {
         possmoves[0] = 1;
         possmoves[1] = 5;
      } else if (openSpot == 3) {
         possmoves[0] = 0;
         possmoves[1] = 4;
         possmoves[2] = 6;
      } else if (openSpot == 4) {
         possmoves[0] = 1;
         possmoves[1] = 3;
         possmoves[2] = 5;
         possmoves[3] = 7;
      } else if (openSpot == 5) {
         possmoves[0] = 2;
         possmoves[1] = 4;
         possmoves[3] = 8;
      } else if (openSpot == 6) {
         possmoves[0] = 3;
         possmoves[1] = 7;
      } else if (openSpot == 7) {
         possmoves[0] = 6;
         possmoves[1] = 4;
         possmoves[2] = 8;
      } else if (openSpot == 8) {
         possmoves[0] = 5;
         possmoves[1] = 7;
      }

   }

   public void checkCorrect() {

   }

   public class ClickAction implements MouseListener {

      @Override
      public void mouseClicked(MouseEvent e) {

         int x = e.getX();
         int y = e.getY();
         int pX = (int) Math.floor(x / 200);
         int pY = (int) Math.floor(y / 200);
         int piecepressed = (pY * 3) + pX;
         boolean moveable = false;
         int toBeMoved = -1;
         for (int i = 0; i < 4; i++) {
            if (piecepressed == possmoves[i]) {
               moveable = true;
               toBeMoved = possmoves[i];
            }
         }
         if (moveable) {
            GameTile saved = pieces[openSpot];
            pieces[openSpot] = pieces[toBeMoved];
            pieces[toBeMoved] = saved;
            openSpot = toBeMoved;
            setOpenSpot();
            paint();
            checkCorrect();
         }
      }

      @Override
      public void mouseEntered(MouseEvent arg0) {

      }

      @Override
      public void mouseExited(MouseEvent arg0) {

      }

      @Override
      public void mousePressed(MouseEvent arg0) {

      }

      @Override
      public void mouseReleased(MouseEvent arg0) {

      }
   }
}

class GameTile extends JComponent {

   private int id;
   private int position;

   public GameTile(int id, int initpos) {
      setBorder(BorderFactory.createTitledBorder("" + id)); // !!
      setLayout(new BorderLayout()); // !! so the added JLabel will show
      if (id == 0) {
         this.id = id;
         this.position = initpos;
      } else {
         this.id = id;
         this.position = initpos;
         String label = Integer.toString(id);
         // !! setSize(200, 200);
         setOpaque(true); // !!
         setPreferredSize(new Dimension(200, 200)); // !!
         setBackground(new Color(0, 0, 0));
         // !! Label l = new Label(label, Label.CENTER);
         JLabel l = new JLabel(label, SwingConstants.CENTER); // !!
         this.add(l);
         l.setVisible(true);
      }
   }

   public void setPos(int position) {
      this.position = position;
   }

   public int getPos() {
      return position;
   }

   public int getID() {
      return id;
   }
}

可能还有很多话要说,但到目前为止我已经看到了这一切。