44629

How to set repeating background image to a JPanel?

Question:

I want to set an image which repeats throughout the full width of the JPanel like we apply Background image to a DIV in CSS. How do I obtain that in swing for a JPanel?

Answer1:

Swing doesn't provide this functionality out of the box, so you will need to do it yourself...

The overall process is relative simple,

for (y = 0 to containerHeight) do for (x = 0 to containerWidth) do drawImage(tile, x, y)

The fun part is knowing where and how to apply it. Take a look at:

<ul><li><a href="http://docs.oracle.com/javase/tutorial/uiswing/painting/" rel="nofollow">Performing Custom Painting</a></li> <li><a href="http://docs.oracle.com/javase/tutorial/2d/" rel="nofollow">2D Graphics</a></li> <li><a href="http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html" rel="nofollow">Reading/Loading an Image</a></li> </ul>

For details about the various parts you will need to know.

<strong>Example</strong>

So using this as the tile...

<img alt="Tile" class="b-lazy" data-src="https://i.stack.imgur.com/mvua8.jpg" data-original="https://i.stack.imgur.com/mvua8.jpg" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

I was able to produce this...

<img alt="tiled" class="b-lazy" data-src="https://i.stack.imgur.com/3QzyD.png" data-original="https://i.stack.imgur.com/3QzyD.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class PaintTitle { public static void main(String[] args) { new PaintTitle(); } public PaintTitle() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private BufferedImage tile; public TestPane() { try { tile = ImageIO.read(getClass().getResource("/tile.jpg")); } catch (IOException ex) { ex.printStackTrace(); } } @Override public Dimension getPreferredSize() { return new Dimension(200, 200); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); int tileWidth = tile.getWidth(); int tileHeight = tile.getHeight(); for (int y = 0; y < getHeight(); y += tileHeight) { for (int x = 0; x < getWidth(); x += tileWidth) { g2d.drawImage(tile, x, y, this); } } g2d.dispose(); } } }

Recommend

  • Java Listen to Button and Keyboard click
  • How to add a scrollbar for long JComponents in a JPanel? How to center a JComponent?
  • How to create vertical TitledBorder in JPanel (javax swing)
  • Conditional in Rails partial depending on the context page?
  • Draw a bitmap from a control taller than the screen
  • Is there a way to detect whether or not there is an opened solution in VS 2012 from a vsix extension
  • File path validation in javascript
  • Skip a project while building a solution using msbuild 3.5
  • Exception in thread “AWT-EventQueue-0” java.lang.NoClassDefFoundError
  • Parse PFFile download order iOS
  • Can a MEF application built on .NET 4 import types built against .NET 3.5?
  • how do you read the ramda docs?
  • JMeter - using substring on a user variable
  • Thread Synchronization with IntentService
  • How to trigger a KeyPressed event for unit testing in JAVA
  • java drawing on JPanel with timer/delay
  • iPhone: 5 seconds video capture
  • wxWidgets: Detecting click event on custom controls
  • Exception in the iconization of JInternalFrame with DefaultDesktopManager
  • C# 4 and CLR Compatibility
  • Draw half infinite lines?
  • Android: How to correctly use NotifyDataSetChanged with SimpleExpandableListAdapter?
  • Hector: how to query parts of a Composite Type
  • Why are YouTube videos using 'youtube.com/v' not loading
  • Multiple producers single consumer locking schema
  • Python ImageIO Gif Set Delay Between Frames
  • Invalid Date on validation Date of js
  • Access Android Market through SSH tunnel
  • How integrated is Collada to OpenGL ES
  • Can you perform a UNION without a subquery in SQLAlchemy?
  • ImageMagick, replace semi-transparent white with opaque white
  • Cross-Platform Protobuf Serialization
  • Why winpcap requires both .lib and .dll to run?
  • Return words with double consecutive letters
  • How to format a variable of double type
  • Python: how to group similar lists together in a list of lists?
  • JTable with a ScrollPane misbehaving
  • coudnt use logback because of log4j
  • JaxB to read class hierarchy
  • Busy indicator not showing up in wpf window [duplicate]