package chap;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import javax.swing.*;
public class test8 extends JFrame {
public test8() {
JPanel northPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel westPanel = new JPanel();
JPanel eastPanel = new JPanel();
JPanel centerPanel = new JPanel();
JButton button1=new JButton("北方参战者");
JButton button2=new JButton("西方观察团");
JButton button3=new JButton("东方观察团");
JButton button4=new JButton("南方参与者");
northPanel.add(button1,BorderLayout.NORTH);
southPanel.add(button2,BorderLayout.WEST);
westPanel.add(button3,BorderLayout.EAST);
eastPanel.add(button4,BorderLayout.SOUTH);
centerPanel.setLayout(new GridLayout(12, 12));
for (int i = 0; i < 144; i++) {
JPanel tempPanel = new JPanel();
if ((i / 12) % 2 == 0) {
if (i % 2 == 0) {
tempPanel.setBackground(Color.WHITE);
} else {
tempPanel.setBackground(Color.BLACK);
}
} else {
if (i % 2 == 0) {
tempPanel.setBackground(Color.BLACK);
} else {
tempPanel.setBackground(Color.WHITE);
}
}
centerPanel.add(tempPanel);
}
getContentPane().add(northPanel, "North");
getContentPane().add(southPanel, "South");
getContentPane().add(westPanel, "West");
getContentPane().add(eastPanel, "East");
getContentPane().add(centerPanel, "Center");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new test8();
}
}
除了中间的设置面板,四周的不要使用面板,直接把按钮添加过去就可以。
代码如下
public class test8 extends JFrame {
public test8() {
// JPanel northPanel = new JPanel();
// JPanel southPanel = new JPanel();
// JPanel westPanel = new JPanel();
// JPanel eastPanel = new JPanel();
JPanel centerPanel = new JPanel();
JButton button1=new JButton("北方参战者");
JButton button2=new JButton("西方观察团");
JButton button3=new JButton("东方观察团");
JButton button4=new JButton("南方参与者");
getContentPane().add(button1,BorderLayout.NORTH);
getContentPane().add(button2,BorderLayout.WEST);
getContentPane().add(button3,BorderLayout.EAST);
getContentPane().add(button4,BorderLayout.SOUTH);
centerPanel.setLayout(new GridLayout(12, 12));
for (int i = 0; i < 144; i++) {
JPanel tempPanel = new JPanel();
if ((i / 12) % 2 == 0) {
if (i % 2 == 0) {
tempPanel.setBackground(Color.WHITE);
} else {
tempPanel.setBackground(Color.BLACK);
}
} else {
if (i % 2 == 0) {
tempPanel.setBackground(Color.BLACK);
} else {
tempPanel.setBackground(Color.WHITE);
}
}
centerPanel.add(tempPanel);
}
// getContentPane().add(northPanel, "North");
// getContentPane().add(southPanel, "South");
// getContentPane().add(westPanel, "West");
// getContentPane().add(eastPanel, "East");
getContentPane().add(centerPanel, "Center");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new test8();
}
}