Java Jung draw ovals - java

i am using jung (java) try to draw circles to the Background. I dont get any output and wondering why it is not working.
Iam using PreRenderPaintable and PostRenderPaintable but still get no results.
vv.addPreRenderPaintable(new VisualizationViewer.Paintable() {
public void paint(Graphics g)
{
System.out.println("PRE RENDER");
System.out.println("vv.getComponentCount()= " + vv.getComponentCount());
Graphics2D g2d = (Graphics2D)g;
AffineTransform oldXform = g2d.getTransform();
AffineTransform lat = vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).getTransform();
AffineTransform vat = vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).getTransform();
AffineTransform at = new AffineTransform();
at.concatenate(g2d.getTransform());
at.concatenate(vat);
at.concatenate(lat);
g2d.setTransform(at);
g.drawOval(100, 100, 150, 150);
g.drawString("adsadd", 200, 200);
g2d.setTransform(oldXform);
}
public boolean useTransform() { return false; }
});
vv.addPostRenderPaintable(new VisualizationViewer.Paintable()
{
public void paint(Graphics g)
{
System.out.println("POST RENDER");
System.out.println("vv.getComponentCount()= " + vv.getComponentCount());
Component comp = vv.getComponent(0);
System.out.println(comp);
System.out.println(comp.getClass());
g.drawString("adasasdsadasdsadsadasdasdsadd", 300, 300);
}
public boolean useTransform()
{
return false;
}
});

The Problem was not setting the color of the output.
For Example:
g.setFont(font);
Color oldColor = g.getColor();
g.setColor(Color.lightGray);

Related

How to Load an Image object in Java

I am getting input==null while trying to load an Image. I can't seem to figure out why, even after browsing a good number of StackOverflow questions. It looks right to me.
Here is the code:
private BufferedImage image;
public practice(){
setLayout(new BorderLayout());
timeBall.start();
JPanel panelNorth = makePanel();
panelNorth.setBackground(Color.CYAN);
add(panelNorth, BorderLayout.NORTH);
try{
image = ImageIO.read(practice.class.getResource("/pics/flying.png"));
}catch(IOException e){
e.printStackTrace();
}
}
public Dimension getPreferredSize() {
return image == null ? new Dimension(400, 300): new Dimension(image.getWidth(), image.getHeight());
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLUE);
ellipse = new Ellipse2D.Double(Ox, Oy+Speedy, height, height);
Graphics2D graphics = (Graphics2D)g;
g.drawImage(image, 0, 0, this);
graphics.fill(ellipse);
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
Oy = Oy + Speedy / 10;
Ox = Ox + Speedx / 10;
}

Stable Line Custom Component

I used following code to create a custom component to draw edges of graphs, but the component has weird behaviors. sometimes it appear right, but sometimes it doesn't appear.
I looked other custom component samples but couldn't find where is the problem.
So the question is where is the problem?
public class EdgeLine extends JPanel
{
private static final long serialVersionUID = -5820537358240087280L;
public final Edge edge;
private int cHeight;
private int cWidth;
private Line2D line;
public EdgeLine(Edge edge)
{
Point firstLocation = edge.firstVertex.location;
Point secondLocation = edge.secondVertex.location;
this.edge = edge;
cWidth = Math.abs(firstLocation.y - secondLocation.y);
cHeight = Math.abs(firstLocation.x - secondLocation.x);
setSize(cHeight, cWidth);
this.setBackground(new Color(0, 0, 0, 0));
int xPoint = Math.min(firstLocation.x, secondLocation.x);
int yPoint = Math.min(firstLocation.y, secondLocation.y);
setLocation(new java.awt.Point(xPoint, yPoint));
line = new Line2D.Float(firstLocation.x - xPoint, firstLocation.y - yPoint
, secondLocation.x - xPoint, secondLocation.y - yPoint);
}
private void drawLine(Graphics2D graphic)
{
graphic = (Graphics2D) getGraphics();
graphic.setStroke(new BasicStroke(6));
graphic.setColor(Color.ORANGE);
graphic.draw(line);
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (isOpaque())
{ //paint background
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
Graphics2D graphic = (Graphics2D) g.create();
drawLine(graphic);
graphic.dispose();
}
#Override
public Dimension getPreferredSize()
{
Dimension dim = new Dimension(cHeight, cWidth);
return dim;
}
}

rotate an Ellipse2D object

I'm trying to rotate one whole Ellipse2D object based on user key input. If the user presses the right key, rotate right and left key means rotate left. The rotAngle is set to 25. I made a separate drawRotEllipse because otherwise it would have always drawn the original one. I think my confusion is happening with the Graphics and Shapes Objects. Tried the AffineTransform business but that didn't work out either. I just want it to rotate about the center. Thanks for any help!
class Canvas extends JPanel implements java.io.Serializable{
int x1 = (int) (this.getWidth()/2)+100;
int y1 = (int) (this.getHeight()/2)+20;
int x2 = (int) this.getWidth()+100;
int y2 = (int) this.getHeight()+200;
#Override
public void paintComponent(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.RED);
drawEllipse(g);
}
public void drawEllipse (Graphics g){
Graphics2D g2d = (Graphics2D) g;
myShape = new Ellipse2D.Double(x1,y1,x2,y2);
g2d.draw(myShape);
this.repaint();
}
public void drawRotEllipse (Graphics g){
g2d.draw(myShape);
this.repaint();
}
}
private void jPanel1KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode()==39){
g2d.rotate(Math.toDegrees(rotAngle));
myCanvas.drawRotEllipse(g2d);
}
else if (evt.getKeyCode()==37){
g2d.rotate(Math.toDegrees(-rotAngle));
myCanvas.drawRotEllipse(g2d);
}
}
if (evt.getKeyCode()==39)
Don't use magic numbers. People don't know that means by just looking at the code.
Instead use variable provided by the API:
if (evt.getKeyCode() == KeyEvent.VK_RIGHT)
You KeyEvent code should not do the actual painting. All the code should do is set the "degrees" property of your class. The setDegrees(...) method will then be responsible for invoking repaint(). Now whenever the component is repainted the shape will be painted at its current degrees of rotation.
Here is an example that uses a JSlider to change the rotation degrees of the class.
It rotates an image. You should be able to change the code rotation the image to just draw your shape:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
public class Rotation2 extends JPanel
{
BufferedImage image;
int degrees;
int point = 250;
public Rotation2(BufferedImage image)
{
this.image = image;
setDegrees( 0 );
setPreferredSize( new Dimension(600, 600) );
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g.create();
double radians = Math.toRadians( degrees );
g2.translate(point, point);
g2.rotate(radians);
g2.translate(-image.getWidth(this) / 2, -image.getHeight(this) / 2);
g2.drawImage(image, 0, 0, null);
g2.dispose();
g.setColor(Color.RED);
g.fillOval(point - 5, point - 5, 10, 10);
}
public void setDegrees(int degrees)
{
this.degrees = degrees;
repaint();
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
// String path = "mong.jpg";
String path = "dukewavered.gif";
ClassLoader cl = Rotation2.class.getClassLoader();
BufferedImage bi = ImageIO.read(cl.getResourceAsStream(path));
final Rotation2 r = new Rotation2(bi);
final JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
int value = slider.getValue();
r.setDegrees( value );
}
});
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(r));
f.add(slider, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
catch(IOException e)
{
System.out.println(e);
}
}
});
}
}

How do I fill the remaining portions in the button?

I have been trying the round button but there is a problem here. Currently I am getting a button like this :
What I want to do is fill the remaining portions in the button square. How do I do this ? This is the code that painted this button.
import javax.swing.*;
import java.awt.*;
class Tester extends JButton {
public Tester(String label) {
super(label);
setContentAreaFilled(false);
Dimension size = this.getPreferredSize();
size.width = size.height = Math.max(size.width,size.height);
this.setPreferredSize(size);
}
#Override
public void paintComponent(Graphics g) {System.out.println("Inside the paintComponent method");
if (getModel().isArmed()) {
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0,0,getSize().width-1,getSize().height-1);
System.out.println(getSize().width);
System.out.println(getSize().height);
super.paintComponent(g);
}
public static void main(String args[]) {
JFrame fr = new JFrame();
JPanel p = new JPanel();
JButton button = new Tester("Click Me !");
button.setBackground(Color.GREEN);
p.add(button);
fr.add(p);
fr.setVisible(true);
fr.setSize(400,400);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
How do I fill the remaining portions in the button ?
You can just use the fillrect() method to fill the remaining portion before you call fillOval()
#Override
public void paintComponent(Graphics g) {
System.out.println("Inside the paintComponent method");
g.setColor(Color.red); // here
g.fillRect(0, 0, this.getWidth(), this.getHeight()); //here
if (getModel().isArmed()) {
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);
System.out.println(getSize().width);
System.out.println(getSize().height);
super.paintComponent(g);
}
Doing like above I'll get
Hope this helps.
Simply use something like Graphics#fillRect to fill a rectangular area
public void paintComponent(Graphics g) {
System.out.println("Inside the paintComponent method");
// Or what ever background color you want...
g.setColor(Color.RED);
g.fillRect(0, 0, getWidth(), getHeight());
if (getModel().isArmed()) {
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0,0,getSize().width-1,getSize().height-1);
System.out.println(getSize().width);
System.out.println(getSize().height);
super.paintComponent(g);
}

How to draw a Round rectangle in java with normal rectangle outline

For my java application i need a Round rectangle with an outline that looks like a normal rectangle, like this
I know you can do that by drawing a normal rectangle and a RoundRect inside it but i don't want to draw a RoundRect inside it because I want to draw something else in it.
So a round rect with normal corners. How do I draw that in Java?
The problem is that the rectangle looks like this if I use layers:
The corners are filled up with the wrong color. How do I prevent that?
I can think of two approaches. The first is to generate a Shape that represents the square outter edge and the rounded inner edge.
The second would be to use a AlphaComposite to generate a masked result.
public class TestMask {
public static void main(String[] args) {
new TestMask();
}
public TestMask() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MaskedPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MaskedPane extends JPanel {
public MaskedPane() {
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage outter = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = outter.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
BufferedImage inner = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
g2d = inner.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fillRoundRect(10, 10, getWidth() - 20, getHeight() - 20, 20, 20);
g2d.dispose();
BufferedImage masked = applyMask(outter, inner, AlphaComposite.DST_OUT);
g.drawImage(masked, 0, 0, this);
}
public BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) {
BufferedImage maskedImage = null;
if (sourceImage != null) {
int width = maskImage.getWidth();
int height = maskImage.getHeight();
maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D mg = maskedImage.createGraphics();
int x = (width - sourceImage.getWidth()) / 2;
int y = (height - sourceImage.getHeight()) / 2;
mg.drawImage(sourceImage, x, y, null);
mg.setComposite(AlphaComposite.getInstance(method));
mg.drawImage(maskImage, 0, 0, null);
mg.dispose();
}
return maskedImage;
}
public BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage) {
return (BufferedImage) applyMask(sourceImage, maskImage, AlphaComposite.DST_IN);
}
}
}
Updated with Shape example
Finally had time to bang one out...
public class TestMask {
public static void main(String[] args) {
new TestMask();
}
public TestMask() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ShapedPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ShapedPane extends JPanel {
public ShapedPane() {
setBackground(Color.GREEN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fill(new RounedFrame(getWidth(), getHeight(), 10, 20));
g2d.dispose();
}
}
public class RounedFrame extends Path2D.Float {
public RounedFrame(float width, float height, float thickness, float radius) {
moveTo(0, 0);
lineTo(width, 0);
lineTo(width, height);
lineTo(0, height);
lineTo(0, 0);
float innerWidth = width - thickness;
float innerHeight = height - thickness;
moveTo(thickness + radius, thickness);
lineTo(innerWidth - radius, thickness);
curveTo(innerWidth, thickness, innerWidth, thickness, innerWidth, thickness + radius);
lineTo(innerWidth, innerHeight - radius);
curveTo(innerWidth, innerHeight, innerWidth, innerHeight, innerWidth - radius, innerHeight);
lineTo(thickness + radius, innerHeight);
curveTo(thickness, innerHeight, thickness, innerHeight, thickness, innerHeight - radius);
lineTo(thickness, thickness + radius);
curveTo(thickness, thickness, thickness, thickness, thickness + radius, thickness);
closePath();
setWindingRule(WIND_EVEN_ODD);
}
}
}
Updated
From a comment by Andrew, you could simplify the use of the shape example by using Area
You could replace the paintComponent from the above example with this one...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Area area = new Area(new Rectangle(0, 0, getWidth(), getHeight()));
area.subtract(new Area(new RoundRectangle2D.Float(10, 10, getWidth() - 20, getHeight() - 20, 20, 20)));
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fill(area);
g2d.dispose();
}
Which is much simpler :D
Something like:
paintComponent(Graphics g) {
//If you want more: Graphics2D g2 = (Graphics2D) g;
Rect rect = getBounds();
g.setColor(Color.BLACK);
g.fillRect(rect.x, rect,y, rect.width, rect.height);
rect.grow(-4, -4);
g.setColor(getBackground());
g.fillRoundRect(rect.x, rect,y, rect.width, rect.height, 5, 5);
}
E.G.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
class CustomBorderWithContent {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
int w = 200;
int h = 100;
int pad = 4;
BufferedImage img = new BufferedImage(
w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Ripped/adapted from Joop's answer
g.setColor(Color.BLACK);
g.fillRect(0, 0, w, h);
g.setColor(Color.ORANGE);
g.fillRoundRect(pad, pad, w-2*pad, h-2*pad, 25, 25);
// Now..
g.setColor(Color.BLUE);
g.drawString("Something else..", 20, 25);
g.dispose();
JOptionPane.showMessageDialog(
null, new JLabel(new ImageIcon(img)));
}
};
SwingUtilities.invokeLater(r);
}
}

Categories

Resources