//成功了!
JPanel background = new JPanel();
background.setBackground(Color.BLACK);
background.setBounds(0,0,this.getSize().width,this.getSize().height);
add(background);`
//这个方法不起作用!为什么?而经典方法setBackground(Color.BLACK);
也有同样的问题
JPanel background = new JPanel()
{
@Override
public void setBackground(Color bg){
super.setBackground(Color.BLACK);
}
@Override
public void setBounds(int a, int b, int c, int d){
super.setBounds(0,0,this.getSize().width,this.getSize().height);
}
};
add(background);
您将遇到的明确问题将来自调用setBounds
方法。为您的面板调用setBackground
,并通过调用add
方法将其添加到JFrame
。默认情况下,JPanel
将被添加到JFrame
的中心,因为JFrame
的默认布局是BorderLayout
,它将完全适合而无需调用setBounds
。完全没有必要通过重写任何方法来使事情复杂化。
:
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JPanel panel = new JPanel();
panel.setBackground(Color.BLACK);
JFrame frame = new JFrame();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//frame.pack();
frame.setSize(400, 300);
frame.setVisible(true);
});
}
}
…
虽然您已经重写了方法,但还没有调用它们。