pvbemu/src/desktop/util/UPanel.java

94 lines
2.7 KiB
Java

package util;
// Java imports
import java.awt.*;
import java.util.*;
import javax.swing.*;
// Wrapper around JPanel to work around a bug in GridBagLayout
public class UPanel extends JPanel {
// Instance fields
private HashSet<PaintListener> paintListeners;
///////////////////////////////////////////////////////////////////////////
// Classes //
///////////////////////////////////////////////////////////////////////////
// Functional interface for paint events
public interface PaintListener {
void paint(Graphics2D g, int width, int height);
}
///////////////////////////////////////////////////////////////////////////
// Constructors //
///////////////////////////////////////////////////////////////////////////
// Default constructor
public UPanel() {
this(null);
}
// Layout manager constructor
public UPanel(LayoutManager layout) {
super(layout);
paintListeners = new HashSet<PaintListener>();
}
///////////////////////////////////////////////////////////////////////////
// Public Methods //
///////////////////////////////////////////////////////////////////////////
// Add a listener to receive paint events
public void addPaintListener(PaintListener l) {
if (l != null)
paintListeners.add(l);
}
// Retrieve a list of the current paint listeners
public PaintListener[] getPaintListeners() {
return paintListeners.toArray(
new PaintListener[paintListeners.size()]);
}
// Retrieve the maximum size of the component
public Dimension getMaximumSize() {
var ret = super.getMaximumSize();
return ret != null ? ret : new Dimension();
}
// Retrieve the minimum size of the component
public Dimension getMinimumSize() {
var ret = super.getMinimumSize();
return ret != null ? ret : new Dimension();
}
// Retrieve the preferred size of the component
public Dimension getPreferredSize() {
var ret = super.getPreferredSize();
return ret != null ? ret : new Dimension();
}
// Draw the component
public void paintComponent(Graphics g) {
super.paintComponent(g);
var G = (Graphics2D) g;
int width = getWidth();
int height = getHeight();
for (var lst : paintListeners)
lst.paint(G, width, height);
}
// Remove a paint listener from the collection
public void removePaintListener(PaintListener l) {
paintListeners.remove(l);
}
}