Java - opaque color - java

i am trying to draw some lines. Problem is about colors. For example. I have several lines of red color, and than i draw one line of blue color (or reversed). And sometimes, that lines those is more, is opaque for that last one.
I tried to make new color and set color with alpha composite 0.7 - for those more lines, and one color i left default - opaque (alpha 1.0). At first i draw more lines, and than last one. But that lines "overwrite" that one. Is there some solution to fix this problem?
I draw that lines on glasspane.
edit: that code is robust, so it is difficult to post it, and it is one part of thesis.
principle is 2 color for example
Color basicColor;
Color similarColor;
than i have paint method and 2 hashmaps as attributes - some points are stored.
i iterate over this map, remember that one point and similar to him, all other connect with
graphics2D.drawLine(x1,y1,x2,y2) and than change color and paint last one line with another color. I am modifying stroke too, to make it more significant.
I hope it will be enough...
edit2:
i have some Point similarPoint than some robust paint method and here is graphics modifying
iterator iterate over list of points' lists.
Point similar = null;
Iterator<Point> secondIterator;
graphics.setColor(colorOfSimilar);
while (iterator.hasNext()) {
Point point = iterator.next();
if (point.equals(similarPoint)) {
similar = similarPoint;
} else {
secondIterator = secondMap.get(point).iterator();
while (secondIterator.hasNext()) {
Point secondPoint = secondIterator.next();
graphics2D.drawLine(point.getX(), point.getY(),
secondPoint.getX(), secondPoint.getY());
}
}
}
if (similar != null) {
secondIterator = secondMap.get(similar);
graphics2D.setColor(hooverColor);
graphics2D.setStroke(new BasicStroke(2.5f));
while (secondIterator.hasNext()) {
Point secondPoint = secondIterator.next();
graphics2D.drawLine(similar.getX(), similar.getY(),
secondPoint.getX(), secondPoint.getY());
}
graphics2D.setColor(colorOfSimilar);
graphics2D.setStroke(new BasicStroke(1.0f));
}
i wrote it in notepad so sorry about some mistakes (i think brackets etc.), but this is mechanism of modifying, around that is other methods for iterate and other, but it is not important. Problem with stroke doesn´t exist, because at first i did it without stroke.
Thanks for any idea.

The result depends on which compositing rule is specified in the graphics context using setComposite(). This utility may be useful in understanding the various modes. It may also help you in preparing an sscce that exhibits the problem you describe.
Addendum: Here's an example that shows how one might use AlphaComposite.Src mode for this.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
/** #see http://stackoverflow.com/questions/7823631 */
public class X extends JPanel {
private static final int SIZE = 300;
private static final int INSET = 64;
private static final AlphaComposite OVER_HALF =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
private boolean src;
public X(boolean src) {
this.src = src;
this.setBackground(Color.lightGray);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Line2D line1 = new Line2D.Double(INSET, INSET,
getWidth() - INSET, getHeight() - INSET);
Line2D line2 = new Line2D.Double(getWidth() - INSET,
INSET, INSET, getHeight() - INSET);
g2.setStroke(new BasicStroke(64,
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_BEVEL));
g2.setComposite(OVER_HALF);
g2.setColor(Color.red);
g2.draw(line1);
if (src) {
g2.setComposite(AlphaComposite.Src);
}
g2.setColor(Color.blue);
g2.draw(line2);
}
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(1, 0));
frame.add(new X(false));
frame.add(new X(true));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Related

How to make rounded corners of JTabbedPane in Java Swing

I need make a JTabbedPane like this (I made the image in Photoshop):
But in my look and feel (based on TabbedPaneUI: javax.swing.plaf.basic.BasicTabbedPaneUI) looks like this:
How can I do it?
I’ve tried change LAF properties, but I didn't find a solution.
If I use setBorder method the swing make this:
jtabbedpane1.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1, true));
Java changed only the upper left corner as outer border as image above shows.
I need a solution that might use the Paint method on an extended JTabbedPane class, but I really don't know if this is correct or how do this.
I read the tutorial above and tried override paintComponent method in my extended JTabbedPane class, see:
public class MyTabbedPane extends JTabbedPane {
[...]
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.drawRoundRect(getX()-12, getY()-11, getWidth()-4, getHeight()-22, 6, 6);
}
}
The result:
https://i.imgur.com/YLXkVRS.jpg
Rounded corners are actually a boolean argument when instantiating a border, as can be seen here with BorderFactory.
So what we can do is something like this:
pane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 2, true));
Where "true" refers to rounded corners.
If you are interested in customizing the border further, you will most likely have to paint it yourself, in which case I would look here for a further read.
Edit regarding your code:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.drawPolyLine(new int[]{getX(), getX() getX() + 12}, new int[]{getY() + 12, getY(), getY()});
g.drawPolyLine(.....); // next corner
g.drawPolyLine(.....); // next corner
}
etc. where you repeat for each corner that you want your L shape at.
Here is the start of an answer.
import javax.swing.*;
import java.awt.Dimension;
import javax.swing.plaf.TabbedPaneUI;
import javax.swing.plaf.metal.MetalTabbedPaneUI;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Insets;
public class Bordered{
public static void main(String[] args){
JFrame frame = new JFrame("border check");
JPanel content = new JPanel();
JTabbedPane tabs = new JTabbedPane();
JPanel one = new JPanel();
one.add(new JLabel("first tab"));
one.setOpaque(true);
one.setBackground(Color.WHITE);
JPanel two = new JPanel();
two.add(new JLabel("second tab"));
tabs.add("one", one);
tabs.add("two", two);
tabs.setUI( new MetalTabbedPaneUI(){
#Override
protected void paintContentBorder(Graphics g, int placement, int selectedIndex){
int width = tabPane.getWidth();
int height = tabPane.getHeight();
Insets insets = tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(placement);
int x = insets.left;
int y = insets.top;
int w = width - insets.right - insets.left;
int h = height - insets.top - insets.bottom;
y += calculateTabAreaHeight(placement, runCount, maxTabHeight);
h -= (y - insets.top);
//g.fillRoundRect(x, y, w, h, 5, 5);
}
});
tabs.setPreferredSize(new Dimension(400, 200));
content.add(tabs);
frame.setContentPane(content);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Somethings to note, The inner panel the ones holding the jlabel have square corners. I've shown this by making one white. I've taken some of the boundary code from BasicTabbedPaneUI source code.
They really did not make this easy to manage, but looking at the source for the MetalTabbedPaneUI you can see they draw each border as a line, and it would need to be modified to draw a curve at the ends.

Java Path2D.Double on JPanel are painted with a 'tail'

I have a strange behaviour when drawing a Path2D on a JPanel.
Some of the shapes get kind of a tail as you can see on this screenshot:
When I change the type to Line2D.Double, it is as I'd expect it:
Here's the code that draws the path / line:
Path2D.Double path = new Path2D.Double();
Graphics2D g = (Graphics2D)this.getGraphics();
for(int i=0; i<geom.size(); i++)
{
double x = ddGeom.getX(geom.get(i));
double y = ddGeom.getY(geom.get(i));
if(i==0)
path.moveTo(x-draw_center.x, y-draw_center.y);
path.lineTo(x-draw_center.x, y-draw_center.y);
}
g.draw(path);
Do you have an idea where the 'tails' in Screenshot1 come from? I use SDK Version 6.
Thank you very much for your help
Edit: When changing the code snippet to
if(i==0)
path.moveTo(x-draw_center.x, y-draw_center.y);
else
path.lineTo(x-draw_center.x, y-draw_center.y);
most (maybe 75%) of the tails disappear. Any idea why this happens?
I finally got it. Thanks to HovercraftFullOfEels hint 'strange Stroke' I played around with my strokes.
Original stroke:
BasicStroke stroke = new BasicStroke(2.0f);
Changed to:
BasicStroke stroke = new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL);
With the new Stroke all the 'tails' disappeared. I'm still not understanding why this happens, but if someone has the same problem, this workaround could help.
I'd still be very interested in an explanation for this behaviour.
Thank you for your great help
What you are seeing in your first image looks almost like ''miters''. Miters are a way to draw line joins in a path where the two outer borders of the lines that are joined are extended until they intersect and the enclosing area is filled as well.
Is it possible that your geometry contains consecutive points with almost the same coordinates? The following example exhibits the same problem because of the last two points with have almost identical coordinates.
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setContentPane(new Container() {
#Override
public void paint(Graphics graphics) {
Graphics2D g2 = (Graphics2D) graphics;
g2.setStroke(new BasicStroke(5));
g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
g2.setRenderingHint(KEY_STROKE_CONTROL, VALUE_STROKE_PURE);
Path2D.Double path = new Path2D.Double();
path.moveTo(200, 100);
path.lineTo(100, 100);
path.lineTo(101, 100.3);
g2.draw(path);
}
});
frame.setVisible(true);

How to make smoother gradient background colors

Using GradientPaint for gradient background colors is not always satisfactory, especially in certain sizes. For example this code:
public class TestPanel extends JPanel {
protected void paintComponent( Graphics g ) {
Graphics2D g2d = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
Color color1 = Color.BLACK;
Color color2 = Color.GRAY;
GradientPaint gp = new GradientPaint(0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
TestPanel panel = new TestPanel();
frame.add(panel);
frame.setSize(200,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
produces the following:
The cyclic version looks even worse than that:
How can I make the gradient look smoother (in both cases)?
EDIT:
It seems that it is (at least partially) a monitor problem. The gradient colors look awful on my netbook (1024 x 600, True Color 32-bit) while they look a lot better on my desktop pc (1280 x 1024, True Color 32-bit). But the results are still not so smooth even with the desktop's monitor.
Both are using Java Version 6 Update 33.
Does that mean that an application should only use gradient backgrounds when it is viewed with higher resolutions?
EDIT 2:
Anyway, for those facing simlar problem or are just interested in this, I think that the only solution for a gradient color to look smoother is just higher resolution (assuming that the monitor is already set to true color of course) - which is not really a solution. Like I said in a comment, I thought that a 1024 x 600 resolution would be sufficient for a simple black-to-gray gradient color but it seems that I was wrong. When the same code is run on a computer with a monitor that supports higher resolution the gradient looks better, like through my desktop's monitor, 1280 x 1024. Unfortunately I dont have an option for better resolution but I believe it would look even smoother. I also noticed that the two images that I uploaded (taken from my netbook) when they are viewed through a better monitor these same images look smoother... so it must be just the resolution.
Since there is no solution I think that the only way to use specific gradient steps that would always look smooth (like black-to-gray, which even that seems to look bad in lower resolutions) is to have the gui program test for resolution on start-up and make the choice to show the appropriate gradient but I'm not sure if it is worth it. And using less gradient steps is just a compromise.
Due to lack of more/better responses, I've accepted the use of pre-dithered images as an answer.
I see your images, but cannot reproduce the banding. Do you have your display set to TrueColor? Are you using a recent Java version? Anyway, the following line might help:
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
EDIT: it seems that dithering is not supported in Java for TrueColor gradients, even if you don't have enough shades of gray... Some ideas:
use some colors
use pre-dithered image files
http://en.wikipedia.org/wiki/Colour_banding
I can see it. I think it's because the panel's size and the number of colors don't match up. One way to make it smoother is to make the panel's size an even multiple of the number of colors in the gradient. It's not perfect, but I don't know a better way.
public class TestPanel extends JPanel {
private static final int scale = 2;
private static final Color c1 = Color.BLACK;
private static final Color c2 = Color.GRAY;
private static final int size = (c2.getRed() - c1.getRed()) * scale;
#Override
public Dimension getPreferredSize() {
return new Dimension(size, size);
}
#Override
protected void paintComponent( Graphics g ) {
Graphics2D g2d = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0, 0, c1, 0, h, c2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Java: how to do double-buffering in Swing?

EDIT TWO
To prevent snarky comments and one-line answers missing the point: IFF it is as simple as calling setDoubleBuffered(true), then how do I get access to the current offline buffer so that I can start messing with the BufferedImage's underlying pixel databuffer?
I took the time to write a running piece of code (which looks kinda fun too) so I'd really appreciate answers actually answering (what a shock ;) my question and explaining what/how this is working instead of one-liners and snarky comments ;)
Here's a working piece of code that bounces a square across a JFrame. I'd like to know about the various ways that can be used to transform this piece of code so that it uses double-buffering.
Note that the way I clear the screen and redraw the square ain't the most efficient but this is really not what this question is about (in a way, it's better for the sake of this example that it is somewhat slow).
Basically, I need to constantly modify a lot pixels in a BufferedImage (as to have some kind of animation) and I don't want to see the visual artifacts due to single-buffering on screen.
I've got a JLabel whose Icon is an ImageIcon wrapping a BufferedImage. I want to modify that BufferedImage.
What has to be done so that this becomes double-buffered?
I understand that somehow "image 1" will be shown while I'll be drawing on "image 2". But then once I'm done drawing on "image 2", how do I "quickly" replace "image 1" by "image 2"?
Is this something I should be doing manually, like, say, by swapping the JLabel's ImageIcon myself?
Should I be always drawing in the same BufferedImage then do a fast 'blit' of that BufferedImage's pixels in the JLabel's ImageIcon's BufferedImage? (I guess no and I don't see how I could "synch" this with the monitor's "vertical blank line" [or equivalent in flat-screen: I mean, to 'synch' without interfering with the moment the monitor itselfs refreshes its pixels, as to prevent shearing]).
What about the "repaint" orders? Am I suppose to trigger these myself? Which/when exactly should I call repaint() or something else?
The most important requirement is that I should be modifying pixels directly in the images's pixel databuffer.
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
public class DemosDoubleBuffering extends JFrame {
private static final int WIDTH = 600;
private static final int HEIGHT = 400;
int xs = 3;
int ys = xs;
int x = 0;
int y = 0;
final int r = 80;
final BufferedImage bi1;
public static void main( final String[] args ) {
final DemosDoubleBuffering frame = new DemosDoubleBuffering();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing( WindowEvent e) {
System.exit(0);
}
});
frame.setSize( WIDTH, HEIGHT );
frame.pack();
frame.setVisible( true );
}
public DemosDoubleBuffering() {
super( "Trying to do double buffering" );
final JLabel jl = new JLabel();
bi1 = new BufferedImage( WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB );
final Thread t = new Thread( new Runnable() {
public void run() {
while ( true ) {
move();
drawSquare( bi1 );
jl.repaint();
try {Thread.sleep(10);} catch (InterruptedException e) {}
}
}
});
t.start();
jl.setIcon( new ImageIcon( bi1 ) );
getContentPane().add( jl );
}
private void drawSquare( final BufferedImage bi ) {
final int[] buf = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData();
for (int i = 0; i < buf.length; i++) {
buf[i] = 0xFFFFFFFF; // clearing all white
}
for (int xx = 0; xx < r; xx++) {
for (int yy = 0; yy < r; yy++) {
buf[WIDTH*(yy+y)+xx+x] = 0xFF000000;
}
}
}
private void move() {
if ( !(x + xs >= 0 && x + xs + r < bi1.getWidth()) ) {
xs = -xs;
}
if ( !(y + ys >= 0 && y + ys + r < bi1.getHeight()) ) {
ys = -ys;
}
x += xs;
y += ys;
}
}
EDIT
This is not for a full-screen Java application, but a regular Java application, running in its own (somewhat small) window.
---- Edited to address per pixel setting ----
The item blow addresses double buffering, but there's also an issue on how to get pixels into a BufferedImage.
If you call
WriteableRaster raster = bi.getRaster()
on the BufferedImage it will return a WriteableRaster. From there you can use
int[] pixels = new int[WIDTH*HEIGHT];
// code to set array elements here
raster.setPixel(0, 0, pixels);
Note that you would probably want to optimize the code to not actually create a new array for each rendering. In addition, you would probably want to optimized the array clearing code to not use a for loop.
Arrays.fill(pixels, 0xFFFFFFFF);
would probably outperform your loop setting the background to white.
---- Edited after response ----
The key is in your original setup of the JFrame and inside the run rendering loop.
First you need to tell SWING to stop Rasterizing whenever it wants to; because, you'll be telling it when you're done drawing to the buffered image you want to swap out in full. Do this with JFrame's
setIgnoreRepaint(true);
Then you'll want to create a buffer strategy. Basically it specifies how many buffers you want to use
createBufferStrategy(2);
Now that you tried to create the buffer strategy, you need to grab the BufferStrategy object as you will need it later to switch buffers.
final BufferStrategy bufferStrategy = getBufferStrategy();
Inside your Thread modify the run() loop to contain:
...
move();
drawSqure(bi1);
Graphics g = bufferStrategy.getDrawGraphics();
g.drawImage(bi1, 0, 0, null);
g.dispose();
bufferStrategy.show();
...
The graphics grabbed from the bufferStrategy will be the off-screen Graphics object, when creating triple buffering, it will be the "next" off-screen Graphics object in a round-robin fashion.
The image and the Graphics context are not related in a containment scenario, and you told Swing you'd do the drawing yourself, so you have to draw the image manually. This is not always a bad thing, as you can specify the buffer flipping when the image is fully drawn (and not before).
Disposing of the graphics object is just a good idea as it helps in garbage collection. Showing the bufferStrategy will flip buffers.
While there might have been a misstep somewhere in the above code, this should get you 90% of the way there. Good luck!
---- Original post follows ----
It might seem silly to refer such a question to a javase tutorial, but have you looked into BufferStrategy and BufferCapatbilites?
The main issue I think you are encountering is that you are fooled by the name of the Image. A BufferedImage has nothing to do with double buffering, it has to do with "buffering the data (typically from disk) in memory." As such, you will need two BufferedImages if you wish to have a "double buffered image"; as it is unwise to alter pixels in image which is being shown (it might cause repainting issues).
In your rendering code, you grab the graphics object. If you set up double buffering according to the tutorial above, this means you will grab (by default) the off-screen Graphics object, and all drawing will be off-screen. Then you draw your image (the right one of course) to the off-screen object. Finally, you tell the strategy to show() the buffer, and it will do the replacement of the Graphics context for you.
Generally we use Canvas class which is suitable for animation in Java. Anyhoo, following is how you achieve double buffering:
class CustomCanvas extends Canvas {
private Image dbImage;
private Graphics dbg;
int x_pos, y_pos;
public CustomCanvas () {
}
public void update (Graphics g) {
// initialize buffer
if (dbImage == null) {
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics ();
}
// clear screen in background
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
// draw elements in background
dbg.setColor (getForeground());
paint (dbg);
// draw image on the screen
g.drawImage (dbImage, 0, 0, this);
}
public void paint (Graphics g)
{
g.setColor (Color.red);
g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
}
}
Now you can update the x_pos and y_pos from a thread, followed by the 'repaint' call on the canvas object. The same technique should work on a JPanel as well.
What you want is basically impossible in windowed mode with Swing. There is no support for raster synchronization for window repaints, this is only available in fullscreen mode (and even then may not be supported by all platforms).
Swing components are double-buffered by default, that is they will do all the rendering to an intermediate buffer and that buffer is then finally copied to the screen, avoiding flicker from background clearing and then painting on top of it.
And thats the only strategy that is reasonable well supported on all underlying platforms. It avoids only repaint flickering, but not visual tearing from moving graphic elements.
A reasonably simple way of having access to the raw pixels of an area fully under you control would be to extend a custom component from JComponent and overwrite its paintComponent()-method to paint the area from a BufferedImage (from memory):
public class PixelBufferComponent extends JComponent {
private BufferedImage bufferImage;
public PixelBufferComponent(int width, int height) {
bufferImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
setPreferredSize(new Dimension(width, height));
}
public void paintComponent(Graphics g) {
g.drawImage(bufferImage, 0, 0, null);
}
}
You can then manipulate you buffered image whichever way you desire. To get your changes made visible on screen, simply call repaint() on it. If you do the pixel manipulation from a thread other than the EDT, you need TWO buffered images to cope with race conditions between the actual repaint and your manipulation thread.
Note that this skeleton will not paint the entire area of the component when used with a layout manager that stretches the component beyond its preferred size.
Note also, the buffered image approach mostly only makes sense if you do real low level pixel manipulation via setRGB(...) on the image or if you directly access the underlying DataBuffer directly. If you can do all the manipulations using Graphics2D's methods, you could do all the stuff in the paintComponent method using the provided graphics (which is actually a Graphics2D and can be simply casted).
Here's a variation in which all drawing takes place on the event dispatch thread.
Addendum:
Basically, I need to constantly modify a lot pixels in a BufferedImage…
This kinetic model illustrates several approaches to pixel animation.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.image.BufferedImage;
/** #see http://stackoverflow.com/questions/4430356 */
public class DemosDoubleBuffering extends JPanel implements ActionListener {
private static final int W = 600;
private static final int H = 400;
private static final int r = 80;
private int xs = 3;
private int ys = xs;
private int x = 0;
private int y = 0;
private final BufferedImage bi;
private final JLabel jl = new JLabel();
private final Timer t = new Timer(10, this);
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DemosDoubleBuffering());
frame.pack();
frame.setVisible(true);
}
});
}
public DemosDoubleBuffering() {
super(true);
this.setLayout(new GridLayout());
this.setPreferredSize(new Dimension(W, H));
bi = new BufferedImage(W, H, BufferedImage.TYPE_INT_ARGB);
jl.setIcon(new ImageIcon(bi));
this.add(jl);
t.start();
}
#Override
public void actionPerformed(ActionEvent e) {
move();
drawSquare(bi);
jl.repaint();
}
private void drawSquare(final BufferedImage bi) {
Graphics2D g = bi.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, W, H);
g.setColor(Color.blue);
g.fillRect(x, y, r, r);
g.dispose();
}
private void move() {
if (!(x + xs >= 0 && x + xs + r < bi.getWidth())) {
xs = -xs;
}
if (!(y + ys >= 0 && y + ys + r < bi.getHeight())) {
ys = -ys;
}
x += xs;
y += ys;
}
}

How to draw 'biohazard' with swing

I'm practicing my swing abilities for the upcoming test, and fried gave me idea to draw biohazard sign like this :
alt text http://img62.imageshack.us/img62/8372/lab6b.gif
I could draw the circles with Elipse2D, but then I somehow need to cut those 3 triangles. Any ideas how I can do that ?
You can use Java2D and canvas for this. The things that you may be using are, Circle and Arc. You should have three arcs with 30 degrees.
I tried using simple graphics over the frame.
Here is an attempt
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Biohazard {
public static void main(String[] args) {
new Biohazard();
}
public Biohazard() {
JFrame frame = new JFrame("Biohazard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyComponent());
frame.setSize(260, 280);
frame.setVisible(true);
}
public class MyComponent extends JComponent {
public void paint(Graphics g) {
int height = 120;
int width = 120;
g.setColor(Color.yellow);
g.fillOval(60, 60, height, width);
g.setColor(Color.black);
g.drawOval(60, 60, height, width);
int swivels = 6;
int commonx, commony, commonh, commonw;
for(int i=0;i<swivels;i++){
commonx = commony = 120-i*10;
commonh = commonw = i*20;
g.drawArc(commonx, commony, commonh, commonw, 60 , 60);
g.drawArc(commonx, commony, commonh, commonw, 180 , 60);
g.drawArc(commonx, commony, commonh, commonw, 300 , 60);
}
}
}
}
The original one : source code can be found at http://pastebin.com/HSNFx7Gq
You can use the Arc2D class to draw each line by specifying the start and extent parameters in degrees.
Maybe this is actually quite easy (I'm not sure how the Swing API handles lines). Draw lines coming out from the center to the points on the circumference of a circle, and just skip those portions for line drawing.

Categories