简体   繁体   中英

How to draw images on a JFrame

I have a array of images stored in a BufferedImage array. I want to display these images in a JFrame in a table like layout. How can I do so. Note: the number of images in the buffered image array is dynamic

1) use JList there you can put Icon (from BufferedImage ), Renderer returns JLabel/JComponent by default

2) all changes (remove, reordering, add) must be done on EDT , then better would be manage all these event from SwingWorker or Runnable#Thread

3) put these Objects to the DefaultListModel for JList

Create JPanel and set it's layout manager to a GridLayout with the number of rows and columns you want in the grid.

Then for each BufferedImage create a JLabel and set its icon to a new IconImage that contains the BufferedImage.

Finally add all the JLabels to the JPanel in the order you want and add the JPanel to the JFrame.

Here's an example from the top of my head; some pseudocode since I don't have images to work with:

JFrame frame = new JFrame("Title");

JPanel gridPanel = new JPanel();
//Layout as a grid with 4 rows and 3 columns
gridPanel.setLayout(new GridLayout(4,3)); 

//Pseudocode.
for(each BufferedImage in BufferedImageArray as img) {
    gridPanel.add(new JLabel(new ImageIcon(img));
}

frame.add(gridPanel);
//Other frame stuff you want here
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
frame.setVisible(true);

There's both topics to address in your question : draw some BufferedImage (which is done with Graphics ) and layout images.

You can do your own layout, but this can be tricky.

To let Swing do this for you, use a already defined layout (for instance GridLayout or FlowLayout ) and add as many JPanel as you have BufferedImage . Make sure your JPanel has a fixed dimension (cf. setPreferredSize() ).

Custom drawing is done with Graphics/Graphics2D API. On every JComponent , you can get the underlying Graphics instance to customize the rendering. Draw each BufferedImage in the graphics2D instance of every JPanel.

The last trick is to normalize images dimensions and don't forget respect ratios when calling Graphics.drawImage or crop images if you want to respect aspect ratio (which is what the users expect most of the time).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM