Basically, because JComponent has no UI delegate, it never paints its background (its paintComponent method essentially does nothing).
You could supply a UI delegate that performs the required actions, or simply use JPanel, for example:
![enter image description here]()
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
public class TestComponent {
public static void main(String[] args) {
new TestComponent();
}
public TestComponent() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBackground(Color.WHITE);
setBorder(new CompoundBorder(
BorderFactory.createEmptyBorder(0,10,10,10),
BorderFactory.createLineBorder(Color.RED)
));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}