import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; public class test_shu extends JPanel{ private JPanel center = new JPanel(new FlowLayout()); private testPanel[] t = new testPanel[5]; public test_shu() { init(); this.setPreferredSize(new Dimension(210, 500)); this.setLayout(new BorderLayout()); this.add(center,BorderLayout.CENTER); } private void init() { for(int i=0;i<5;i++){ t[i] = new testPanel(); center.add(t[i]); } } public static void main(String[] args) { JFrame f = new JFrame(); f.setSize(210, 500); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(new test_shu()); f.setLocation(500, 80); f.pack(); f.setVisible(true); } } class testPanel extends JPanel{ public testPanel() { this.setBorder(BorderFactory.createLineBorder(Color.red)); this.setSize(200, 30); this.setPreferredSize(new Dimension(200, 30)); this.setMaximumSize(new Dimension(200, 30)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.BLUE); g2d.fillRect(0, 0, this.getWidth(), this.getHeight()); } @Override public Dimension getPreferredSize() { return new Dimension(200, 30); } }
上面的代码显示5个testPanel类型的JPanel,结果如下,可是这5个JPnael之间都有空隙,而我的代码中并没有设置这些空隙,这是什么原因?怎么让它消失?小弟刚学还不太明白