import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class BasicFrame extends JPanel { Paint bgGradient = null; private int prevHeight = -1; private void setupBackgroundAndEffect() { // init the background gradient according to current height bgGradient = new GradientPaint(0, 0, Color.LIGHT_GRAY.brighter(), 0, getHeight(), Color.DARK_GRAY.brighter()); prevHeight = getHeight(); } protected void paintComponent(Graphics g) { if (bgGradient == null || getHeight() != prevHeight) { setupBackgroundAndEffect(); } ((Graphics2D) g).setPaint(bgGradient); g.fillRect(0, 0, getWidth(), getHeight()); } private static void createAndShowGUI() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(400, 300); BasicFrame component = new BasicFrame(); f.add(component); f.setVisible(true); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (InstantiationException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } Runnable doCreateAndShowGUI = new Runnable() { public void run() { createAndShowGUI(); } }; SwingUtilities.invokeLater(doCreateAndShowGUI); } }