2015-11-26 25 views
0

嗯,我想開始學習Java,並使用NetBeans作爲我的GUI編輯器。我可以在調色板中看到如何添加按鈕,標籤,文本框等,但是如何添加可以使用NetBeans自定義寬度和長度的行?我知道我可以通過查看Java代碼的示例來實現這一點,但我希望能夠通過NetBeans插入,而不必插入代碼來創建3x3網格。我是使用NetBeans的新手,我查看了Google,但找不到任何東西。在此先感謝您的幫助。爲井字板創建自定義行NetBeans

回答

0

更好地使用代碼,但可以使用代碼 NetBeans。創建一個GridLayout,但給它的水平和垂直間隙屬性一個非零值。然後,如果使用該佈局的容器具有背景,並且將不透明組件放置到網格中,則會出現黑色線條。

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

@SuppressWarnings("serial") 
public class TicTacToePanel extends JPanel { 
    private static final int ROWS = 3; 
    private static final int MY_C = 240; 
    private static final Color BG = new Color(MY_C, MY_C, MY_C); 
    private static final int PTS = 60; 
    private static final Font FONT = new Font(Font.SANS_SERIF, Font.BOLD, PTS); 
    public static final Color X_COLOR = Color.BLUE; 
    public static final Color O_COLOR = Color.RED; 
    private JLabel[][] labels = new JLabel[ROWS][ROWS]; 
    private boolean xTurn = true; 

    public TicTacToePanel() { 
     setLayout(new GridLayout(ROWS, ROWS, 2, 2)); 
     setBackground(Color.black); 

     MyMouse myMouse = new MyMouse(); 
     for (int row = 0; row < labels.length; row++) { 
      for (int col = 0; col < labels[row].length; col++) { 
       JLabel label = new JLabel("  ", SwingConstants.CENTER); 
       label.setOpaque(true); 
       label.setBackground(BG); 
       label.setFont(FONT); 
       add(label); 
       label.addMouseListener(myMouse); 
      } 
     } 
    } 

    private class MyMouse extends MouseAdapter { 
     @Override // override mousePressed not mouseClicked 
     public void mousePressed(MouseEvent e) { 
      JLabel label = (JLabel) e.getSource(); 
      String text = label.getText().trim(); 
      if (!text.isEmpty()) { 
       return; 
      } 
      if (xTurn) { 
       label.setForeground(X_COLOR); 
       label.setText("X"); 
      } else { 
       label.setForeground(O_COLOR); 
       label.setText("O"); 
      } 

      // information to help check for win 
      int chosenX = -1; 
      int chosenY = -1; 
      for (int x = 0; x < labels.length; x++) { 
       for (int y = 0; y < labels[x].length; y++) { 
        if (labels[x][y] == label) { 
         chosenX = x; 
         chosenY = y; 
        } 
       } 
      } 
      // TODO: check for win here 
      xTurn = !xTurn; 
     } 
    } 

    private static void createAndShowGui() { 
     TicTacToePanel mainPanel = new TicTacToePanel(); 

     JFrame frame = new JFrame("Tic Tac Toe"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGui(); 
      } 
     }); 
    } 
}