I've got a JList whose elements consist of image files for which I'm creating thumbnails (in a background Thread). When these thumbnails become available, I'd like to force a repaint of just that item. However, I find that when I use the listModel's fireDataChanged method (see below), all the visible items in the list are repainted (using my custom ListCellRenderer).
public void updateElement(int index) {
frame.listModel.fireContentsChanged(frame.listModel, index, index);
}
Is there any way to cause ONLY the indexed item to be repainted?
Without some kind of runnable example which demonstrates your issue, it's impossible to make any concrete recommendations.
The following simple example makes use of a SwingWorker to change the value of the elements within the ListModel. To make it look more realistic, I've shuffled the List of indices and applied a short delay between each.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private DefaultListModel<String> model = new DefaultListModel<>();
public TestPane() {
setLayout(new BorderLayout());
add(new JScrollPane(new JList(model)));
JButton load = new JButton("Load");
add(load, BorderLayout.SOUTH);
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
load.setEnabled(false);
model.removeAllElements();
for (int index = 0; index < 100; index++) {
model.addElement("[" + index + "] Loading...");
}
LoadWorker worker = new LoadWorker(model);
worker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println(evt.getPropertyName() + " == " + evt.getNewValue());
if ("state".equals(evt.getPropertyName())) {
Object value = evt.getNewValue();
if (value instanceof SwingWorker.StateValue) {
SwingWorker.StateValue stateValue = (SwingWorker.StateValue) value;
if (stateValue == SwingWorker.StateValue.DONE) {
load.setEnabled(true);
}
}
}
}
});
worker.execute();
}
});
}
}
public class LoadResult {
private int index;
private String value;
public LoadResult(int index, String value) {
this.index = index;
this.value = value;
}
public int getIndex() {
return index;
}
public String getValue() {
return value;
}
}
public class LoadWorker extends SwingWorker<Void, LoadResult> {
private DefaultListModel model;
public LoadWorker(DefaultListModel model) {
this.model = model;
}
public DefaultListModel getModel() {
return model;
}
#Override
protected void process(List<LoadResult> chunks) {
for (LoadResult loadResult : chunks) {
model.set(loadResult.index, loadResult.value);
}
}
#Override
protected Void doInBackground() throws Exception {
int count = model.getSize();
List<Integer> indicies = new ArrayList<>(count);
for (int index = 0; index < count; index++) {
indicies.add(index);
}
Collections.shuffle(indicies);
for (int index : indicies) {
Thread.sleep(15);
publish(new LoadResult(index, "[" + index + "] Has been loaded"));
}
return null;
}
}
}
The above is a linear progression, meaning it's processing each item in sequence, one at a time.
Because image loading can take time and is CPU intensive process, you could make use of a ExecutorService and use a pool of threads to help spread the load.
For example:
Java - Multithreading with ImageIO
Make images fetched from server display in real time
Extracting images from a text file of 100 image urls using java
I find that when I use the listModel's fireDataChanged method (see below), all the visible items in the list are repainted
You should NOT invoke that method manually. The fireXXX(...) methods should only be invoked by the model itself.
You should be updating the model by using the:
model.set(...);
The set(...) method will then invoke the appropriate method to notify the JList to repaint the cell.
Here is my attempt at a simple Thumbnail app. It attempts to add performance improvements by:
loading the model with a default Icon so the list doesn't continually need to resize itself
Use a ExecutorService to take advantage of multiple processors
Using an ImageReader to read the file. The sub sampling property allows you to use fewer pixels when scaling the image.
Just change the class to point to a directory containing some .jpg files and give it a go:
ThumbnailApp:
import java.io.*;
import java.util.concurrent.*;
import java.awt.*;
//import java.awt.datatransfer.*;
import java.awt.event.*;
import javax.swing.*;
class ThumbnailApp
{
private DefaultListModel<Thumbnail> model = new DefaultListModel<Thumbnail>();
private JList<Thumbnail> list = new JList<Thumbnail>(model);
public ThumbnailApp()
{
}
public JPanel createContentPane()
{
JPanel cp = new JPanel( new BorderLayout() );
list.setCellRenderer( new ThumbnailRenderer<Thumbnail>() );
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
Icon empty = new EmptyIcon(160, 160);
Thumbnail prototype = new Thumbnail(new File("PortugalSpain-000.JPG"), empty);
list.setPrototypeCellValue( prototype );
cp.add(new JScrollPane( list ), BorderLayout.CENTER);
return cp;
}
public void loadImages(File directory)
{
new Thread( () -> createThumbnails(directory) ).start();
}
private void createThumbnails(File directory)
{
try
{
File[] files = directory.listFiles((d, f) -> {return f.endsWith(".JPG");});
int processors = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool( processors - 2 );
long start = System.currentTimeMillis();
for (File file: files)
{
Thumbnail thumbnail = new Thumbnail(file, null);
model.addElement( thumbnail );
// new ThumbnailWorker(file, model, model.size() - 1).execute();
service.submit( new ThumbnailWorker(file, model, model.size() - 1) );
}
long duration = System.currentTimeMillis() - start;
System.out.println(duration);
service.shutdown();
}
catch(Exception e) { e.printStackTrace(); }
}
private static void createAndShowGUI()
{
ThumbnailApp app = new ThumbnailApp();
JFrame frame = new JFrame("ListDrop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane( app.createContentPane() );
frame.setSize(1600, 900);
frame.setVisible(true);
// File directory = new File("C:/Users/netro/Pictures/TravelSun/2019_01_Cuba");
File directory = new File("C:/Users/netro/Pictures/TravelAdventures/2018_PortugalSpain");
app.loadImages( directory );
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(() -> createAndShowGUI());
}
}
ThumbnailWorker:
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.Iterator;
//import java.util.concurrent.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import javax.swing.*;
class ThumbnailWorker extends SwingWorker<Image, Void>
{
private File file;
private DefaultListModel<Thumbnail> model;
private int index;
public ThumbnailWorker(File file, DefaultListModel<Thumbnail> model, int index)
{
this.file = file;
this.model = model;
this.index = index;
}
#Override
protected Image doInBackground() throws IOException
{
// Image image = ImageIO.read( file );
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = readers.next();
ImageReadParam irp = reader.getDefaultReadParam();
// irp.setSourceSubsampling(10, 10, 0, 0);
irp.setSourceSubsampling(5, 5, 0, 0);
ImageInputStream stream = new FileImageInputStream( file );
reader.setInput(stream);
Image image = reader.read(0, irp);
int width = 160;
int height = 90;
if (image.getHeight(null) > image.getWidth(null))
{
width = 90;
height = 160;
}
BufferedImage scaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = scaled.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
image = null;
return scaled;
}
#Override
protected void done()
{
try
{
ImageIcon icon = new ImageIcon( get() );
Thumbnail thumbnail = model.get( index );
thumbnail.setIcon( icon );
model.set(index, thumbnail);
System.out.println("finished: " + file);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
ThumbnailRenderer
import java.awt.Component;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ThumbnailRenderer<E> extends JLabel implements ListCellRenderer<E>
{
public ThumbnailRenderer()
{
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);
setHorizontalTextPosition( JLabel.CENTER );
setVerticalTextPosition( JLabel.BOTTOM );
setBorder( new EmptyBorder(4, 4, 4, 4) );
}
/*
* Display the Thumbnail Icon and file name.
*/
public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus)
{
if (isSelected)
{
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else
{
setBackground(list.getBackground());
setForeground(list.getForeground());
}
//Set the icon and filename
Thumbnail thumbnail = (Thumbnail)value;
setIcon( thumbnail.getIcon() );
setText( thumbnail.getFileName() );
return this;
}
}
Thumbnail:
import java.io.File;
import javax.swing.Icon;
public class Thumbnail
{
private File file;
private Icon icon;
public Thumbnail(File file, Icon icon)
{
this.file = file;
this.icon = icon;
}
public Icon getIcon()
{
return icon;
}
public void setIcon(Icon icon)
{
this.icon = icon;
}
public String getFileName()
{
return file.getName();
}
}
I tested on a directory with 302 images. Using the ExecutorService got the load time down from 2:31 to 0:35.
Related
I'm a Windows user, and I have developed a small software to calculate few parameter based on some inputs. The GUI in Windows is displayed as expected, but in Mac OS it's different. Please let me know how to correct it. The code for the same is.
package home;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import java.awt.Component;
import java.awt.ComponentOrientation;
/**
* Home Page for the application.
* #author Harshit Rathore
*
*/
public class Home_Main {
private JFrame f;
private JXTabbedPane tabbedpane;
private ImageIcon icon_view, icon_analysis, icon_algo, icon_info, icon_sche_gen;
Schedule_Generation schedule_gen;
View_JPanel2D view2d;
View_JPanel3D view3d;
MapJPanel mapPanel;
Home_Main() {
f = new JFrame();
f.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
f.setTitle("Anti-Accidental Algorithm");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tabbedpane = new JXTabbedPane(JTabbedPane.LEFT);
AbstractTabRenderer renderer = (AbstractTabRenderer)tabbedpane.getTabRenderer();
renderer.setPrototypeText("This text is a prototype->");
renderer.setHorizontalTextAlignment(SwingConstants.LEADING);
icon_view = new ImageIcon(this.getClass().getResource("/view_icon.png"));
icon_analysis = new ImageIcon(this.getClass().getResource("/analysis_icon.png"));
icon_algo = new ImageIcon(this.getClass().getResource("/algo_icon.png"));
icon_info = new ImageIcon(this.getClass().getResource("/info_icon.png"));
icon_sche_gen = new ImageIcon(this.getClass().getResource("/schedule_icon.png"));
mapPanel = new home.MapJPanel();
view2d = new home.View_JPanel2D();
view3d = new home.View_JPanel3D();
schedule_gen = new home.Schedule_Generation(view2d, view3d, mapPanel);
tabbedpane.addTab("Algorithm", icon_algo, new home.Algo_JPanel());
tabbedpane.addTab("<html>Schedule<br>Generation</html>", icon_sche_gen, schedule_gen);
tabbedpane.addTab("<html>View Data 2D<br>(Azimuth, Elevation)</html>", icon_view, view2d);
tabbedpane.addTab("<html>View Data 3D<br>(Azimuth, Elevation, Tilt)</html>", icon_view, view3d);
tabbedpane.addTab("MapPanel", icon_info, mapPanel);
tabbedpane.addTab("<html>Windload<br>Torque</html>", icon_analysis, new home.WindloadTorque());
f.getContentPane().add(tabbedpane);
f.setMinimumSize(new Dimension(1100, 800));
f.setSize(1600, 800);
f.setVisible(true);
f.setEnabled(true);
}
/**
* The main function of the software.
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Home_Main();
}
// custom tabbedpane
class JXTabbedPane extends JTabbedPane {
/**
*
*/
private static final long serialVersionUID = 1L;
private ITabRenderer tabRenderer = new DefaultTabRenderer();
public JXTabbedPane() {
super();
}
public JXTabbedPane(int tabPlacement) {
super(tabPlacement);
}
public JXTabbedPane(int tabPlacement, int tabLayoutPolicy) {
super(tabPlacement, tabLayoutPolicy);
}
public ITabRenderer getTabRenderer() {
return tabRenderer;
}
public void setTabRenderer(ITabRenderer tabRenderer) {
this.tabRenderer = tabRenderer;
}
#Override
public void addTab(String title, Component component) {
this.addTab(title, null, component, null);
}
#Override
public void addTab(String title, Icon icon, Component component) {
this.addTab(title, icon, component, null);
}
#Override
public void addTab(String title, Icon icon, Component component, String tip) {
super.addTab(title, icon, component, tip);
int tabIndex = getTabCount() - 1;
Component tab = tabRenderer.getTabRendererComponent(this, title, icon, tabIndex);
super.setTabComponentAt(tabIndex, tab);
}
}
interface ITabRenderer {
public Component getTabRendererComponent(JTabbedPane tabbedPane, String text, Icon icon, int tabIndex);
}
abstract class AbstractTabRenderer implements ITabRenderer {
private String prototypeText = "";
private Icon prototypeIcon = new ImageIcon(this.getClass().getResource("/view_icon.png"));
private int horizontalTextAlignment = SwingConstants.CENTER;
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public AbstractTabRenderer() {
super();
}
public void setPrototypeText(String text) {
String oldText = this.prototypeText;
this.prototypeText = text;
firePropertyChange("prototypeText", oldText, text);
}
public String getPrototypeText() {
return prototypeText;
}
public Icon getPrototypeIcon() {
return prototypeIcon;
}
public void setPrototypeIcon(Icon icon) {
Icon oldIcon = this.prototypeIcon;
this.prototypeIcon = icon;
firePropertyChange("prototypeIcon", oldIcon, icon);
}
public int getHorizontalTextAlignment() {
return horizontalTextAlignment;
}
public void setHorizontalTextAlignment(int horizontalTextAlignment) {
this.horizontalTextAlignment = horizontalTextAlignment;
}
public PropertyChangeListener[] getPropertyChangeListeners() {
return propertyChangeSupport.getPropertyChangeListeners();
}
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
return propertyChangeSupport.getPropertyChangeListeners(propertyName);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
}
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
PropertyChangeListener[] listeners = getPropertyChangeListeners();
for (int i = listeners.length - 1; i >= 0; i--) {
listeners[i].propertyChange(new PropertyChangeEvent(this, propertyName, oldValue, newValue));
}
}
}
class DefaultTabRenderer extends AbstractTabRenderer implements PropertyChangeListener {
private Component prototypeComponent;
public DefaultTabRenderer() {
super();
prototypeComponent = generateRendererComponent(getPrototypeText(), getPrototypeIcon(),
getHorizontalTextAlignment());
addPropertyChangeListener(this);
}
private Component generateRendererComponent(String text, Icon icon, int horizontalTabTextAlignmen) {
JPanel rendererComponent = new JPanel(new GridBagLayout());
rendererComponent.setOpaque(false);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(2, 4, 2, 4);
c.fill = GridBagConstraints.HORIZONTAL;
rendererComponent.add(new JLabel(icon), c);
c.gridx = 1;
c.weightx = 1;
rendererComponent.add(new JLabel(text, horizontalTabTextAlignmen), c);
return rendererComponent;
}
#Override
public Component getTabRendererComponent(JTabbedPane tabbedPane, String text, Icon icon, int tabIndex) {
Component rendererComponent = generateRendererComponent(text, icon, getHorizontalTextAlignment());
int prototypeWidth = prototypeComponent.getPreferredSize().width;
int prototypeHeight = prototypeComponent.getPreferredSize().height;
rendererComponent.setPreferredSize(new Dimension(prototypeWidth, prototypeHeight));
return rendererComponent;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("prototypeText".equals(propertyName) || "prototypeIcon".equals(propertyName)) {
this.prototypeComponent = generateRendererComponent(getPrototypeText(), getPrototypeIcon(),
getHorizontalTextAlignment());
}
}
}
}
The outputs are-
First one is from Windows (desired one) second one is from Mac OS(need modification).
Thank You
The reason for the buttons looking different is because of Java Swing's LAF (Look & Feel).
The Look and Feel is like the master “theme” for your Swing Application where it defines specific rules on how certain components should look, etc…
Java Swing on Windows looks different from on Unix & OSX is because there is a different provider for the LAF (known as LAF "metal")
You thus can pack a LAF library into your program, and you can find many here.
To call a theme to be used, you must place this before any GUI/Swing events are called (AKA repaints, component inits, etc.):
try {
UIManager.setLookAndFeel(myThemeLAF.class.getName());
} catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
Alternatively, you could override the individual paintComponent(Graphics g) methods.
This can be achieved either through anonymous classes or just having a class extend that object and override it from there:
#1 Anonymous Inner Classes
JPanel myPanel = new JPanel() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//... draw stuffs
}
};
#2 Extending existing objects
public class MyPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// paint stuffs
}
}
how to create jcomboBox with two /multiple columns in the drop down let but when we select only one selected value show in Jcombobox
please give me any solution for this .
You might be able to use JList#setLayoutOrientation(JList.VERTICAL_WRAP):
import java.awt.*;
import javax.accessibility.Accessible;
import javax.swing.*;
import javax.swing.plaf.basic.ComboPopup;
public class TwoColumnsDropdownTest {
private Component makeUI() {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
model.addElement("111");
model.addElement("2222");
model.addElement("3");
model.addElement("44444");
model.addElement("55555");
model.addElement("66");
model.addElement("777");
model.addElement("8");
model.addElement("9999");
int rowCount = (model.getSize() + 1) / 2;
JComboBox<String> combo = new JComboBox<String>(model) {
#Override public Dimension getPreferredSize() {
Insets i = getInsets();
Dimension d = super.getPreferredSize();
int w = Math.max(100, d.width);
int h = d.height;
int buttonWidth = 20; // ???
return new Dimension(buttonWidth + w + i.left + i.right, h + i.top + i.bottom);
}
#Override public void updateUI() {
super.updateUI();
setMaximumRowCount(rowCount);
setPrototypeDisplayValue("12345");
Accessible o = getAccessibleContext().getAccessibleChild(0);
if (o instanceof ComboPopup) {
JList<?> list = ((ComboPopup) o).getList();
list.setLayoutOrientation(JList.VERTICAL_WRAP);
list.setVisibleRowCount(rowCount);
list.setFixedCellWidth((getPreferredSize().width - 2) / 2);
}
}
};
JPanel p = new JPanel();
p.add(combo);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new TwoColumnsDropdownTest().makeUI());
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
You need to do a few things.
By default, what is displayed in the JComboBox, as the selected item, is the value returned by method toString of the items in the ComboBoxModel. Based on your comment I wrote an Item class and overrode the toString method.
In order to display something different in the drop-down list, you need a custom ListCellRenderer.
In order for the drop-down list to display the entire details of each item, the drop-down list needs to be wider than the JComboBox. I used code from the following SO question to achieve that:
How can I change the width of a JComboBox dropdown list?
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.math.BigDecimal;
import java.text.NumberFormat;
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicComboPopup;
public class MultiColumnCombo implements PopupMenuListener {
private JComboBox<Item> combo;
public void popupMenuCanceled(PopupMenuEvent event) {
// Do nothing.
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
// Do nothing.
}
public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
AccessibleContext comboAccessibleContext = combo.getAccessibleContext();
int comboAccessibleChildrenCount = comboAccessibleContext.getAccessibleChildrenCount();
if (comboAccessibleChildrenCount > 0) {
Accessible comboAccessibleChild0 = comboAccessibleContext.getAccessibleChild(0);
if (comboAccessibleChild0 instanceof BasicComboPopup) {
EventQueue.invokeLater(() -> {
BasicComboPopup comboPopup = (BasicComboPopup) comboAccessibleChild0;
JScrollPane scrollPane = (JScrollPane) comboPopup.getComponent(0);
Dimension d = setCurrentDimension(scrollPane.getPreferredSize());
scrollPane.setPreferredSize(d);
scrollPane.setMaximumSize(d);
scrollPane.setMinimumSize(d);
scrollPane.setSize(d);
Point location = combo.getLocationOnScreen();
int height = combo.getPreferredSize().height;
comboPopup.setLocation(location.x, location.y + height - 1);
comboPopup.setLocation(location.x, location.y + height);
});
}
}
}
private void createAndDisplayGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createCombo());
frame.setSize(450, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createCombo() {
JPanel panel = new JPanel();
Item[] items = new Item[]{new Item("A", "Item A", new BigDecimal(1.99d), new BigDecimal(2.99d)),
new Item("B", "Item B", new BigDecimal(7.5d), new BigDecimal(9.0d)),
new Item("C", "Item C", new BigDecimal(0.25d), new BigDecimal(3.15d))};
combo = new JComboBox<>(items);
AccessibleContext comboAccessibleContext = combo.getAccessibleContext();
int comboAccessibleChildrenCount = comboAccessibleContext.getAccessibleChildrenCount();
if (comboAccessibleChildrenCount > 0) {
Accessible comboAccessibleChild0 = comboAccessibleContext.getAccessibleChild(0);
if (comboAccessibleChild0 instanceof BasicComboPopup) {
BasicComboPopup comboPopup = (BasicComboPopup) comboAccessibleChild0;
comboPopup.getList().setCellRenderer(new MultiColumnRenderer());
}
}
combo.addPopupMenuListener(this);
panel.add(combo);
return panel;
}
private Dimension setCurrentDimension(Dimension dim) {
Dimension d = new Dimension(dim);
d.width = 120;
return d;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new MultiColumnCombo().createAndDisplayGui());
}
}
class Item {
private String code;
private String name;
private BigDecimal price;
private BigDecimal salePrice;
public Item(String code, String name, BigDecimal price, BigDecimal salePrice) {
this.code = code;
this.name = name;
this.price = price;
this.salePrice = salePrice;
}
public String displayString() {
return String.format("%s %s %s %s",
code,
name,
NumberFormat.getCurrencyInstance().format(price),
NumberFormat.getCurrencyInstance().format(salePrice));
}
public String toString() {
return name;
}
}
class MultiColumnRenderer implements ListCellRenderer<Object> {
/** Component returned by method {#link #getListCellRendererComponent}. */
private JLabel cmpt;
public MultiColumnRenderer() {
cmpt = new JLabel();
cmpt.setOpaque(true);
cmpt.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
}
public Component getListCellRendererComponent(JList<? extends Object> list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
String text;
if (value == null) {
text = "";
}
else {
if (value instanceof Item) {
text = ((Item) value).displayString();
}
else {
text = value.toString();
}
}
cmpt.setText(text);
if (isSelected) {
cmpt.setBackground(list.getSelectionBackground());
cmpt.setForeground(list.getSelectionForeground());
}
else {
cmpt.setBackground(list.getBackground());
cmpt.setForeground(list.getForeground());
}
cmpt.setFont(list.getFont());
return cmpt;
}
}
In my java application, my objective is to display or output an image using MVC architecture. My java application is comprised of an imagecontroller(main), imageview, and image model. I am currently able to select an image, the compiler acknowledges where the image has been selected from in the c: drive however it does not output or display the image. Here is a copy of my code below:
package imagecontroller;
import javax.swing.SwingUtilities;
import java.io.File;
public class ImageController {
private final ImageModel model;
private final ImageView view;
public ImageController () {
this.view = new ImageView(this);
this.model = new ImageModel(this.view);
public static void launch () {
new ImageController();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ImageController::launch);
}
}
package imagecontroller;
import java.awt.Dimension;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;
public class ImageView extends JFrame{
private final ImageController controller;
public ImageView(ImageController controller) {
this.controller = controller;
JFileChooser Chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & PNG Images", "jpg", "png");
Chooser.addChoosableFileFilter(filter);
Chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
Chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result
Chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
Chooser.setAcceptAllFileFilterUsed(true);
File selectedFile = Chooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle("ImageAnnotator");
frame.setVisible(true);
frame.setSize(new Dimension (500,500));
}
}
}
package imagecontroller;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
public class ImageModel extends JComponent {
private final ImageView view;
private BufferedImage image;
public ImageModel(ImageView view) {
this.view = view;
}
public void CustomComponent (File png) {
BufferedImage image = null;
setPreferredSize(new Dimension(400, 400));
try {
this.image = ImageIO.read(new File("640px-Pleiades_large.png"));
} catch (IOException x) {
JOptionPane.showMessageDialog(null, "Not an ImageFile, Please Select an Image");
}
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g = g.create();
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
int margin = 20;
int w = (getWidth() - (2 * margin + 2)) / 2;
int h = this.image.getHeight() * w / this.image.getWidth();
g.drawImage(image, h, h, WIDTH, HEIGHT, view);
}
}
The reason that the MVC pattern is called the MVC pattern is that the name suggests the order. In other words, create the model, then the view, then the controllers.
Here's an image display GUI I put together.
So, let's start with the model. For an image viewer GUI, the model is pretty simple.
public class ImageDisplayModel {
private BufferedImage image;
private File file;
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
The ImageDisplayModel class is a plain Java class that holds a BufferedImage and a File path. By saving the File path, the next time the user selects an image, the directory will be set to be the same as the last image.
The ImageDisplayModel class is an ordinary getter / setter class.
The next step is to create the view.
public class ImageDisplay implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ImageDisplay());
}
private ImageDisplayModel model;
private ImagePanel imagePanel;
private JFrame frame;
public ImageDisplay() {
this.model = new ImageDisplayModel();
}
#Override
public void run() {
frame = new JFrame("Image Display");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenuBar());
imagePanel = new ImagePanel(model);
frame.add(imagePanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JMenuBar createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenuItem openitem = new JMenuItem("Open...");
openitem.addActionListener(new OpenFileListener(this, model));
filemenu.add(openitem);
menubar.add(filemenu);
return menubar;
}
public void updateImagePanel(int width, int height) {
imagePanel.setPreferredSize(width, height);
imagePanel.repaint();
frame.pack();
}
public JFrame getFrame() {
return frame;
}
}
We start the application with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
The view constructor instantiates the application model.
The JFrame code is in the run method.
The JMenuBar method allows us to select multiple images, one after the other.
The getFrame method allows the eventual controller class to access the JFrame instance. The updateImagePanel method allows the eventual controller class to update the image panel.
Next, we create the DrawingPanel class.
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private ImageDisplayModel model;
public ImagePanel(ImageDisplayModel model) {
this.model = model;
this.setPreferredSize(649, 480);
}
public void setPreferredSize(int width, int height) {
this.setPreferredSize(new Dimension(width, height));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage image = model.getImage();
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
}
Simple and straightforward. We draw the BufferedImage if one exists. We also adjust the size of the JPanel so that the image fits.
The only information that the DrawingPanel class needs is the model class. The drawing panel will draw the image. Period.
Finally, we create the controller class.
public class OpenFileListener implements ActionListener {
private ImageDisplay frame;
private ImageDisplayModel model;
public OpenFileListener(ImageDisplay frame, ImageDisplayModel model) {
this.frame = frame;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & PNG Images", "jpg", "png");
chooser.addChoosableFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
File file = model.getFile();
if (file != null) {
chooser.setCurrentDirectory(file);
}
int result = chooser.showOpenDialog(frame.getFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
model.setFile(selectedFile);
BufferedImage image;
try {
image = ImageIO.read(selectedFile);
model.setImage(image);
frame.updateImagePanel(image.getWidth(),
image.getHeight());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The controller class updates the model information and instructs the view to repaint itself. The controller isn't concerned with the view internals. All the controller needs to know is that the view can update.
Finally, here's the complete runnable code. I made the classes inner classes so I could post this code as one block.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
public class ImageDisplay implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ImageDisplay());
}
private ImageDisplayModel model;
private ImagePanel imagePanel;
private JFrame frame;
public ImageDisplay() {
this.model = new ImageDisplayModel();
}
#Override
public void run() {
frame = new JFrame("Image Display");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenuBar());
imagePanel = new ImagePanel(model);
frame.add(imagePanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JMenuBar createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenuItem openitem = new JMenuItem("Open...");
openitem.addActionListener(new OpenFileListener(this, model));
filemenu.add(openitem);
menubar.add(filemenu);
return menubar;
}
public void updateImagePanel(int width, int height) {
imagePanel.setPreferredSize(width, height);
imagePanel.repaint();
frame.pack();
}
public JFrame getFrame() {
return frame;
}
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private ImageDisplayModel model;
public ImagePanel(ImageDisplayModel model) {
this.model = model;
this.setPreferredSize(649, 480);
}
public void setPreferredSize(int width, int height) {
this.setPreferredSize(new Dimension(width, height));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage image = model.getImage();
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
}
public class OpenFileListener implements ActionListener {
private ImageDisplay frame;
private ImageDisplayModel model;
public OpenFileListener(ImageDisplay frame, ImageDisplayModel model) {
this.frame = frame;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & PNG Images", "jpg", "png");
chooser.addChoosableFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
File file = model.getFile();
if (file != null) {
chooser.setCurrentDirectory(file);
}
int result = chooser.showOpenDialog(frame.getFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
model.setFile(selectedFile);
BufferedImage image;
try {
image = ImageIO.read(selectedFile);
model.setImage(image);
frame.updateImagePanel(image.getWidth(),
image.getHeight());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ImageDisplayModel {
private BufferedImage image;
private File file;
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
}
I really found this interesting and thought to explore it a little more. Taking pointers from The MVC pattern and Swing (which I suggest you read especially the accepted answer) lets try have a go.
Explanation:
Brief Summary of the code to follow (based off of the above link)
The LoginView. The view is simply your UI components, with getter methods for any components needed by the LoginController as well as implementing a PropertyChangeListener which is used by the view to receive PropertyChangeEvents which could be fired by our LoginController or LoginModel.
The LoginController The controller has access to both the view and the model. The controller sets up the necessary events on the views components and reacts to them by validating input from the view and then asks the model to do its job and potentially that will change its state. The controller takes your views actions and interprets them. If you click on a button, it's the controller's job to figure out what that means and how the model should be manipulated based on that action.
The controller may also ask the view to change it does this by subscribing the view (which implements PropertyChangeListener) to its SwingPropertyChangeSupport. When the controller receives an action from the view, in this case the Login button pressed it validates inputs from the view and fires the necessary validation errors (if any). It then calls the model to do the actual validation.
The LoginModel The controller calls methods on the model which intern notifies the view when its state has changed. When something changes in the model, based either on some action you took (like clicking a button) the model notifies the view that its state has changed through the same mechanism as the controller.
The view can also ask the model for state. The view gets the state it displays directly from the model. For instance, if we pass in a model instance to our view which already has authenticated set to true, you will immediately receive the message to say you are logged in (this has not been demonstrated here, but would entail passing the model into the views constructor and after initializing the initView() doing something like onAuthenticatedPropertyChange(model.isAuthenticated())).
Some extra information is both controller and model implement the observer pattern (as in the view observes changes to the controller and models in order to react to them)
The controller also does all model execution on a background thread via a SwingWorker, and all property change listeners are fired back on the EDT
Here is the code which demonstrates the above:
TestApp.java:
import javax.swing.SwingUtilities;
public class TestApp {
public TestApp() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGUI() {
LoginModel model = new LoginModel();
LoginView view = new LoginView();
LoginController controller = new LoginController(view, model);
}
}
LoginView.java:
import java.awt.Color;
import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class LoginView implements PropertyChangeListener {
private JFrame frame;
private JPanel loginPanel;
private JTextField usernameTextField;
private JTextField passwordTextField;
private JLabel errorLabel;
private JButton loginButton;
public LoginView() {
initView();
}
private void initView() {
frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginPanel = createLoginPanel();
frame.add(loginPanel);
frame.pack();
frame.setVisible(true);
}
private JPanel createLoginPanel() {
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JLabel usernameLabel = new JLabel("Username:");
usernameLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
usernameTextField = new JTextField();
usernameTextField.setAlignmentX(Component.CENTER_ALIGNMENT);
usernameTextField.setColumns(20);
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
passwordTextField = new JTextField();
passwordTextField.setAlignmentX(Component.CENTER_ALIGNMENT);
passwordTextField.setColumns(20);
loginButton = new JButton("Login");
loginButton.setAlignmentX(Component.CENTER_ALIGNMENT);
errorLabel = new JLabel();
errorLabel.setForeground(Color.RED);
errorLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
errorLabel.setVisible(false);
panel.add(usernameLabel);
panel.add(usernameTextField);
panel.add(passwordLabel);
panel.add(passwordTextField);
panel.add(errorLabel);
panel.add(loginButton);
return panel;
}
public JButton getLoginButton() {
return loginButton;
}
public JTextField getUsernameTextField() {
return usernameTextField;
}
public JTextField getPasswordTextField() {
return passwordTextField;
}
public JFrame getFrame() {
return frame;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
Object newValue = evt.getNewValue();
switch (propertyName) {
case "authenticated":
// authentication has finished lets do something
onAuthenticatedPropertyChange((Boolean) newValue);
break;
case "authenticating":
// lets disable the UI as we authenticate
errorLabel.setVisible(false);
disableLoginPanelComponents(true);
break;
case "usernameInvalid":
showError((String) newValue);
break;
case "passwordInvalid":
showError((String) newValue);
break;
}
}
private void onAuthenticatedPropertyChange(Boolean authenticated) {
if (authenticated == true) {
errorLabel.setVisible(false);
JOptionPane.showMessageDialog(frame, "You are in!");
} else {
showError("Invalid username or password!");
}
// re-enable components after authentication regadless of fail or pass
disableLoginPanelComponents(false);
}
private void showError(String error) {
errorLabel.setText(error);
errorLabel.setVisible(true);
}
private void disableLoginPanelComponents(boolean disable) {
for (int i = 0; i < loginPanel.getComponentCount(); i++) {
Component component = (Component) loginPanel.getComponent(i);
if (component instanceof JTextField || component instanceof JButton) {
((JComponent) loginPanel.getComponent(i)).setEnabled(!disable);
}
}
}
}
LoginController:
import java.awt.event.ActionEvent;
import javax.swing.SwingWorker;
import javax.swing.event.SwingPropertyChangeSupport;
public class LoginController {
private final SwingPropertyChangeSupport propertyChangeSupport;
private final LoginView view;
private final LoginModel model;
public LoginController(LoginView view, LoginModel model) {
this.view = view;
this.model = model;
propertyChangeSupport = new SwingPropertyChangeSupport(this, true);
initController();
}
private void initController() {
// make the view a listener of both the model and controller as both can send events which the view must react too
model.addPropertyChangeListener(view);
propertyChangeSupport.addPropertyChangeListener(view);
view.getLoginButton().addActionListener((ActionEvent e) -> {
// lets do some basic validation of username and password fields
String username = view.getUsernameTextField().getText();
String password = view.getPasswordTextField().getText();
// validate user input before sending it to the model (this is the contorllers job - besdoes business rules i..e username doesnt exist etc)
if (username.isEmpty()) {
propertyChangeSupport.firePropertyChange("usernameInvalid", null, "Username cannot be empty!");
return;
}
if (password.isEmpty()) {
propertyChangeSupport.firePropertyChange("passwordInvalid", null, "Password cannot be empty!");
return;
}
// call the model to login on a background thread as the model may query the db or hit an API etc
new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
model.login(username, password);
return null;
}
}.execute();
});
}
}
LoginModel.java:
import java.beans.PropertyChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.SwingPropertyChangeSupport;
public class LoginModel {
private final SwingPropertyChangeSupport propertyChangeSupport;
private boolean authenticated;
public LoginModel() {
propertyChangeSupport = new SwingPropertyChangeSupport(this, true); // we pass in true to noifty observers on the Event Dispatch Thread
}
public void login(String username, String password) {
propertyChangeSupport.firePropertyChange("authenticating", null, true);
// lets simulate query a database or something for 3 seconds
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
Logger.getLogger(LoginModel.class.getName()).log(Level.SEVERE, null, ex);
}
authenticated = username.equals("admin") && password.equals("password");
propertyChangeSupport.firePropertyChange("authenticated", null, authenticated);
}
public void addPropertyChangeListener(PropertyChangeListener prop) {
propertyChangeSupport.addPropertyChangeListener(prop);
}
public boolean isAuthenticated() {
return authenticated;
}
}
The above is generic and doesn't directly answer YOUR question but gives you an example of an MVC pattern in Swing.
Update:
Here is an example specific to your issue
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.SwingPropertyChangeSupport;
import javax.swing.filechooser.FileNameExtensionFilter;
public class TestApp {
public TestApp() {
createAndShowGUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGUI() {
DisplayImageModel model = new DisplayImageModel();
DisplayImageView view = new DisplayImageView();
DisplayImageController controller = new DisplayImageController(view, model);
}
class DisplayImageView implements PropertyChangeListener {
private JFrame frame;
private ImagePanel imagePanel;
private JLabel imageLabel;
private JButton pickImageButton;
public DisplayImageView() {
initView();
}
private void initView() {
frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = createImagePanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private JPanel createImagePanel() {
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
pickImageButton = new JButton("Pick an image");
pickImageButton.setAlignmentX(Component.CENTER_ALIGNMENT);
imagePanel = new ImagePanel();
imagePanel.getPanel().setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(imagePanel.getPanel());
panel.add(pickImageButton);
return panel;
}
public JButton getPickAnImageButton() {
return pickImageButton;
}
public JLabel getImageLabel() {
return imageLabel;
}
public JFrame getFrame() {
return frame;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
Object newValue = evt.getNewValue();
switch (propertyName) {
case "image":
onImagePropertyChange((BufferedImage) newValue);
break;
}
}
private void onImagePropertyChange(BufferedImage image) {
imagePanel.setImage(image);
frame.pack();
}
}
class DisplayImageModel {
private final SwingPropertyChangeSupport propertyChangeSupport;
private BufferedImage image;
public DisplayImageModel() {
propertyChangeSupport = new SwingPropertyChangeSupport(this, true); // we pass in true to noifty observers on the Event Dispatch Thread
}
public void setImage(BufferedImage image) {
this.image = image;
propertyChangeSupport.firePropertyChange("image", null, image);
}
public void addPropertyChangeListener(PropertyChangeListener prop) {
propertyChangeSupport.addPropertyChangeListener(prop);
}
public BufferedImage getImage() {
return image;
}
}
class DisplayImageController {
private final SwingPropertyChangeSupport propertyChangeSupport;
private final DisplayImageView view;
private final DisplayImageModel model;
public DisplayImageController(DisplayImageView view, DisplayImageModel model) {
this.view = view;
this.model = model;
propertyChangeSupport = new SwingPropertyChangeSupport(this, true);
initController();
}
private void initController() {
// make the view a listener of both the model and controller as both can send events which the view must react too
model.addPropertyChangeListener(view);
propertyChangeSupport.addPropertyChangeListener(view);
view.getPickAnImageButton().addActionListener((ActionEvent e) -> {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & PNG Images", "jpg", "png");
chooser.addChoosableFileFilter(filter);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = chooser.showOpenDialog(view.getFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
BufferedImage image;
try {
image = ImageIO.read(selectedFile);
model.setImage(image);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}
class ImagePanel {
private final JPanel panel;
private BufferedImage image;
public ImagePanel() {
this.panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (image != null) {
return new Dimension(image.getWidth(), image.getHeight());
} else {
return new Dimension(200, 200);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, this);
}
}
};
panel.setBorder(new LineBorder(Color.GRAY, 1));
}
public void setImage(BufferedImage image) {
this.image = image;
panel.revalidate();
panel.repaint();
}
public JPanel getPanel() {
return panel;
}
}
}
I have a Gridlayout filled with images loaded from File and I want to add a different, for example, popup, on mouseEvent mouseClicked for each image. How do I determine which image I'm clicking? I've tried adding GetComponentAt(Point), but Eclipse keeps showing that as an unidentified method for the mouseAdapter, and how do I determine the fields for the if statement?
This is what I have:
public class testclass implements ItemListener {
JPanel template;
final static String title = "Title";
public void testclass (Container window){
JPanel index = new JPanel();
String index2[] = {title};
JComboBox index3 = new JComboBox(index2);
index3.setEditable(false);
index3.addItemListener(this);
index.add(index3);
File folder = new File("images/");
File[] listOfFiles = folder.listFiles();
String nr;
final JPanel panel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < listOfFiles.length; i++) {
nr = "images/" + listOfFiles[i].getName();
final ImageIcon images = new ImageIcon(nr);
final JLabel display[] = new JLabel[1];
for (int n = 0; n < 1; n++){
display[n] = new JLabel(images);
panel.add(display[n]);
} }
panel.addMouseListener(new MouseAdapter()
{ public void mouseClicked (MouseEvent e)
{ //JPanel panel = (JPanel) getComponentAt(e.getPoint());
JOptionPane.showMessageDialog(null, "Message");
}});
template = new JPanel(new CardLayout());
template.add(panel, title);
window.add(index, BorderLayout.PAGE_START);
window.add(template, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent event){
CardLayout change = (CardLayout)(template.getLayout());
change.show(template, (String)event.getItem());
}
private static void userinterface() {
JFrame showwindow = new JFrame("Window");
showwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testclass show = new testclass();
show.testclass(showwindow.getContentPane());
showwindow.pack();
showwindow.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e){
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
userinterface();
}
});
}
}
Edit: Proper Answer
Thankyou for providing code. I have adjusted some things so hopefully you can understand them.
Firstly I have added a new object, ImageButton. From when I added the actionListener the functionality you wanted was already done (minus the good looks, you will have to play around with that, or ask another question)
Added a 'dir' string so that you don't have to keep copy and pasting the directory address.
I had to adjust the size of the window through the userInterface() method, you should look at being able to shorten the sequence of being able to adjust the parameters, maybe another GUI object to keep all that information together.
A couple of things:
The code you wrote was good but it would need for you to adjust alot of (getting the size of windows and repeatedly check for different sizes if you adjusted the window size where a mouse click could click on other image that you don't want!) in order for a mouseListener to work, I am guessing with a wide range of images you would be providing.
Putting comments in your code can help both you and someone trying to help you.
Anyways, please upvote/accept answer if this helps out, which I'm sure it does.
Good Luck!
Put these files into your eclipse and run them it should work if you adjust the dir string to follow your original directory path.
testclass.java
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class testclass implements ItemListener {
JPanel template;
final static String title = "Title";
final String dir = "images/";
public void testclass(Container window) {
JPanel index = new JPanel();
String[] index2 = { title };
JComboBox index3 = new JComboBox(index2);
index3.setEditable(false);
index3.addItemListener(this);
index.add(index3);
index.setSize(500, 500);
File folder = new File(dir);
File[] listOfFiles = folder.listFiles();
String nr;
final JPanel panel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < listOfFiles.length; i++) {
nr = dir + listOfFiles[i].getName();
panel.add(new ImageButton(nr));
}
template = new JPanel(new CardLayout());
template.add(panel, title);
window.add(template, BorderLayout.CENTER);
window.add(index, BorderLayout.NORTH);
window.setVisible(true);
}
public void itemStateChanged(ItemEvent event) {
CardLayout change = (CardLayout) (template.getLayout());
change.show(template, (String) event.getItem());
}
private static void userinterface() {
JFrame showwindow = new JFrame("Window");
showwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testclass show = new testclass();
show.testclass(showwindow.getContentPane());
showwindow.pack();
showwindow.setVisible(true);
showwindow.setSize(500, 500);
}
public static void main(String[] args) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
userinterface();
}
});
}
}
ImageButton.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class ImageButton extends JButton {
private String fileName;
private ImageIcon image;
private JButton button;
public ImageButton(String fileName) {
setFileName(fileName);
setImage(new ImageIcon(fileName));
setButton(new JButton(getImage()));
this.setIcon(getImage());
this.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, ae.getSource());
}
});
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public ImageIcon getImage() {
return image;
}
public void setImage(ImageIcon image) {
this.image = image;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
}
I'm writing a GUI in Swing where I want to do a file chooser that is in the main window, looking something like the image below:
while there seem to be quite a few tutorials on how to write a popup file chooser, i don't see much information on how this type of chooser might be accomplished in swing.
also sorry if this has been asked before, i did a good bit of searching around and wan't able to find anything else..
PanelBrowser, shown below, is a basic prototype that functions similarly to the Mac OS X Finder column view illustrated in your question.
Update: Added horizontal scrolling and more file information.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.io.File;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileSystemView;
/**
* #see http://stackoverflow.com/a/15104660/230513
*/
public class PanelBrowser extends Box {
private static final Dimension SIZE = new Dimension(200, 300);
private List<FilePanel> list = new ArrayList<FilePanel>();
public PanelBrowser(File root) {
super(BoxLayout.LINE_AXIS);
setBackground(Color.red);
FilePanel panel = new FilePanel(this, root);
list.add(panel);
this.add(panel);
}
private void update(FilePanel fp, File file) {
int index = list.indexOf(fp);
int i = list.size() - 1;
while (i > index) {
list.remove(i);
this.remove(i);
i--;
}
final FilePanel panel = new FilePanel(this, file);
list.add(panel);
this.add(panel);
revalidate();
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
scrollRectToVisible(panel.getBounds());
}
});
}
private static class FilePanel extends Box {
private static FileSystemView fsv = FileSystemView.getFileSystemView();
private static DateFormat df = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.DEFAULT);
private PanelBrowser parent;
private JList list;
public FilePanel(PanelBrowser parent, File file) {
super(BoxLayout.PAGE_AXIS);
this.parent = parent;
DefaultListModel model = new DefaultListModel();
if (file.isFile()) {
JLabel name = new JLabel(file.getName());
name.setIcon(fsv.getSystemIcon(file));
this.add(name);
Date d = new Date(file.lastModified());
JLabel mod = new JLabel("Date: " + df.format(d));
this.add(mod);
final String v = String.valueOf(file.length());
JLabel length = new JLabel("Size: " + v);
this.add(length);
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
model.addElement(f);
}
list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setCellRenderer(new FileRenderer());
list.addListSelectionListener(new SelectionHandler());
this.add(new JScrollPane(list) {
#Override
public int getVerticalScrollBarPolicy() {
return JScrollPane.VERTICAL_SCROLLBAR_ALWAYS;
}
});
}
}
private static class FileRenderer extends DefaultListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
File f = (File) value;
setText(f.getName());
setIcon(fsv.getSystemIcon(f));
return label;
}
}
private class SelectionHandler implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
File f = (File) list.getSelectedValue();
parent.update(FilePanel.this, f);
}
}
}
#Override
public Dimension getMinimumSize() {
return new Dimension(SIZE);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SIZE);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(SIZE.width, Short.MAX_VALUE);
}
}
private static void display() {
String path = System.getProperty("user.dir");
PanelBrowser browser = new PanelBrowser(new File(path));
JFrame f = new JFrame(path);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(browser) {
#Override
public int getVerticalScrollBarPolicy() {
return JScrollPane.VERTICAL_SCROLLBAR_NEVER;
}
});
f.pack();
f.setSize(4 * SIZE.width, SIZE.height);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
display();
}
});
}
}
JFileChooser actually extends JComponent, so you can use like any other component. Here is an example with two in-pane file choosers:
public class TestInPaneChoosers {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
buildFrame();
}
});
}
private static void buildFrame() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
f.add(new JFileChooser());
f.add(new JFileChooser());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}