The applet plays an animated gif file:
public class Applet1 extends Applet {
private Image m_image=null;
public void init() {
m_image=getImage(getDocumentBase(), "001.gif");
}
public void paint(Graphics g) {
g.drawImage(m_image,0,0,this);
}
public boolean imageUpdate( Image img, int flags, int x, int y, int w, int h ) {
System.out.println("Image update: flags="+flags+" x="+x+" y="+y+" w="+w+" h="+h);
repaint();
return true;
}
}
I need to add the updated image in another program:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
public class HighlightExample {
public static void main(String[] args) {
JFrame f = new JFrame("Highlight example");
final JTextPane textPane = new JTextPane();
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
final JTextField tf = new JTextField();
pane.add(tf, "Center");
f.getContentPane().add(pane, "South");
f.getContentPane().add(new JScrollPane(textPane), "Center");
textPane.setText("abсdefghijkl lmnop12345678");
final WordSearcher searcher = new WordSearcher(textPane);
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
word = tf.getText().trim();
int offset = searcher.search(word);
if (offset != -1) {
try {
textPane.scrollRectToVisible(textPane.modelToView(offset));
} catch (BadLocationException e) {}
}
}
});
textPane.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent evt) {
searcher.search(word);
}
public void removeUpdate(DocumentEvent evt) {
searcher.search(word);
}
public void changedUpdate(DocumentEvent evt) {
}
});
f.setSize(400, 400);
f.setVisible(true);
}
public static String word;
}
class WordSearcher {
protected JTextComponent comp;
protected Highlighter.HighlightPainter painter;
public WordSearcher(JTextComponent comp) {
this.comp = comp;
this.painter = new UnderlineHighlighter.UnderlineHighlightPainter(Color.red);
}
public int search(String word) {
int firstOffset = -1;
Highlighter highlighter = comp.getHighlighter();
Highlighter.Highlight[] highlights = highlighter.getHighlights();
for (int i = 0; i < highlights.length; i++) {
Highlighter.Highlight h = highlights[i];
if (h.getPainter() instanceof UnderlineHighlighter.UnderlineHighlightPainter) {
highlighter.removeHighlight(h);
}
}
if (word == null || word.equals("")) {
return -1;
}
String content;
try {
Document d = comp.getDocument();
content = d.getText(0, d.getLength()).toLowerCase();
} catch (BadLocationException e) {
return -1;
}
word = word.toLowerCase();
int lastIndex = 0;
int wordSize = word.length();
while ((lastIndex = content.indexOf(word, lastIndex)) != -1) {
int endIndex = lastIndex + wordSize;
try {
highlighter.addHighlight(lastIndex, endIndex, painter);
} catch (BadLocationException e) {}
if (firstOffset == -1) {
firstOffset = lastIndex;
}
lastIndex = endIndex;
}
return firstOffset;
}
}
class UnderlineHighlighter extends DefaultHighlighter{
protected static final Highlighter.HighlightPainter sharedPainter = new UnderlineHighlightPainter(null);
protected Highlighter.HighlightPainter painter;
public static class UnderlineHighlightPainter extends LayeredHighlighter.LayerPainter {
protected Color color; // The color for the underline
public UnderlineHighlightPainter(Color c) {
color = c;
}
public void paint(final Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) {
}
public Shape paintLayer(final Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c, View view) {
g.setColor(color == null ? c.getSelectionColor() : color);
Rectangle alloc;
try {
Shape shape = view.modelToView(offs0,Position.Bias.Forward, offs1,Position.Bias.Backward, bounds);
alloc = (shape instanceof Rectangle) ? (Rectangle) shape : shape.getBounds();
} catch (BadLocationException e) {
return null;
}
FontMetrics fm = c.getFontMetrics(c.getFont());
int baseline = alloc.y + alloc.height - fm.getDescent() + 1;
g.drawLine(alloc.x, baseline, alloc.x + alloc.width, baseline);
Toolkit kit=Toolkit.getDefaultToolkit();
Image im3 =kit.getImage("001.gif");
g.drawImage(im3,alloc.x+15,alloc.y-6,null);
return alloc;
}
}
}
In this program always displays only the first frame of the image im3. Sorry for a lot of code, it is fully compillable.
It seems like the problem is that you are passing null as the ImageObserver when drawing the image (near the end of your code):
g.drawImage(im3,alloc.x+15,alloc.y-6,null);
So, the image will fire an update when a new frame is ready, but that update just gets ignored because there are no listeners. You probably want to pass c as the ImageObserver so that it will repaint itself when the image changes.
Edit:
This approach will c entirely. If you wanted to be clever, you could create your own ImageObserver that remembers the exact rectangle in c that the icon was painted in, and repaints just that rectangle when notified of an update.
Related
I have been looking how to filter with a JTextField a JList and highlight the same expression is written in the text field and in each element of the list, I have been surfing the net and I found an example in this page.
https://www.logicbig.com/tutorials/java-swing/list-filter-highlighting.html
Even though I tried to make the same code, my version filters ok but it does not highlight anything, I post here my code which is more or less the same of the page but changing my classes.
The labelHighlighted
package ui.admin.citas.filtering;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
public class LabelHighlighted extends JLabel {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Rectangle2D> rectangles = new ArrayList<>();
private Color colorHighlight = Color.YELLOW;
public void reset() {
rectangles.clear();
repaint();
}
public void highlightText(String textToHighlight) {
if (textToHighlight == null) {
return;
}
reset();
final String textToMatch = textToHighlight.toLowerCase().trim();
if (textToMatch.length() == 0) {
return;
}
textToHighlight = textToHighlight.trim();
final String labelText = getText().toLowerCase();
if (labelText.contains(textToMatch)) {
FontMetrics fm = getFontMetrics(getFont());
float w = -1;
final float h = fm.getHeight() - 1;
int i = 0;
while (true) {
i = labelText.indexOf(textToMatch, i);
if (i == -1) {
break;
}
if (w == -1) {
String matchingText = getText().substring(i, i + textToHighlight.length());
w = fm.stringWidth(matchingText);
}
String preText = getText().substring(0, i);
float x = fm.stringWidth(preText);
rectangles.add(new Rectangle2D.Float(x, 1, w, h));
i = i + textToMatch.length();
}
repaint();
}
}
#Override
protected void paintComponent(Graphics g) {
if (isOpaque()) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
if (rectangles.size() > 0) {
Graphics2D g2d = (Graphics2D) g;
Color c = g2d.getColor();
for (Rectangle2D rectangle : rectangles) {
g2d.setColor(colorHighlight);
g2d.fill(rectangle);
g2d.setColor(Color.LIGHT_GRAY);
g2d.draw(rectangle);
}
g2d.setColor(c);
}
super.paintComponent(g);
}
}
Here is the decorator.
package ui.admin.citas.filtering;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiPredicate;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class JListFilterDecorator {
private JTextField filterField;
public static <T> JListFilterDecorator decorate(JList<T> list, BiPredicate<T, String> userFilter) {
if (!(list.getModel() instanceof DefaultListModel)) {
throw new IllegalArgumentException("List model must be an instance of DefaultListModel");
}
DefaultListModel<T> model = (DefaultListModel<T>) list.getModel();
List<T> items = getItems(model);
JTextField textField = new JTextField();
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
filter();
}
#Override
public void removeUpdate(DocumentEvent e) {
filter();
}
#Override
public void changedUpdate(DocumentEvent e) {
filter();
}
private void filter() {
model.clear();
String s = textField.getText();
for (T item : items) {
if(userFilter.test(item, s)){
model.addElement(item);
}
}
}
});
JListFilterDecorator decorator = new JListFilterDecorator();
decorator.filterField = textField;
return decorator;
}
private static <T> List<T> getItems(DefaultListModel<T> model) {
List<T> list = new ArrayList<>();
for (int i = 0; i < model.size(); i++) {
list.add(model.elementAt(i));
}
return list;
}
public JTextField getFilterField() {
return filterField;
}
}
Here I create the text field at the constructor of the window
JListFilterDecorator decoratorPacientes = JListFilterDecorator.decorate(listPacientes, VentanaCitasBase::filterPaciente);
JTextField toAddPac = decoratorPacientes.getFilterField();
toAddPac.setText("Busque aquí...");
toAddPac.setForeground(Color.LIGHT_GRAY);
toAddPac.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
toAddPac.setText("");
toAddPac.setForeground(Color.BLACK);
}
#Override
public void focusLost(FocusEvent e) {
toAddPac.setText("Busque aquí...");
toAddPac.setForeground(Color.LIGHT_GRAY);
}
});
getPanelSearch().add(toAddPac);
listPacientes.setCellRenderer(createListPacientesRenderer(toAddPac));
Finally the method that creates the renderer at the window too
private ListCellRenderer<? super PacienteDTO> createListPacientesRenderer(JTextField filterField) {
return new DefaultListCellRenderer() {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (c instanceof JLabel) {
PacienteDTO emp = (PacienteDTO) value;
JLabel original = (JLabel) c;
LabelHighlighted label = new LabelHighlighted();
label.setText(emp.toString());
label.setBackground(original.getBackground());
label.setForeground(original.getForeground());
label.setOpaque(original.isOpaque());
label.setHorizontalTextPosition(original.getHorizontalTextPosition());
label.highlightText(filterField.getText());
return label;
}
return c;
}
};
}
I’m writing a simple graphics editor, thus far I can draw some figures, move and enlarge them. I’m trying to allow user to change color of figure. After I right click in a shape, there appears a popup menu with colors to choose. But no matter what I do - the shape’s color doesn’t change. :/ I hope to get help, I spent a of of time on it but no idea how to solve it. :/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
public class PaintPanel extends JPanel implements MouseListener, MouseMotionListener, MouseWheelListener
{
public RadioMenu radio = new RadioMenu();
private ArrayList <Point2D.Double> points = new ArrayList<>();
private ArrayList <Shape> figures = new ArrayList<>();
private Color mainColor = Color.blue;
private Color bgColor = Color.white;
private Color special = Color.red;
private double scrollSpeed = 5;
private int pointsize = 4;
private int near = 15;
private int index;
private ColorMenu colorMenu = new ColorMenu();
public PaintPanel()
{
super();
addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
setLayout(new BorderLayout());
setBackground(bgColor);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
drawGraphics(g2d);
}
private void drawGraphics(Graphics2D g2d)
{
int i = 0;
for (Shape s : figures)
{
g2d.setColor(mainColor);
if (s instanceof MyEllipse2D)
{
g2d.setColor(((MyEllipse2D) s).color);
System.out.println(g2d.getColor());
}
else if (s instanceof MyRectangle2D)
{
g2d.setColor(((MyRectangle2D) s).color);
System.out.println(g2d.getColor());
}
else if (s instanceof MyPolygon2D)
{
g2d.setColor(((MyPolygon2D) s).color);
System.out.println(g2d.getColor());
}
if (g2d.getColor() != bgColor)
{
g2d.setColor(mainColor);
} else
{
g2d.setColor(mainColor);
g2d.draw(s);
}
++i;
}
i = 0;
for (Point2D.Double p : points)
{
if (i == 0)
{
g2d.setColor(special);
g2d.fillOval((int) p.getX(), (int) p.getY(), pointsize, pointsize);
g2d.setColor(mainColor);
} else
{
g2d.fillOval((int) p.getX(), (int) p.getY(), pointsize, pointsize);
}
++i;
}
}
#Override
public void mousePressed(MouseEvent e)
{
if(e.getButton()==MouseEvent.BUTTON1)
switch (radio.getChoice())
{
case "Okrag":
points.clear();
points.add(new Point2D.Double(e.getX(),e.getY()));
repaint();
break;
case "Prostokat":
points.clear();
points.add(new Point2D.Double(e.getX(),e.getY()));
repaint();
break;
case "Edycja":
index = isSelected(e);
break;
}
else if(e.getButton()==MouseEvent.BUTTON3 && radio.getChoice().equals("Edycja"))
{
index = isSelected(e);
if(index >= 0)
{
colorMenu.doPop(e);
}
}
}
#Override
public void mouseReleased(MouseEvent e)
{
if(e.getButton()==MouseEvent.BUTTON1)
switch (radio.getChoice())
{
case "Okrag":
points.add(new Point2D.Double(e.getX(),e.getY()));
figures.add(new MyEllipse2D(points.get(0),points.get(1),bgColor));
points.clear();
break;
case "Prostokat":
points.add(new Point2D.Double(e.getX(),e.getY()));
figures.add(new MyRectangle2D(points.get(0),points.get(1),bgColor));
points.clear();
break;
case "Wielokat":
if(points.size() != 0 && points.get(0).distance(e.getX(),e.getY())<=near)
{
figures.add(new MyPolygon2D(points,bgColor));
points.clear();
}
else
{
points.add(new Point2D.Double(e.getX(),e.getY()));
}
break;
case "Edycja":
points.clear();
}
repaint();
}
#Override
public void mouseDragged(MouseEvent e)
{
if(index>=0 && radio.getChoice().equals("Edycja"))
{
if (figures.get(index) instanceof MyEllipse2D)
{
((MyEllipse2D) figures.get(index)).move(new Point2D.Double(e.getX(),e.getY()));
}
else if (figures.get(index) instanceof MyRectangle2D)
{
((MyRectangle2D) figures.get(index)).move(new Point2D.Double(e.getX(),e.getY()));
}
else if(figures.get(index) instanceof MyPolygon2D)
{
((MyPolygon2D) figures.get(index)).move(new Point2D.Double(e.getX(),e.getY()));
}
repaint();
}
}
#Override
public void mouseWheelMoved(MouseWheelEvent e)
{
index = isSelected(e);
if(radio.getChoice().equals("Edycja"))
{
if (index>=0)
{
if (figures.get(index) instanceof MyEllipse2D)
{
((MyEllipse2D) figures.get(index)).scale(e.getPreciseWheelRotation(), scrollSpeed);
}
else if (figures.get(index) instanceof MyRectangle2D)
{
((MyRectangle2D) figures.get(index)).scale(e.getPreciseWheelRotation(), scrollSpeed);
}
else if(figures.get(index) instanceof MyPolygon2D)
{
((MyPolygon2D) figures.get(index)).scale(e.getPreciseWheelRotation(), scrollSpeed);
}
repaint();
}
}
}
private int isSelected(MouseEvent e)
{
int i;
for(i=figures.size()-1;i>=0;--i)
{
if(figures.get(i).contains(e.getPoint()))
{
return i;
}
}
return -1;
}
#Override
public void mouseClicked(MouseEvent e)
{
index = isSelected(e);
if(index >= 0 )
{
colorMenu.doPop(e);
if(e.getButton()==MouseEvent.BUTTON3 && radio.getChoice().equals("Edycja"))
{
colorMenu.doPop(e);
if(figures.get(index) instanceof MyEllipse2D)
((MyEllipse2D) figures.get(index)).color = colorMenu.color;
else if(figures.get(index) instanceof MyRectangle2D)
((MyRectangle2D) figures.get(index)).color = colorMenu.color;
else if(figures.get(index) instanceof MyPolygon2D)
((MyPolygon2D) figures.get(index)).color = colorMenu.color;
System.out.println(colorMenu.color);
//colorMenu.color = bgColor;
}
repaint();
}
}
#Override
public void mouseEntered(MouseEvent e)
{
}
#Override
public void mouseExited(MouseEvent e)
{
}
#Override
public void mouseMoved(MouseEvent e)
{
}
}
ColorMenu
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
public class ColorMenu extends JPopupMenu implements ActionListener
{
private ArrayList<JMenuItem> items = new ArrayList<JMenuItem>();
private ArrayList<Color> colors = new ArrayList<Color>();
public Color color;
public ColorMenu()
{
super();
colors.add(Color.black);
colors.add(Color.blue);
colors.add(Color.cyan);
colors.add(Color.gray);
colors.add(Color.green);
colors.add(Color.magenta);
colors.add(Color.orange);
colors.add(Color.red);
colors.add(Color.yellow);
colors.add(Color.white);
for (Color c : colors)
{
items.add(new JMenuItem(c.toString()));
}
for(JMenuItem i: items)
{
i.addActionListener(this);
add(i);
}
}
public void doPop(MouseEvent e)
{
show(e.getComponent(), e.getX(), e.getY());
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
int j=0;
for(JMenuItem i: items)
{
if(i == source)
{
break;
}
++j;
}
this.color = colors.get(j);
}
}
MyRectangle2D
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
public class MyRectangle2D extends Rectangle2D.Double implements Shape
{
private Point2D.Double center;
private double width,hight;
public Color color;
public MyRectangle2D()
{}
public MyRectangle2D(Point2D.Double p1, Point2D.Double p2, Color color)
{
super();
this.color = color;
double x1 = p1.getX();
double y1 = p1.getY();
double x2 = p2.getX();
double y2 = p2.getY();
if(x1<=x2 && y1>=y2)
{
width=x2-x1;
hight=y1-y2;
setRect(x1,y2,width,hight);
}
else if(x1<=x2 && y1<=y2)
{
width=x2-x1;
hight=y2-y1;
setRect(x1,y1,width,hight);
}
else if (x1>=x2 && y1<=y2)
{
width=x1-x2;
hight=y2-y1;
setRect(x2,y1,width,hight);
}
else if(x1>=x2 && y1>=y2)
{
width=x1-x2;
hight=y1-y2;
setRect(x2,y2,width,hight);
}
center = new Point2D.Double(x1 + (x2-x1)/2,y1+(y2-y1)/2);
}
public void scale(double amount, double scale)
{
double change = -1*amount*scale;
width += change;
hight += change;
setRect(center.getX()-width/2,center.getY()-hight/2,width,hight);
}
public void move (Point2D.Double p)
{
center = p;
setRect();
}
private void setRect()
{
setRect(center.getX()-width/2,center.getY()-hight/2,width,hight);
}
}
MyPolygon2D
import java.awt.*;
import java.awt.geom.Point2D;
import java.util.ArrayList;
public class MyPolygon2D extends Polygon implements Shape
{
private ArrayList<MyVector> vectors = new ArrayList<>();
private Point2D.Double center;
private int size;
public Color color;
public MyPolygon2D()
{}
public MyPolygon2D(ArrayList<Point2D.Double> points, Color color)
{
super();
this.color = color;
size = points.size();
for(int i=0; i<size;++i)
{
addPoint((int)points.get(i).getX(),(int)points.get(i).getY());
}
center();
setVectors();
}
public void scale(double amount, double scale)
{
double change = -1*amount*scale;
for (int i=0;i<size;++i)
{
vectors.get(i).x *= (100.0+change)/100.0;
vectors.get(i).y *= (100.0+change)/100.0;
Point2D.Double curr = new Point2D.Double(center.getX()+vectors.get(i).x,center.getY()+vectors.get(i).y);
xpoints[i] = (int)curr.getX();
ypoints[i] = (int)curr.getY();
}
invalidate();
}
public void move (Point2D.Double p)
{
MyVector change = new MyVector(center,p);
center = p;
for(int i=0;i<size;++i)
{
xpoints[i] += (int)change.x;
ypoints[i] += (int)change.y;
}
invalidate();
}
public void setColor(Color color)
{
this.color = color;
}
public Color getColor()
{
return this.color;
}
#Override
public boolean contains(Point p)
{
int maxx=0, maxy=0, minx=Integer.MAX_VALUE, miny=Integer.MAX_VALUE;
for (int i=0;i<size;++i)
{
if(xpoints[i]>=maxx)
maxx = xpoints[i];
if(xpoints[i]<=minx)
minx = xpoints[i];
if(ypoints[i]>=maxy)
maxy = ypoints[i];
if(ypoints[i]<=miny)
miny = ypoints[i];
}
if(p.getX() <= maxx && p.getX() >= minx && p.getY() <= maxy && p.getY() >=miny)
return true;
else
return false;
}
private void setVectors()
{
for(int i=0; i<size;++i)
{
vectors.add(new MyVector(center,new Point2D.Double(xpoints[i],ypoints[i])));
}
}
private void center()
{
center = new Point2D.Double(getBounds2D().getX()+getBounds2D().getWidth()/2,getBounds2D().getY()+getBounds2D().getHeight()/2);
}
private class MyVector
{
public double x, y;
public MyVector(Point2D.Double p1, Point2D.Double p2)
{
x=p2.getX()-p1.getX();
y=p2.getY() - p1.getY();
}
}
}
MyEllipse2D
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
public class MyEllipse2D extends Ellipse2D.Double implements Shape
{
private double radius;
private Point2D.Double center;
public Color color;
public MyEllipse2D(Point2D.Double p1, Point2D.Double p2, Color color)
{
super();
this.color = color;
center = p1;
radius = (p1.distance(p2));
setFrame();
}
public void scale(double amount, double scale)
{
double change = -1*amount*scale;
radius += change;
setFrame();
}
public void move (Point2D.Double p)
{
center = p;
setFrame();
}
public void setColor(Color color)
{
this.color = color;
System.out.println(this.color);
}
public Color getColor()
{
return this.color;
}
private void setFrame()
{
setFrame(center.getX()-radius,center.getY()-radius,2*radius,2*radius);
}
}
RadioMenu
import javax.swing.*;
import java.awt.*;
public class RadioMenu extends JPanel
{
private int amount = 4;
private JRadioButton[] options = new JRadioButton[amount];
private ButtonGroup group = new ButtonGroup();
private String[] names = {"Okrag","Prostokat","Wielokat","Edycja"};
private Font font = new Font("Times New Roman",Font.BOLD,16);
public RadioMenu()
{
super();
setLayout(new GridLayout(1,amount));
for(int i=0;i<amount;++i)
{
if(i!=0)
options[i] = new JRadioButton(names[i],false);
else
options[i] = new JRadioButton(names[i],true);
group.add(options[i]);
add(options[i]);
options[i].setFont(font);
}
}
public String getChoice()
{
for(int i=0; i<amount; ++i)
{
if(options[i].isSelected())
return options[i].getText();
}
return "";
}
}
Frame
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame
{
private Dimension prefsize = new Dimension(800,600);
private Dimension minSize = new Dimension(400,200);
private Menu menu = new Menu();
private PaintPanel panel = new PaintPanel();
public Frame()
{
super();
setVisible(true);
setPreferredSize(prefsize);
setMinimumSize(minSize);
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(panel,BorderLayout.CENTER);
JPanel upper = new JPanel();
upper.setLayout(new GridLayout(2,1));
upper.add(menu);
upper.add(panel.radio);
add(upper,BorderLayout.NORTH);
pack();
}
}
MyAplet
import javax.swing.*;
public class MyAplet extends JApplet
{
public void init()
{
Frame main = new Frame();
}
}
Menu
import javax.swing.*;
public class Menu extends JMenuBar
{
private JMenu info;
//private JMenuItem x;
public Menu()
{
super();
info = new JMenu("info");
//info.add(x);
add(info);
}
}
First, you should be displaying a JPopupMenu in response to only one type of event. You are currently calling colorMenu.doPop(e) in the mousePressed method and twice in the mouseClicked method.
To make sure you only display a JPopupMenu when you’re supposed to, you should use the JPopupMenu.isPopupTrigger method. This way, the menu will be displayed on mousePress or mouseClick, but never both. You do not want to display a JPopupMenu more than once in response to a single mouse action!
private int selectedIndex = -1;
// ...
#Override
public void mousePressed(MouseEvent e)
{
selectedIndex = isSelected(e);
if (colorMenu.isPopupTrigger(e)) {
colorMenu.doPop(e);
} else if (e.getButton() == MouseEvent.BUTTON1) {
// ...
#Override
public void mouseClicked(MouseEvent e)
{
if (selectedIndex >= 0 && colorMenu.isPopupTrigger(e) && radio.getChoice().equals("Edycja"))
{
colorMenu.doPop(e);
The next problem is that you’re trying to read colorMenu.color before the user has made a color selection. When you call colorMenu.doPopup(e), the menu is displayed and the method returns immediately. It does not wait for the user to make a selection and dismiss the menu. Your code is trying to immediately make use of colorMenu.color, but it hasn’t been set yet.
The only way to know when the user has selected a color is with an ActionListener. Your ColorMenu class has an ActionListener, but currently there is no way for the PaintPanel class to know when the ActionListener has been triggered.
You can give your ColorMenu class the capability of notifying listeners in other classes, using the inherited listenerList object:
public void addChangeListener(ChangeListener listener) {
listenerList.add(ChangeListener.class, listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(ChangeListener.class, listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.getListeners(ChangeListener.class);
}
protected void fireChangeListeners() {
ChangeEvent event = new ChangeEvent(this);
for (ChangeListener listener : getChangeListeners()) {
listener.stateChanged(event);
}
}
(ChangeListener and ChangeEvent are in the javax.swing.event package.)
This allows other classes to listen for a user selection. You want to change ColorMenu to actually notify those listeners:
#Override
public void actionPerformed(ActionEvent e)
{
// (other code) ...
this.color = colors.get(j);
fireChangeListeners();
}
Now, you can make PaintPanel listen for a user selection:
public PaintPanel()
{
super();
addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
setLayout(new BorderLayout());
setBackground(bgColor);
colorMenu.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent event) {
if (selectedIndex >= 0)
{
Shape figure = figures.get(selectedIndex);
if (figure instanceof MyEllipse2D)
((MyEllipse2D) figure).color = colorMenu.color;
else if (figure instanceof MyRectangle2D)
((MyRectangle2D) figure).color = colorMenu.color;
else if (figure instanceof MyPolygon2D)
((MyPolygon2D) figure).color = colorMenu.color;
}
}
});
}
You should remove that color changing code from mouseClicked, as it will never be valid to call it there, since the user hasn’t selected a color yet:
#Override
public void mouseClicked(MouseEvent e)
{
if (selectedIndex >= 0 && colorMenu.isPopupTrigger(e) && radio.getChoice().equals("Edycja"))
{
colorMenu.doPop(e);
// Nothing else to do here, since the user has not selected a color yet.
}
}
The basic problem is, you need to know when the color is selected from the menu. The solution to the problem can be achieved in a number of different ways.
You could continue to use a MouseListener to monitor the mousePressed, mouseReleased and mouseClicked events, but you should be making using of the MouseEvent#isPopupTrigger property to determine when the popup should be displayed, as the triggers are different for different platforms.
Another solution would be to use JComponent#setComponentPopupMenu all the component to take care of the action itself. This, however, would require a slight change in design.
This approach places the onus back onto the component, rather then been separated into a different class, like you have the ColorMenu right now.
To start with, we need to know the selected shape, so, to the PaintPanel, we need to add a new property
private Shape selectedShape;
All this does is determines which shape was selected by the user.
Next we need someway to update the shape color. This can be achieved by simply adding a new method to the paintPanel method, which is called when the color is to be changed.
public void setShapeColor(Color color) {
//...
}
Next, we take advantage of the Action API and create a simple ColorAction.
This is self contained unit of work, which contains the information need to display it on a menu (or button) and which determines the actions to take when triggered.
public class ColorAction extends AbstractAction {
private Color color;
public ColorAction(String name, Color color) {
super(name);
this.color = color;
}
public Color getColor() {
return color;
}
#Override
public boolean isEnabled() {
return getSelectedShape() != null;
}
#Override
public void actionPerformed(ActionEvent e) {
setShapeColor(color);
}
}
In this case, this simple inner class to PaintPanel will call setShapeColor when triggered.
"But wait", I hear you call, "The colors can only be selected when a shape is selected!" Ah, we can control the Action through the isEnabled method, which will only return true when a shape is actually selected.
This might seem somewhat counterintuitive, but by not displaying a popup menu when nothing is displayed, it causes the user to think that no popup menu will be displayed ever, at least this way, we can display a popup menu with it's options disabled.
The next trick is trying to determine what is selected. Unfortunately, during my testing, the OS consumed the mousePressed event, which would have been most useful to make this determination, however, not all is lost.
The JComponent will call getPopupLocation just before the popup is made visible, passing in the MouseEvent which triggered it, we can take advantage of this to determine which shape would be selected
#Override
public Point getPopupLocation(MouseEvent event) {
selectedShape = null;
for (int i = figures.size() - 1; i >= 0; --i) {
if (figures.get(i).contains(event.getPoint())) {
selectedShape = figures.get(i);
}
}
return super.getPopupLocation(event);
}
For a more complete example...
public class PaintPanel extends JPanel implements MouseListener, MouseMotionListener, MouseWheelListener {
private ArrayList<Point2D.Double> points = new ArrayList<>();
private ArrayList<Shape> figures = new ArrayList<>();
private Shape selectedShape;
private Color mainColor = Color.blue;
private Color bgColor = Color.white;
private Color special = Color.red;
private double scrollSpeed = 5;
private int pointsize = 4;
private int near = 15;
private int index;
public PaintPanel() {
super();
addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
setLayout(new BorderLayout());
setBackground(bgColor);
setComponentPopupMenu(makePopupMenu());
}
protected JPopupMenu makePopupMenu() {
JPopupMenu menu = new JPopupMenu();
menu.add(new ColorAction("Black", Color.black));
menu.add(new ColorAction("Blue", Color.blue));
menu.add(new ColorAction("Cyan", Color.cyan));
menu.add(new ColorAction("Grey", Color.gray));
menu.add(new ColorAction("Green", Color.green));
menu.add(new ColorAction("Megenta", Color.magenta));
menu.add(new ColorAction("Orange", Color.orange));
menu.add(new ColorAction("Red", Color.red));
menu.add(new ColorAction("Yellow", Color.yellow));
menu.add(new ColorAction("White", Color.white));
return menu;
}
public Shape getSelectedShape() {
return selectedShape;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
public Point getPopupLocation(MouseEvent event) {
selectedShape = null;
for (int i = figures.size() - 1; i >= 0; --i) {
if (figures.get(i).contains(event.getPoint())) {
selectedShape = figures.get(i);
}
}
return super.getPopupLocation(event);
}
#Override
public void mouseClicked(MouseEvent e) {
//...
}
#Override
public void mousePressed(MouseEvent e) {
//...
}
#Override
public void mouseReleased(MouseEvent e) {
//...
}
#Override
public void mouseEntered(MouseEvent e) {
//...
}
#Override
public void mouseExited(MouseEvent e) {
//...
}
#Override
public void mouseDragged(MouseEvent e) {
//...
}
#Override
public void mouseMoved(MouseEvent e) {
//...
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
//...
}
public void setShapeColor(Color color) {
//...
}
public class ColorAction extends AbstractAction {
private Color color;
public ColorAction(String name, Color color) {
super(name);
this.color = color;
}
public Color getColor() {
return color;
}
#Override
public boolean isEnabled() {
return getSelectedShape() != null;
}
#Override
public void actionPerformed(ActionEvent e) {
setShapeColor(color);
}
}
}
There are a couple of other ways you might achieve this, but I'd be using these basic principles are the cornerstone of the design.
For example, you could have a "color model" which get's passed to the popup menu class, which would be updated when a color is selected
For some reason, my KeyListener works just fine and fires off the Booleans to make down and up true and false and the y value changes according to those Booleans exactly how I want it to. My problem is that for some reason, the red rectangle appears to grow in size rather than move, and I'm pretty sure that it's because the previous frame is not cleared. I tried to use super.paintComponent(g); to clear the frame but this accomplishes nothing. Here's the code:
JFrame:
import java.awt.*;
import javax.swing.*;
public class H extends JFrame
{
public H()
{
super("Atlas Blade");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
pack();
P p = new P();
Insets frameInsets = getInsets();
int frameWidth = p.getWidth() +
(frameInsets.left + frameInsets.right);
int frameHeight = p.getHeight() + (
frameInsets.top + frameInsets.bottom);
setPreferredSize(new Dimension(frameWidth, frameHeight));
setLayout(null);
add(p);
pack();
setVisible(true);
}
}
JPanel:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.image.*;
public class P extends JPanel implements KeyListener, Runnable
{
private long updateCount=0;
private long paintCount=0;
private int updatesPerSecond = 50;
private boolean aLeft,aRight,aDown,aUp=false;
private boolean up,down,left,right=false;
int x = 20;
int y=20;
Hb box = new Hb(x,y);
Rectangle rect = new Rectangle(0,300,300,50);
BufferedImage buffer;
public P()
{
super();
setSize(600,350);
//setSize(50,50);
buffer = new BufferedImage (600,350,BufferedImage.TYPE_4BYTE_ABGR);
addKeyListener(this);
Thread jim = new Thread(this);
jim.start();
}
public void run()
{
int waitToUpdate = 1000/updatesPerSecond;
long startTime = System.nanoTime();
while(true)
{
boolean shouldRepaint = false;
long currentTime = System.nanoTime();
long updatesNeeded = (((currentTime-startTime) / 1000000))/ waitToUpdate;
for(long x = updateCount; x< updatesNeeded; x++)
{
updateGame();
shouldRepaint=true;
updateCount++;
}
if(shouldRepaint)
{
paintCount++;
repaint();
}
try
{
Thread.sleep(5);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics bg = buffer.getGraphics();
bg.setColor(Color.BLACK);
bg.drawRect(0,300,300,50);
bg.setColor(Color.RED);
bg.fillRect(x,y,35,35);
g.drawImage(buffer,0,0,null);
}
public void updateGame()
{
box.updateHitbox(x,y);
if(down)
{
if(!box.center.intersects(rect))
{
y++;
//y=y+40;
}
}
else if(up)
{
if(!box.center.intersects(rect))
{
y--;
}
}
}
public void keyPressed(KeyEvent e)
{
int code = e.getKeyCode();
if(code==KeyEvent.VK_A)
{
left=true;
right=false;
aLeft=true;
aRight=false;
aDown=false;
aUp=false;
}
if(code==KeyEvent.VK_D)
{
left=false;
right=true;
aLeft=false;
aRight=true;
aDown=false;
aUp=false;
}
if(code==KeyEvent.VK_S)
{
System.out.println(y);
down=true;
up=false;
aLeft=false;
aRight=false;
aDown=true;
aUp=false;
}
if(code==KeyEvent.VK_W)
{
down=false;
up=true;
aLeft=false;
aRight=false;
aDown=false;
aUp=true;
}
repaint();
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
int code = e.getKeyCode();
if(code==e.VK_A)
{
left=false;
aLeft=false;
}
if(code==e.VK_D)
{
right=false;
aRight=false;
}
if(code==e.VK_S)
{
down=false;
aDown=false;
}
if(code==e.VK_W)
{
up=false;
aUp=false;
}
}
public void addNotify()
{
// call super so the method still does what it was built to do
super.addNotify();
// requests focus so that key inputs are sent to this screen
requestFocus();
}
}
And the Hb class:
import java.awt.Rectangle;
public class Hb
{
public Rectangle center,left,right,up,down;
public Hb(int x, int y)
{
center = new Rectangle(x,y,50,50);
left = new Rectangle(x-1,y+1,1,48);
right = new Rectangle(x+50,y+1,1,48);
up = new Rectangle(x+1,y-1,48,1);
down = new Rectangle(x+1,y+50,48,1);
}
public void updateHitbox(int x, int y)
{
center = new Rectangle(x,y,50,50);
left = new Rectangle(x-1,y+1,1,48);
right = new Rectangle(x+50,y+1,1,48);
up = new Rectangle(x+1,y-1,48,1);
down = new Rectangle(x+1,y+50,48,1);
}
}
Your problem is that you're doing all your drawing in the BufferedImage, and that doesn't allow erasure of "dirty" pixels. Instead, only draw in the BufferedImage that which should be a static and unchanging part of the image, usually the background. The foreground image that moves should be painted directly in paintComponent using the Graphcis object given to the method by the JVM.
public P() {
super();
setSize(600, 350); // not recommended
buffer = new BufferedImage(600, 350, BufferedImage.TYPE_4BYTE_ABGR);
Graphics bg = buffer.getGraphics();
bg.setColor(Color.BLACK);
bg.drawRect(0, 300, 300, 50);
bg.dispose();
// ....
}
and
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(buffer, 0, 0, null);
g.setColor(Color.RED);
g.fillRect(x, y, 35, 35);
}
I just wrote some code to make my player move in my little maze game, but nothing happens. Also my maze is not drawn correct as in the matrix input. I don't figure out why is wrong this code...any help is well appeciated.
Thank you!
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.*;
public class Main extends JPanel {
private static Image white;
private static Image black;
private static Image finish;
private static Image player;
private static int x = 1;
private static int y = 1;
private String matrix[][];
public Main() {
addKeyListener(new Keys());
setFocusable(true);
}
public static String[][] load(String input) {
List<String[]> rows = new ArrayList<>();
try (Scanner scanner = new Scanner(input)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] cols = new String[line.length()];
for (int i = 0; i < cols.length; i++) {
cols[i] = line.substring(i, i + 1);
}
rows.add(cols);
}
}
return rows.toArray(new String[rows.size()][]);
}
public static JFrame buildFrame() {
JFrame frame = new JFrame("Labyrinth Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900, 950);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return frame;
}
public void moveUp() {
x += 0;
y += -1;
}
public void moveLeft() {
x += -1;
y += 0;
}
public void moveDown() {
x += 0;
y += 1;
}
public void moveRight() {
x += 1;
y += 0;
}
public class Keys extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
// repaint();
if (keycode == KeyEvent.VK_W) {
if (!matrix[getX()][getY() - 1].equals("1")) {
moveUp();
}
}
if (keycode == KeyEvent.VK_A) {
if (!matrix[getX() - 1][getY()].equals("1")) {
moveLeft();
}
}
if (keycode == KeyEvent.VK_S) {
if (!matrix[getX()][getY() + 1].equals("1")) {
moveDown();
}
}
if (keycode == KeyEvent.VK_D) {
if (!matrix[getX() + 1][getY()].equals("1")) {
moveRight();
}
}
}
#Override
public void keyReleased(KeyEvent event) {
}
}
public static void main(String[] args) {
String input = "1111111111111111111111111111111111111111111\n"
+ "1000000010001000001000000010000000100000001\n"
+ "1010111010101010101111101011111010111111101\n"
+ "1010001010100010100000001010000010000010001\n"
+ "1011101010111110101111111010111111111010111\n"
+ "1000101010100000101000001000100010000010001\n"
+ "1011101011101011111011101111111010111110101\n"
+ "1010001000001010000010100000001010000010101\n"
+ "1010111111111010111110111111101011111011101\n"
+ "1010100000100010100000000000101000000000101\n"
+ "1110101111101110111110111011101011111110101\n"
+ "1000100000000010000010100010001000100010001\n"
+ "1011111111111111111011101010111111101011101\n"
+ "1000000000000000100010001010000000001010001\n"
+ "1011111111111011101110111011111111111010111\n"
+ "1000100010001000001010001000100000001010101\n"
+ "1110101011101111111010101110111110111010101\n"
+ "1000101010001000100000101000100000100010001\n"
+ "1011101010111010101111101011101110101111111\n"
+ "1000001010000010000000101000001000100010001\n"
+ "1111111011111110111111101111111011111010101\n"
+ "1000001010000010100010001000000010000010101\n"
+ "1011111010111011101010111011111110101110101\n"
+ "1010000010001010001010001000100000101010101\n"
+ "1010111111101010111011101111101111101011101\n"
+ "1000100000001010101010001000100010101000101\n"
+ "1011111011111010101010111010111010101011101\n"
+ "1010000010001000101010000010001010001000001\n"
+ "1010101110101111101011101111101011111010101\n"
+ "1010101000101000001000101000001000000010101\n"
+ "1011101011111010111110111011101111111110111\n"
+ "1000001000000010000000000010000000000010021\n"
+ "1111111111111111111111111111111111111111111\n";
String[][] matrix = load(input);
JFrame frame = buildFrame();
ImageIcon img = new ImageIcon("C:/Users/Desktop/black20.png");
black = img.getImage();
img = new ImageIcon("C:/Users/Desktop/gri20.png");
white = img.getImage();
img = new ImageIcon("C:/Users/Desktop/finish20.png");
finish = img.getImage();
img = new ImageIcon("C:/Users/Desktop/smiley20.png");
player = img.getImage();
// frame.add(new Player());
JPanel pane = new JPanel() {
#Override
public void paint(Graphics g) {
super.paint(g);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j].equals("1")) {
g.drawImage(black, i * 20, j * 20, null);
}
if (matrix[i][j].equals("0")) {
g.drawImage(white, i * 20, j * 20, null);
}
if (matrix[i][j].equals("2")) {
g.drawImage(finish, i * 20, j * 20, null);
}
}
}
g.drawImage(player, x * 20, y * 20, null);
}
};
frame.add(pane);
frame.add(new Main());
}
}
It should look like:
Problems/Suggestions:
You're adding more than one component to the JFrame in a default fashion. Since the JFrame's contentPane uses BorderLayout, only one component will display, the last one added, and the other will be completely covered and will remain invisible.
Your Main JPanel is not being used as a true JPanel. Nothing is being added to it, and in fact it looks like it should be a logical class and not a component class.
Rather than using KeyListeners, which are very fidgety when it comes to focus problems, use Key Bindings which will allow you to get around focus issues in a clean and higher level way.
Don't override the JPanel's paint method but rather its paintComponent method as this will give you several advantages, including default use of double buffering for your animation.
Don't give component classes a public int getX() and public int getY() method without care since these override key methods that place the component within its container. Since the Main class shouldn't even extend JPanel, this will end up to be a non-issue for your code, but in the future, it would mess your program up.
When you run into similar problems, such as a KeyListener not working, remove the issue from your big program and try to reproduce it in a small separate program. This will give you a much cleaner environment for helping you to isolate and understand your problem and thereby help you fix it.
Your program is mis-using the static modifier. Your x and y fields should not be static and should not be accessed in a static way.
You've got way too much code within your main method, which is one of the reasons why you likely made x and y static, because you were forced to do so since you're trying to access them within main. The solution is not to make the fields static but to get all that code out of the static world and into the instance world.
Edit
For some reason the question intrigued me, and so I decided to try to M-V-C or Model-View-Controller it if possible and see what I could come up with. So here goes a bunch of classes that sort of work, beginning with a text file that holds the data.
The GUI looks like:
It must be in the same location as the class files since it is obtained as a resource and must have the file name "input.txt"
1111111111111111111111111111111111111111111
1000000010001000001000000010000000100000001
1010111010101010101111101011111010111111101
1010001010100010100000001010000010000010001
1011101010111110101111111010111111111010111
1000101010100000101000001000100010000010001
1011101011101011111011101111111010111110101
1010001000001010000010100000001010000010101
1010111111111010111110111111101011111011101
1010100000100010100000000000101000000000101
1110101111101110111110111011101011111110101
1000100000000010000010100010001000100010001
1011111111111111111011101010111111101011101
1000000000000000100010001010000000001010001
1011111111111011101110111011111111111010111
1000100010001000001010001000100000001010101
1110101011101111111010101110111110111010101
1000101010001000100000101000100000100010001
1011101010111010101111101011101110101111111
1000001010000010000000101000001000100010001
1111111011111110111111101111111011111010101
1000001010000010100010001000000010000010101
1011111010111011101010111011111110101110101
1010000010001010001010001000100000101010101
1010111111101010111011101111101111101011101
1000100000001010101010001000100010101000101
1011111011111010101010111010111010101011101
1010000010001000101010000010001010001000001
1010101110101111101011101111101011111010101
1010101000101000001000101000001000000010101
1011101011111010111110111011101111111110111
1000001000000010000000000010000000000010021
1111111111111111111111111111111111111111111
Next the main program, the one that creates the model, the view, and the controller, hooks them all together, and then displays the GUI:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
* link: http://stackoverflow.com/a/41418250/522444
*
* #author Pete
*
*/
#SuppressWarnings("serial")
public class Main2 extends JPanel {
private View mainPanel;
public Main2(MatrixModel matrixModel) {
mainPanel = new View(matrixModel);
new Controller(matrixModel, mainPanel);
setLayout(new BorderLayout());
add(mainPanel, BorderLayout.CENTER);
}
private static void createAndShowGui(MatrixModel model) {
Main2 mainPanel = new Main2(model);
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
final MatrixModel model = MatrixUtil.getInput(MatrixUtil.PATH_TO_RSC);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui(model);
}
});
}
}
Next a utility class with static methods for reading in the text file as a resource and converting it into a Model object:
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MatrixUtil {
// again this text file must be in the jar file or the code base
// at the same location as the class / java files
public static final String PATH_TO_RSC = "input.txt";
public static MatrixModel getInput(String resourcePath) {
InputStream is = MatrixUtil.class.getResourceAsStream(resourcePath);
if (is == null) {
String text = "resourcePath is not found and not loading text: " + resourcePath;
throw new IllegalArgumentException(text);
}
return getInput(is);
}
public static MatrixModel getInput(InputStream is) {
MatrixModel model = null;
try (Scanner scan = new Scanner(is)) {
List<List<MatrixPosition>> listOfLists = new ArrayList<>();
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (line.trim().isEmpty()) {
continue;
}
List<MatrixPosition> list = new ArrayList<>();
for (char c : line.toCharArray()) {
list.add(MatrixPosition.getMatrixPosition(String.valueOf(c)));
}
listOfLists.add(list);
}
MatrixPosition[][] grid = new MatrixPosition[listOfLists.size()][];
for (int i = 0; i < grid.length; i++) {
List<MatrixPosition> list = listOfLists.get(i);
grid[i] = list.toArray(new MatrixPosition[] {});
}
model = new MatrixModel(grid, new SpritePosition(1, 1));
}
return model;
}
}
Basic enum to represent direction:
public enum Direction {
UP, DOWN, LEFT, RIGHT
}
Another enum to represent a location point in the grid, and whether it is a wall, a coridor or the end as well as static methods to convert from number to MatrixPosition:
public enum MatrixPosition {
WALL(1), CORRIDOR(0), END(2);
private int value;
private MatrixPosition(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static MatrixPosition getMatrixPosition(int value) {
for (MatrixPosition position : MatrixPosition.values()) {
if (value == position.getValue()) {
return position;
}
}
String text = "value of " + value;
throw new IllegalArgumentException(text);
}
public static MatrixPosition getMatrixPosition(String strValue) {
int value = -1;
try {
value = Integer.parseInt(strValue);
} catch (NumberFormatException e) {
String text = "NumberFormatException for strValue " + strValue;
throw new IllegalAccessError(text);
}
return getMatrixPosition(value);
}
}
A class to represent a position of our sprite, similar to the java.awt.Point class but with row and column fields instead of x and y:
public class SpritePosition {
int row;
int column;
public SpritePosition(int row, int column) {
this.row = row;
this.column = column;
}
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
public void setRowColumn(int row, int column) {
this.row = row;
this.column = column;
}
}
The model has property change support code so that it can notify any classes listening to it of any changes in its state. The controller will be the class listening to the model
import java.beans.PropertyChangeListener;
import javax.swing.event.SwingPropertyChangeSupport;
public class MatrixModel {
public static final String SPRITE_POINT = "sprite point";
private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport(this);
private MatrixPosition[][] grid;
private SpritePosition spritePosition;
public MatrixModel(MatrixPosition[][] grid, SpritePosition spritePosition) {
this.grid = grid;
this.spritePosition = spritePosition;
}
public int getRows() {
return grid.length;
}
public int getColumns() {
return grid[0].length;
}
public MatrixPosition getPosition(SpritePosition p) {
return getPosition(p.row, p.column);
}
public MatrixPosition getPosition(int row, int col) {
return grid[row][col];
}
public void setSpritePoint(SpritePosition spritePosition) {
SpritePosition oldValue = this.spritePosition;
SpritePosition newValue = spritePosition;
this.spritePosition = spritePosition;
pcSupport.firePropertyChange(SPRITE_POINT, oldValue, newValue);
}
public boolean isPointValid(SpritePosition p) {
if (p.column < 0 || p.row < 0) {
return false;
}
if (p.column >= grid[0].length || p.row >= grid.length) {
return false;
}
return grid[p.row][p.column] == MatrixPosition.CORRIDOR;
}
public boolean isMoveValid(Direction direction) {
int row = spritePosition.row;
int column = spritePosition.column;
switch (direction) {
case UP:
return isPointValid(new SpritePosition(row - 1, column));
case DOWN:
return isPointValid(new SpritePosition(row + 1, column));
case LEFT:
return isPointValid(new SpritePosition(row, column - 1));
case RIGHT:
return isPointValid(new SpritePosition(row, column + 1));
default:
return false;
}
}
public void move(Direction direction) {
if (!isMoveValid(direction)) {
String text = "For move to " + direction + "spritePosition: " + spritePosition;
throw new IllegalArgumentException(text);
}
int row = spritePosition.row;
int column = spritePosition.column;
switch (direction) {
case UP:
setSpritePoint(new SpritePosition(row - 1, column));
break;
case DOWN:
setSpritePoint(new SpritePosition(row + 1, column));
break;
case LEFT:
setSpritePoint(new SpritePosition(row, column - 1));
break;
case RIGHT:
setSpritePoint(new SpritePosition(row, column + 1));
break;
default:
break;
}
}
public SpritePosition getSpritePosition() {
return spritePosition;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(listener);
}
public void addPropertyChangeListener(String name, PropertyChangeListener listener) {
pcSupport.addPropertyChangeListener(name, listener);
}
public void removePropertyChangeListener(String name, PropertyChangeListener listener) {
pcSupport.removePropertyChangeListener(name, listener);
}
}
Controller class, one that sets up key bindings on the view so that it can listen for key presses, checks if they represent a valid move, and if so then tells the model to make the move. It also adds a listener to the model so that when its state changes, it will tell the view to move the sprite
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.EnumMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
public class Controller {
private MatrixModel model;
private View view;
private Map<Direction, KeyStroke> dirKeyMap = new EnumMap<>(Direction.class);
public Controller(MatrixModel model, View view) {
this.model = model;
this.view = view;
dirKeyMap.put(Direction.DOWN, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0));
dirKeyMap.put(Direction.UP, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0));
dirKeyMap.put(Direction.LEFT, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
dirKeyMap.put(Direction.RIGHT, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
model.addPropertyChangeListener(new ModelListener());
setUpKeyBindings(view);
}
private void setUpKeyBindings(View view) {
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = view.getInputMap(condition);
ActionMap actionMap = view.getActionMap();
for (Direction dir : Direction.values()) {
KeyStroke keyStroke = dirKeyMap.get(dir);
hookUp(inputMap, actionMap, dir, keyStroke);
}
}
private void hookUp(InputMap inputMap, ActionMap actionMap, Direction dir, KeyStroke key) {
inputMap.put(key, key.toString());
actionMap.put(key.toString(), new MoveAction(dir, model));
}
public MatrixModel getModel() {
return model;
}
public View getView() {
return view;
}
class ModelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (MatrixModel.SPRITE_POINT.equals(evt.getPropertyName())) {
SpritePosition p = model.getSpritePosition();
view.setSpritePoint(p);
}
}
}
}
#SuppressWarnings("serial")
class MoveAction extends AbstractAction {
private Direction dir;
private MatrixModel model;
public MoveAction(Direction dir, MatrixModel model) {
super(dir.toString());
this.dir = dir;
this.model = model;
}
public void actionPerformed(ActionEvent e) {
if (model.isMoveValid(dir)) {
model.move(dir);
}
}
}
Finally the View class, that extends JPanel, that displays the maze and the sprite:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class View extends JPanel {
private static final int CELL_WIDTH = 20;
private static final Color CORRIDOR_COLOR = Color.LIGHT_GRAY;
private static final Color WALL_COLOR = Color.DARK_GRAY;
private static final Color END_COLOR = Color.ORANGE;
private static final Color SPRITE_COLOR = Color.RED;
private static final int GAP = 1;
private BufferedImage gridImg = null;
private SpritePosition spritePosition;
private JPanel mainPanel = new JPanel();
public View(MatrixModel matrixModel) {
gridImg = createImg(matrixModel);
spritePosition = matrixModel.getSpritePosition();
}
public JPanel getMainPanel() {
return mainPanel;
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || gridImg == null) {
return super.getPreferredSize();
}
int prefW = gridImg.getWidth();
int prefH = gridImg.getHeight();
return new Dimension(prefW, prefH);
}
public void setSpritePoint(SpritePosition spritePosition) {
this.spritePosition = spritePosition;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (gridImg != null) {
g.drawImage(gridImg, 0, 0, this);
}
g.setColor(SPRITE_COLOR);
int y = spritePosition.row * CELL_WIDTH + GAP;
int x = spritePosition.column * CELL_WIDTH + GAP;
g.fillRect(x, y, CELL_WIDTH - 2 * GAP, CELL_WIDTH - 2 * GAP);
}
private BufferedImage createImg(MatrixModel matrixModel) {
BufferedImage img = null;
if (matrixModel != null && matrixModel.getRows() > 0) {
int w = matrixModel.getColumns() * CELL_WIDTH;
int h = matrixModel.getRows() * CELL_WIDTH;
img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
for (int row = 0; row < matrixModel.getRows(); row++) {
for (int col = 0; col < matrixModel.getColumns(); col++) {
MatrixPosition position = matrixModel.getPosition(row, col);
Color c = null;
switch (position) {
case CORRIDOR:
c = CORRIDOR_COLOR;
break;
case WALL:
c = WALL_COLOR;
break;
case END:
c = END_COLOR;
break;
}
g2.setColor(c);
int x = col * CELL_WIDTH;
int y = row * CELL_WIDTH;
g2.fillRect(x, y, CELL_WIDTH, CELL_WIDTH);
}
}
g2.dispose();
}
return img;
}
}
In Windows 7, and Java 1.7 (or if 1.6, comment-out the two lines indicated), create a NetBeans/Eclipse project named "test" with two classes, Test and DroppableFrame, and paste this code into it. And then run it.
If you run with modal = true, it flickers. If you run with modal = false, it doesn't. What am I doing wrong?
// test.java
package test;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Test implements KeyListener, MouseListener
{
public Test(boolean m_modal)
{
Dimension prefSize;
Insets inset;
Font fontLabel, fontInput, fontButtons;
int buttonCenters, buttonBackoff, buttonWidth, buttonCount, thisButton, buttonTop;
String caption;
JLayeredPane m_pane;
JLabel m_lblBackground;
JScrollPane m_txtInputScroll;
int m_width, m_height, m_actual_width, m_actual_height;
boolean m_singleLineInput = true;
String m_caption = "Sample Modal Input";
m_width = 450;
m_height = m_singleLineInput ? /*single line*/180 : /*multi-line*/250;
m_frame = new DroppableFrame(false);
caption = m_caption;
m_frame.setTitle(caption);
// Compute the actual size we need for our window, so it's properly centered
m_frame.pack();
Insets fi = m_frame.getInsets();
m_actual_width = m_width + fi.left + fi.right;
m_actual_height = m_height + fi.top + fi.bottom;
m_frame.setSize(m_width + fi.left + fi.right,
m_height + fi.top + fi.bottom);
prefSize = new Dimension(m_width + fi.left + fi.right,
m_height + fi.top + fi.bottom);
m_frame.setMinimumSize(prefSize);
m_frame.setPreferredSize(prefSize);
m_frame.setMinimumSize(prefSize);
m_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
m_frame.setSize(m_width, m_height);
m_frame.setLocationRelativeTo(null); // Center window
m_frame.setLayout(null); // We handle all redraws
Container c = m_frame.getContentPane();
c.setBackground(Color.WHITE);
c.setForeground(Color.BLACK);
m_pane = new JLayeredPane();
m_pane.setLayout(null);
m_pane.setBounds(0, 0, m_width, m_height);
m_pane.setVisible(true);
m_pane.setBorder(BorderFactory.createEmptyBorder());
c.add(m_pane);
// Set the background image
m_lblBackground = new JLabel();
m_lblBackground.setBounds(0, 0, m_width, m_height);
m_lblBackground.setHorizontalAlignment(JLabel.LEFT);
m_lblBackground.setVerticalAlignment(JLabel.TOP);
m_lblBackground.setVisible(true);
m_lblBackground.setBackground(Color.WHITE);
m_pane.add(m_lblBackground);
m_pane.moveToFront(m_lblBackground);
// Create the fonts
fontLabel = new Font("Calibri", Font.BOLD, 20);
fontInput = new Font("Calibri", Font.BOLD, 14);
fontButtons = fontLabel;
// Create the visible label contents
JLabel m_lblLabel = new JLabel();
m_lblLabel.setBounds(15, 52, 423, 28);
m_lblLabel.setHorizontalAlignment(JLabel.LEFT);
m_lblLabel.setVerticalAlignment(JLabel.CENTER);
m_lblLabel.setFont(fontLabel);
m_lblLabel.setForeground(Color.BLUE);
m_lblLabel.setText("A sample input:");
m_lblLabel.setVisible(true);
m_pane.add(m_lblLabel);
m_pane.moveToFront(m_lblLabel);
// Create the input box
if (m_singleLineInput)
{ // It's a single-line input box
m_txtInputSingleLine = new JTextField();
m_txtInputSingleLine.setBounds(15, 85, 421, 25);
m_txtInputSingleLine.setFont(fontInput);
m_txtInputSingleLine.setText("Initial Value");
m_txtInputSingleLine.setVisible(true);
m_txtInputSingleLine.addKeyListener(this);
m_pane.add(m_txtInputSingleLine);
m_pane.moveToFront(m_txtInputSingleLine);
} else {
m_txtInput = new JTextArea();
m_txtInputScroll = new JScrollPane(m_txtInput);
m_txtInputScroll.setBounds(15, 83, 421, 100);
m_txtInputScroll.setAutoscrolls(true);
m_txtInputScroll.setVisible(true);
m_txtInput.setFont(fontInput);
m_txtInput.setLineWrap(true);
m_txtInput.setWrapStyleWord(true);
m_txtInput.setTabSize(2);
m_txtInput.setText("Initial Value");
m_txtInput.setVisible(true);
m_pane.add(m_txtInputScroll);
m_pane.moveToFront(m_txtInputScroll);
}
// Determine which buttons are specified
buttonCount = 0;
m_buttons = _CANCEL_BUTTON + _OKAY_BUTTON;
if ((m_buttons & _NEXT_BUTTON) != 0)
{
m_btnNext = new JButton("Next");
m_btnNext.setFont(fontButtons);
m_btnNext.addMouseListener(this);
inset = m_btnNext.getInsets();
inset.left = 3;
inset.right = 3;
m_btnNext.setMargin(inset);
m_pane.add(m_btnNext);
m_pane.moveToFront(m_btnNext);
++buttonCount;
}
if ((m_buttons & _CANCEL_BUTTON) != 0)
{
m_btnCancel = new JButton("Cancel");
m_btnCancel.setFont(fontButtons);
m_btnCancel.addMouseListener(this);
inset = m_btnCancel.getInsets();
inset.left = 3;
inset.right = 3;
m_btnCancel.setMargin(inset);
m_pane.add(m_btnCancel);
m_pane.moveToFront(m_btnCancel);
++buttonCount;
}
if ((m_buttons & _ACCEPT_BUTTON) != 0)
{
m_btnAccept = new JButton("Accept");
m_btnAccept.setFont(fontButtons);
m_btnAccept.addMouseListener(this);
inset = m_btnAccept.getInsets();
inset.left = 3;
inset.right = 3;
m_btnAccept.setMargin(inset);
m_pane.add(m_btnAccept);
m_pane.moveToFront(m_btnAccept);
++buttonCount;
}
if ((m_buttons & _OKAY_BUTTON) != 0)
{
m_btnOkay = new JButton("Okay");
m_btnOkay.setFont(fontButtons);
m_btnOkay.addMouseListener(this);
inset = m_btnOkay.getInsets();
inset.left = 3;
inset.right = 3;
m_btnOkay.setMargin(inset);
m_pane.add(m_btnOkay);
m_pane.moveToFront(m_btnOkay);
++buttonCount;
}
// Determine the coordinates for each button
buttonCenters = (m_width / (buttonCount + 1));
buttonWidth = (int)((double)buttonCenters * 0.80);
buttonBackoff = (m_width / (buttonCount + 2)) / 2;
// Position the buttons
thisButton = 1;
buttonTop = m_singleLineInput ? 130 : 200;
if (m_btnNext != null)
{ // Position and make visible this button
m_btnNext.setBounds( + (thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnNext.setVisible(true);
++thisButton;
}
if (m_btnCancel != null)
{ // Position and make visible this button
m_btnCancel.setBounds((thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnCancel.setVisible(true);
++thisButton;
}
if (m_btnAccept!= null)
{ // Position and make visible this button
m_btnAccept.setBounds((thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnAccept.setVisible(true);
++thisButton;
}
if (m_btnOkay != null)
{ // Position and make visible this button
m_btnOkay.setBounds((thisButton * buttonCenters) - buttonBackoff, buttonTop, buttonWidth, 40);
m_btnOkay.setVisible(true);
++thisButton;
}
// The modal code causes some slow component rendering.
// Needs looked at to figure out why
if (m_modal)
{ // Make it a modal window
m_frame.setModal(m_width, m_height, fi, m_pane);
} else {
// Make it a non-modal window
m_frame.setVisible(true);
m_frame.forceWindowToHaveFocus();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
m_frame.dispose();
System.exit(0);
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args)
{
boolean modal = true;
Test t = new Test(modal);
}
private DroppableFrame m_frame;
private int m_buttons;
private JTextField m_txtInputSingleLine;
private JTextArea m_txtInput;
private JButton m_btnNext;
private JButton m_btnCancel;
private JButton m_btnAccept;
private JButton m_btnOkay;
public static final int _NEXT_BUTTON = 1;
public static final int _CANCEL_BUTTON = 2;
public static final int _ACCEPT_BUTTON = 4;
public static final int _OKAY_BUTTON = 8;
public static final int _NEXT_CANCEL = 3;
public static final int _ACCEPT_CANCEL = 6;
public static final int _OKAY_CANCEL = 10;
}
// DroppableFrame.java
package test;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.io.*;
import java.util.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import java.awt.event.ComponentListener;
import java.awt.event.InputEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.*;
public class DroppableFrame extends JFrame
implements DropTargetListener,
DragSourceListener,
DragGestureListener,
ComponentListener
{
public DroppableFrame(boolean isResizeable)
{
super("JFrame");
m_dragSource = DragSource.getDefaultDragSource();
m_dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
this.setDropTarget(new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this));
addComponentListener(this);
m_isResizeable = isResizeable;
m_modal = false;
setResizable(isResizeable);
}
/**
* Sets the frame to a modal state
* #param width
* #param height
*/
public void setModal(int width,
int height,
Insets fi,
JLayeredPane m_pan)
{
int i;
Component[] comps;
Component c;
Point p;
m_modal = true;
m_modalDialog = new Dialog((JFrame)null, getTitle(), true);
m_modalDialog.setLayout(null);
m_modalDialog.setResizable(m_isResizeable);
m_modalDialog.setSize(width + fi.left + fi.right, height + fi.top + (fi.bottom * 2));
m_modalDialog.setAlwaysOnTop(true);
m_modalDialog.setLocationRelativeTo(null);
if (m_pan != null)
{ // Add/copy the pane's components
comps = m_pan.getComponents();
if (comps != null)
for (i = 0; i < comps.length; i++)
{ // Add and reposition the component taking into account the insets
c = m_modalDialog.add(comps[i]);
p = c.getLocation();
c.setLocation(p.x + fi.left, p.y + fi.top + fi.bottom);
}
}
m_modalDialog.setVisible(true);
}
#Override
public void paint(Graphics g)
{
Dimension d = getSize();
Dimension m = getMaximumSize();
boolean resize = d.width > m.width || d.height > m.height;
d.width = Math.min(m.width, d.width);
d.height = Math.min(m.height, d.height);
if (resize)
{
Point p = getLocation();
setVisible(false);
setSize(d);
setLocation(p);
setVisible(true);
}
super.paint(g);
}
#Override
public void dragDropEnd(DragSourceDropEvent DragSourceDropEvent){}
#Override
public void dragEnter(DragSourceDragEvent DragSourceDragEvent){}
#Override
public void dragExit(DragSourceEvent DragSourceEvent){}
#Override
public void dragOver(DragSourceDragEvent DragSourceDragEvent){}
#Override
public void dropActionChanged(DragSourceDragEvent DragSourceDragEvent){}
#Override
public void dragEnter (DropTargetDragEvent dropTargetDragEvent)
{
dropTargetDragEvent.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
#Override
public void dragExit (DropTargetEvent dropTargetEvent) {}
#Override
public void dragOver (DropTargetDragEvent dropTargetDragEvent) {}
#Override
public void dropActionChanged (DropTargetDragEvent dropTargetDragEvent){}
#Override
public synchronized void drop(DropTargetDropEvent dropTargetDropEvent)
{
try
{
Transferable tr = dropTargetDropEvent.getTransferable();
if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
{
dropTargetDropEvent.acceptDrop (DnDConstants.ACTION_COPY_OR_MOVE);
java.util.List fileList = (java.util.List)tr.getTransferData(DataFlavor.javaFileListFlavor);
Iterator iterator = fileList.iterator();
while (iterator.hasNext())
{
File file = (File)iterator.next();
if (file.getName().toLowerCase().endsWith(".xml"))
{ // Do something with the file here
} else {
System.out.println("Ignored dropped file: " + file.getAbsolutePath());
}
}
dropTargetDropEvent.getDropTargetContext().dropComplete(true);
} else {
dropTargetDropEvent.rejectDrop();
}
} catch (IOException io) {
dropTargetDropEvent.rejectDrop();
} catch (UnsupportedFlavorException ufe) {
dropTargetDropEvent.rejectDrop();
}
}
#Override
public void dragGestureRecognized(DragGestureEvent dragGestureEvent)
{
}
public void setTranslucency(float opaquePercent)
{
try
{
if (System.getProperty("java.version").substring(0,3).compareTo("1.6") <= 0)
{ // Code for translucency works in 1.6, raises exception in 1.7
Class awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
Method mSetWindowOpacity;
mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
if (mSetWindowOpacity != null)
{
if (!m_modal)
mSetWindowOpacity.invoke(null, this, opaquePercent);
}
} else {
// If compiling in 1.6 or earlier, comment-out these next two lines
if (!m_modal)
setOpacity(opaquePercent);
}
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) {
} catch (ClassNotFoundException ex) {
} catch (IllegalAccessException ex) {
} catch (IllegalArgumentException ex) {
} catch (InvocationTargetException ex) {
} catch (IllegalComponentStateException ex) {
} catch (Throwable t) {
} finally {
}
}
#Override
public void componentResized(ComponentEvent e)
{
Dimension d = getSize();
Dimension m = getMaximumSize();
boolean resize = d.width > m.width || d.height > m.height;
d.width = Math.min(m.width, d.width);
d.height = Math.min(m.height, d.height);
if (resize)
setSize(d);
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
#Override
public void dispose()
{
if (m_modal)
{
m_modalDialog.setVisible(false);
m_modalDialog = null;
}
super.dispose();
}
public void forceWindowToHaveFocus()
{
Rectangle bounds;
Insets insets;
Robot robot = null;
if (m_modal)
m_modalDialog.setVisible(true);
setVisible(true);
toFront();
bounds = getBounds();
insets = getInsets();
try {
robot = new Robot();
robot.mouseMove(bounds.x + bounds.width / 2, bounds.y + insets.top / 2);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (AWTException ex) {
}
}
protected DragSource m_dragSource;
protected boolean m_isResizeable;
protected boolean m_modal;
protected Dialog m_modalDialog;
}
Looks like you're adding Swing components to an AWT Dialog. This will definitely cause problems. Using JDialog seems to remove the flickering.