因此,這裏是我的井字基本的模板:如何填寫兩個面板之間的邊界?
package myProjects;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.event.*;
public class SecondTickTacToe extends JFrame{
public JPanel mainPanel;
public static JPanel[][] panel = new JPanel[3][3];
public static void main(String[] args) {
new SecondTickTacToe();
}
public SecondTickTacToe(){
this.setSize(310, 400);
this.setTitle("Tic Tac Toe");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainPanel = new JPanel();
for(int row=0; row<3; row++){
for(int column=0; column<3; column++){
int top=0;
int bottom=0;
int left=0;
int right=0;
panel[row][column] = new JPanel();
panel[row][column].addMouseListener(new Mouse());
panel[row][column].setPreferredSize(new Dimension(90, 90));
panel[row][column].setBackground(Color.GREEN);
if(column==0||column==1)
right = 5;
if(column==1||column==2)
left = 5;
if(row==0||row==1)
bottom = 5;
if(row==1||row==2)
top = 5;
panel[row][column].setBorder(BorderFactory.createMatteBorder(top, left, bottom, right, Color.BLACK));
addItem(panel[row][column], row, column);
}
}
this.add(mainPanel);
this.setVisible(true);
}
private void addItem(JComponent c, int x, int y){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 100.0;
gbc.weighty = 100.0;
gbc.fill = GridBagConstraints.NONE;
mainPanel.add(c, gbc);
}
}
class Mouse extends MouseAdapter{
public void mousePressed(MouseEvent e){
if(e.getSource() instanceof JPanel)
((JPanel)e.getSource()).setBackground(Color.BLUE);
}
}
(你必須要運行的程序,看看我說的)
因此,這裏是我的問題: 是有什麼方法可以填充JPanels邊界之間的空間?我希望它變得堅實。使面板變大似乎並不奏效,而增大邊框尺寸似乎也無能爲力。有誰知道如何使這項工作? (我的最終目標是使邊框看起來像一個堅實的井字模板)
謝謝,我不知道默認的邊距:/我會修復你提到的一切,以及:) –