Painting Shapes onto JPanels
hi, I'm currently trying to draw shapes in java for the first time. I've been looking at the tutorials and examples for java.sun but I'm having a few problems.
At the moment I have code as follows:
public class drawShape{
public void paintComponent(Graphics g) {
g.drawRect(2,2,2,2);
I want to draw the rectangle onto a form called mainCanvas which is just a normal JPanel. I've been trying but am unsure how to get this working. I've tried mainCanvas.drawRect but that won't work. and in all the examples given on java.sun I can't see what Graphics g is supposed to be?
Hope u can help
The Graphics object gets passed to you. e.g.:
public class MyPanel extends JPanel {
// overriding paintComponent
public void paintComponent(Graphics g) {
g.drawRect(2,2,2,2);
}Then when you add a MyPanel to a frame and make it visible, Swing's rendering system will make sure your paintComponent method gets called.
Similar Messages
-
Shape a JPanel based on the components added
Can I shape the JPanel depending on the components added to it?
Please refer the code I have posted in http://forums.sun.com/thread.jspa?threadID=5323662&messageID=10386358#10386358
My requirement is that, I need to shape the JPanel(mainPanel) such that the icon and label are the borders.
RonyPlease read up on using Layout Managers in the Swing tutorials.
-
Hi guys,
I will start with the original problem and get to the only option that seems possible before hardcoding everything.
I need to draw something like a binary tree. Jtree doesn't fall into binary because it does not have the root in the center. <1;2;6;8;9>, where 6 is the root, and 1,2 are its left child's children and 8,9 are right child's children. Since I couldn't find any possible solution of customizing JTree to draw it in binary format, I am left with the following option that is a step towards hardcoding.
Create a subclass of JPanel and paint inside it. The full hardcode method would be to draw everything right here, ie the lines and the boxes.
But since I need to listen to box selections using mouse, I was hoping to draw the boxes using JPanel/JLabel and override their paint() method.
So is there a way to paint components(JLabel/JPanel and lines) into a painted component (JPanel)? Note, the container JPanel is not using any layout. everything is being drawn using paint method.You are probably going to want to create smaller objects that handle their own painting. For example... Create an extension of JComponent that handles painting a single node. Then create the JPanel to add those to. You can even go as far as writing your own LayoutManager to handle laying the Components out in your binary layout. This is really the most effective way to do it, especially if you want to be able to detect clicks and what not. You can just add MouseListener's to the individual components than.
Hope this helps,
Josh Castagno
http://www.jdc-software.com -
Can Event Handling work in Paint/Shape ( drawline/Rectangle)?
Hi,
I m having rectangle and line in my JPanel.
The question is, can mouseListener work on that things?
for the example, let say i click the rectangle - popup message will appear. Please help me and sample coding will help a lot
TqHi ,
first understand the reply2 it is true.
you can store the information whatever you drawn on the paint method ( like ArrayList , Vecotr , HashMap , Hashtable .... into the Shape co-ordinates and locations some thing like that ) take the MouseEvent to check the mouse position which shape is involved and process it. -
Hi
I am trying to paint several types of swing components onto the g2 of a jpanel. I have been able to do this satisfactorily with most types of jcomponent, however, i am struggling to get a suitable result for jcomboboxs. I cant get it to paint the drop down arrow, it just paints the box with the text in. Below is the code i am using
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class NewJFrame extends JFrame {
public static void main(String args[]){
try {
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
}catch (Exception e) {
e.printStackTrace();
new NewJFrame();
public NewJFrame(){
JPanel panel = new MyPanel();
getContentPane().add(panel);
setSize(300,300);
setVisible(true);
class MyPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.translate(10,10);
JComboBox box = new JComboBox(new String[]{"First"});
box.setSize(100,20);
box.paint(g2);
g2.translate(-10,10);
I would really appreciate any help anyone can give me on sorting this out. Thanks.OK, firstly thanks for the replies. Perhaps I should
have explained what I am trying to achieve. What I
am trying to build is basically something tantermount
to a GUI builder, whereby the user can select a
widget from a tool bar, and place it on a canvas,
they can then select any components they've dragged
out and drag them around the page, resize them,
change thier properties, etc. To do this i have
decided i want to render the components directly to
the g2 of the JPanel. What I am not trying to do is
create a bog standard GUI that you would indeed use a
layout manager(s) for. I have done a pretty
commendable amount of googleing for this, and the
closest thing i can come up with is the Draw app
here, and this is loosely what Ive based my app on.
http://java.sun.com/products/javawebstart/demos.html
I have my program up and running for most of the
e basic widgets, except JComboBoxs. So I will ask
again can anyone
a) Please answer my original question and tell me how
i can render the JComboBox with its arrow.
Or perhaps even more usefully,
b) Point me to a sample app where what I am trying to
achieve is done already
Thanks in advance,Then why not use absolute layout and implement listeners to move the items around when the user drags. The other thing I would look at is creating a single version of each widget to use. You could then use that one widget to paint it in a number of different places in the same manner a JTable does, I'm sure that'd be far more efficient. -
Using paint() for a JPanel in a ScrollBar
i have a class that extends JPanel and paints some graphics in it using the function paint(). like g.drawString.. i had to add an instantition of that class in the container of my main class within a scrollbar. It initially painted well but when i scroll, it gets distorted. its something like this
public class PaintedPane extends JPanel
public PaintedPane()
paint()
other codes here..
public class MainClass extends JFrame
public PaintedPane pane;
public JScrollbar scroll;
public MainClass()
pane = new PaintedPane();
scroll = new JScrollBar(pane);
it seems that the pane wont update the part of the pane not initially exposed because of the scrollBar. how can i fix it? thanks!sorry for the wrong section.
here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainClass extends JFrame
public TextDraw td;
public JScrollPane pane;
public Container c;
public MainClass()
c = getContentPane();
c.setLayout(new FlowLayout());
td = new TextDraw();
td.setPreferredSize(new Dimension(300, 300));
pane = new JScrollPane(td);
pane.setPreferredSize(new Dimension(300, 200));
c.add(pane);
setSize(400, 400);
show();
public static void main(String args[])
MainClass m = new MainClass();
m.addWindowListener(
new WindowAdapter()
public void windClosing(WindowEvent e)
System.exit(0);
}and another java file for the TextDraw
import javax.swing.*;
import java.awt.*;
public class TextDraw extends JPanel
public TextDraw()
setBackground(Color.WHITE);
setSize(500, 500);
show();
public void paint(Graphics g)
for(int x = 0; x < 20; x++)
g.drawString("Hello world!", 20, (x)*20);
g.fillRect(5, (x)*20, 10, 10);
}i dont realy know what to do to fix this. And if i chang the values of the "setSize(400, 400)" of the MainClass to "setSize(300, 300)" it works fine. why is it like that? sorry im not very familiar with all the paint, paintComponent and graphics things. thanks! -
I'm trying to create a paint application for my degree dissertation and i've hit a bit of a snag. I have a Canvas which is an extenstion of a JPanel, but i dont know how to enable other classes to paint on it. Can anyone help me please?
thanks,
Gregmake your other classes call methods on your Canvas class. your Canvas class can paint on itself based on the method calls...
-
hi all,
below is my code,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics2D;
import java.awt.Graphics.*;
public class Testing extends JFrame implements ActionListener
String x[] = { " ", "Material A", "Material B", "Material C"};
String y[] = { " ", "+5", "+4", "+3", "+2", "+1", " 0",
"-1", "-2", "-3", "-2", "-5" };
private JButton Plot, End;
private Container c;
private JPanel centerPanel, northPanel, southPanel;
private JComboBox designMaterialx, materialRatingy;
String desMaterial = "";
public Testing()
super( "Welcome" );
Container c = getContentPane();
centerPanel = new JPanel()
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g.setColor(Color.blue);
g.drawRect(120, 120, 20, 200);
g.drawString ("Material", 30, 220);
g.drawString ("Ratings", 30, 240);
g.drawString ("+5", 102, 130);
g.drawString ("0", 107, 220);
g.drawString ("-5", 102, 315);
g.setColor(Color.red);
g.drawRect(120, 321, 20, 200);
g.drawString ("Design", 30, 410);
g.drawString ("Materials", 30, 430);
g2d.rotate(-Math.PI/2.0,250.0,250.0);
g.setColor(Color.black);
g.drawString(desMaterial, -15, 135);
centerPanel.setBackground(Color.white);
c.add( centerPanel, BorderLayout.CENTER);
setVisible(true);
northPanel = new JPanel();
northPanel.add(new Label( "Please choose accordingly:" ));
northPanel.setLayout (new FlowLayout(FlowLayout.CENTER, 20, 0));
designMaterialx = new JComboBox( x );
designMaterialx.setMaximumRowCount( 2 );
designMaterialx.setBorder(BorderFactory.createTitledBorder("Design Materials"));
northPanel.add( designMaterialx );
designMaterialx.setEditable(true);
materialRatingy = new JComboBox( y );
materialRatingy.setMaximumRowCount( 2 );
materialRatingy.setBorder(BorderFactory.createTitledBorder("Material Ratings"));
northPanel.add( materialRatingy );
c.add( northPanel, BorderLayout.NORTH );
setVisible( true );
southPanel = new JPanel();
Plot = new JButton( "Plot" );
End = new JButton( "End" );
southPanel.add( Plot );
southPanel.add( End );
c.add( southPanel, BorderLayout.SOUTH );
setVisible( true );
Plot.addActionListener(this);
End.addActionListener(this);
Plot.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
desMaterial = designMaterialx.getSelectedItem().toString();
centerPanel.repaint();
System.out.println(desMaterial);
pack();
public static void main( String args[] )
Testing app = new Testing();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
public void actionPerformed(ActionEvent e)
if(e.getSource()==Plot)
System.out.println("Plot");
else if(e.getSource()==End)
System.exit(0);
at the moment when the plot jButton is pressed, the selected values of the design materials jComboBox will be painted on the centerPanel inside the red rectangle. upon subsequent selection of the design materials & pressing of the plot jbutton, i wish to add them next to the existing ones but i'm not sure how to do this. could anyone out there help me on this? any kind of help would be appreciated.
thanks in advance.
rolfHere's a bunch of ideasimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class Test3 extends JFrame {
MyGraph mg = new MyGraph();
JTextField nameField = new JTextField("Sample2");
JTextField valueField = new JTextField("100");
public Test3() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = getContentPane();
mg.addData(new MyData("Sample",50));
content.add(mg, BorderLayout.CENTER);
JPanel dataPanel = new JPanel();
dataPanel.add(new JLabel("Name:"));
dataPanel.add(nameField);
dataPanel.add(new JLabel("Value:"));
dataPanel.add(valueField);
JButton jb = new JButton("Add");
dataPanel.add(jb);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mg.addData(new MyData(nameField.getText(),Integer.parseInt(valueField.getText())));
mg.repaint();
content.add(dataPanel, BorderLayout.NORTH);
setSize(300,300);
public static void main(String[] args) { new Test3().setVisible(true); }
class MyGraph extends JPanel {
ArrayList al = new ArrayList();
public void addData(MyData data) { al.add(data); }
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
super.paintComponent(g2d);
g2d.setColor(Color.red);
int height = getHeight(), width=getWidth();
for (int i=0; i<al.size(); i++) {
MyData md = (MyData)al.get(i);
g2d.drawRect(i*20,height-md.getNum(),17,md.getNum());
g2d.rotate(-Math.PI/2.0,width/2,height/2);
g2d.setColor(Color.blue);
for (int i=0; i<al.size(); i++) {
MyData md = (MyData)al.get(i);
g2d.drawString(md.getName(),30,i*20-15);
class MyData {
String name;
int num;
public MyData(String name, int num) {
this.name=name;
this.num=num;
public String getName() { return name; }
public int getNum() { return num; }
} -
Can you layer a Microsoft shape onto an image in Photoshop and change the color???
I'm using OS X Yosemite 10-10-1, Photoshop CC, 2014.2.1. I uploaded a shape from Word Office 2011 and layered it over my image. The symbol is blue and I want to change the color in Photoshop. I've tried but can't seem to figure out how it's done. The shape is blue.
Thank you.Put the Word symbol on a new Word document.
Save as .pdf
Bring into Photoshop and save as .psd. The area around the symbol will be clear.
Drag symbol layer over an image
Lock the clear area usng the symbol indicated by the red arrow shown above
Choose your replacement color
Edit > Fill with the Blending Mode set to Color
Job done. -
Hi.
Can any one help me with how to paint directly in JPanel, I need to paint directly in a swing component, but i dont know in which and how
How i use the paintComponent method of JPanel class..
Thanks.There are two ways to do this. If you are extending the JPanel class call the paintComponent method and put all your painting in there.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ThingMie extends JPanel
// private variables
public ThingMie()
// other gui stuff
setBackground(Color.white);
setBorder(BorderFactory.createRaisedBevelBorder());
protected void paintComponent(Graphics g)
super.paintComponent(g);
// write a string
g.setFont(new Font("Comic Sans MS", Font.PLAIN, 11));
g.setColor(Color.red);
g.drawString("hello", 6, 10);
// draw a rectangle
g.setColor(Color.green);
g.drawRect(15, 15, 30, 60);
// draw an ellipse
g.setColor(Color.blue);
g.drawOval(150, 20, 50, 100);
public static void main(String [] args)
JFrame thing = new JFrame();
thing.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
thing.getContentPane().add(new ThingMie(), BorderLayout.CENTER);
thing.setTitle("Painting to a panel");
thing.setSize(400, 300);
thing.setVisible(true);
If you're creating a JPanel within another component, say a JFrame or a JDialog you can use code like this:
import java.awt.*;
import javax.swing.*;
class ThingMie extends JFrame
// private variables
private JPanel panel;
public ThingMie()
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// other gui stuff
panel = new JPanel()
protected void paintComponent(Graphics g)
super.paintComponent(g);
// write a string
g.setFont(new Font("Comic Sans MS", Font.PLAIN, 11));
g.setColor(Color.red);
g.drawString("hello", 6, 10);
// draw a rectangle
g.setColor(Color.green);
g.drawRect(15, 15, 30, 60);
// draw an ellipse
g.setColor(Color.blue);
g.drawOval(150, 20, 50, 100);
panel.setBackground(Color.white);
panel.setBorder(BorderFactory.createRaisedBevelBorder());
getContentPane().add(panel, BorderLayout.CENTER);
public static void main(String [] args)
ThingMie thing = new ThingMie();
thing.setTitle("Painting to a panel");
thing.setSize(400, 300);
thing.setVisible(true);
/***********/ -
Adding mouse events to shapes painted from a shape array
Hi,
I currently paint shapes to a canvas from an array and want to be able to move these shapes around the screen. Unfortunately I am unsure how to set up the MouseDragged event so that it redraws only the shape I want (Currently there is no link in the paint method to the mouseDragged variables), any ideas?
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
public class MyCanvas extends Canvas implements MouseMotionListener{
private ArrayList liList;
private ArrayList reList;
private int rectX;
private int rectY;
int re;
int li;
public MyCanvas()
Parser p = new Parser();
liList = p.getLineArray();
reList = p.getRectArray();
addMouseMotionListener(this);
public void paint(Graphics g)
Graphics2D g2 = (Graphics2D)g;
while(re<reList.size())
Shape r = (Shape)reList.get(re);
g2.setStroke(new BasicStroke(4));
g2.setPaint(Color.blue);
g2.fill(r);
g2.draw(r);
re++;
while(li><liList.size())
Shape l = (Shape)liList.get(li);
g2.setStroke(new BasicStroke(4));
g2.setPaint(Color.red);
g2.fill(l);
g2.draw(l);
li++;
public void mouseDragged(MouseEvent e)
int rx = e.getX();
int ry = e.getY();
repaint();
public void mouseMoved(MouseEvent e)
}Cheers>why is that?Because event listeners work with components, and a Shape is no Component. Besides, I don't see any method to add a listener.
-
Adding mouse events to shapes painted from arrays
Hi,
I currently paint shapes to a canvas from an array and want to be able to move these shapes around the screen. Unfortunately I am unsure how to set up the MouseDragged event so that it redraws only the shape I want (Currently there is no link in the paint method to the mouseDragged variables), any ideas?
import java.awt.BasicStroke;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
public class MyCanvas extends Canvas implements MouseMotionListener{
private ArrayList liList;
private ArrayList reList;
private int rectX;
private int rectY;
int re;
int li;
public MyCanvas()
Parser p = new Parser();
liList = p.getLineArray();
reList = p.getRectArray();
addMouseMotionListener(this);
public void paint(Graphics g)
Graphics2D g2 = (Graphics2D)g;
while(re<reList.size())
Shape r = (Shape)reList.get(re);
g2.setStroke(new BasicStroke(4));
g2.setPaint(Color.blue);
g2.fill(r);
g2.draw(r);
re++;
while(li<liList.size())
Shape l = (Shape)liList.get(li);
g2.setStroke(new BasicStroke(4));
g2.setPaint(Color.red);
g2.fill(l);
g2.draw(l);
li++;
public void mouseDragged(MouseEvent e)
int rx = e.getX();
int ry = e.getY();
repaint();
public void mouseMoved(MouseEvent e)
}Cheerswhy is that?Because event listeners work with components, and a Shape is no Component. Besides, I don't see any method to add a listener.
-
Hi i am in the process of making a paint program and have decided to go through the (hopefully not) long process of using layers.
at the moment all shapes, when drawn, are stored in a vector and then painted onto the graphics of a class extending JPanel.
what i want to do is store them in separate images, all the size of the JPanel canvas (so they can be positioned at (0, 0)) and anyt area of the image that isnt part of the shape should be transparent.
i have tried creating a new graphics object for each shape and then painting them onto an ARGB buffered image then storing all the images in a new vector and finally painting them onto the canvas however this isnt working.
is there an easier way to do this, or does anybody know what has happened?
thanksIf they're in a vector, they're basically already in a kind of layered system, of course.
If what you want is to have all the shapes live in their own coordinate system, and then be able to assign relative positions to draw their system in a larger coordinate system...well, I thought that Java2D already handled that. But if it doesn't, then rather than drawing in images, another thing you can do is create a class that represents a coordinate system. Basically, all it would have to do is have two state elements: a reference to a shape, and a reference to an (x,y) pair where you want to anchor that shape for drawing. Then your vector could hold these objects.
It wouldn't have to be much more than:
class Layer {
private Shape shape;
private Point location;
// constructor that sets these; shape could be final, but location probably shouldn't be
public void paint(Graphics g) {
// maybe use AffineTransform to move the shape to the given location, then
// paint it?
}You should probably check on a forum that does more with GUIs though.
But, if you want to, you can also make each layer just be an image. You'd gain some of the operations of images (like Graphics knowing how to scale them) but might lose image quality. There are a bunch of tutorials about double buffering that will tell you how to create an intermediate image; you could apply that to make multiple images, if you wanted to. -
Hello All!
How can I achieve incremental painting in a JPanel or in general JComponents.. By "incremental painting" I mean I do not want to lose my previous drawings on the panel aka. I want to update the drawing by adding more drawings.
An example would help this is the code:
import java.awt.*;
import javax.swing.*;
public class CustomPanel extends JPanel{
public final static int CIRCLE = 1, SQUARE = 2;
private int shape;
public void paintComponent(Graphics g){
super.paintComponent(g);
if(shape == CIRCLE)
g.fillOval(50,10,60,60);
else if(shape == SQUARE)
g.fillRect(150,110,60,60);
public void draw(int s){
shape = s;
repaint();
This class is used by the following class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CustomPanelTest extends JFrame{
private JPanel buttonPanel;
private CustomPanel myPanel;
private JButton circle, square;
public CustomPanelTest()
super("Custom Panel Test");
myPanel = new CustomPanel();
myPanel.setBackground(Color.green);
square = new JButton("Square");
square.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
myPanel.draw(CustomPanel.SQUARE);
circle = new JButton("Circle");
circle.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
myPanel.draw(CustomPanel.CIRCLE);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,2) );
buttonPanel.add(circle);
buttonPanel.add(square);
Container c = getContentPane();
c.add(myPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
setSize(300,150);
show();
public static void main ( String args[] )
CustomPanelTest app = new CustomPanelTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing (WindowEvent e )
System.exit(0);
While executing, either a circle or square is drawn by erasing the previous drawing. What I want to achieve is for example drawing a series of circles and/or squares without losing the previous drawings.
Thank you!!!!This will do it. I added a bufferedimage.
import java.awt.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
public class CustomPanel extends JPanel
public final static int CIRCLE = 1, SQUARE = 2;
private int shape;
private BufferedImage I = null;
private Graphics G;
public void paintComponent(Graphics g)
if (I == null)
I = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_ARGB);
G = I.getGraphics();
G.setColor(Color.white);
G.fillRect(0,0,getWidth(),getHeight());
super.paintComponent(g);
G.setColor(Color.red);
if(shape == CIRCLE) G.fillOval(50,10,60,60);
if(shape == SQUARE) G.fillRect(150,110,60,60);
g.drawImage(I,0,0,null);
public void draw(int s)
shape = s;
repaint();
}Noah -
Hello can any body help me to add color to my shape using jcombobox
please how can i fill color to my shape and change the line color of my shape using jcombobox here is my code
//package paint;
* PaintShapesDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PaintShapesDemo extends JFrame implements ActionListener
final private int RECT =1 ;
final private int CIRCLE = 2;
final private int POLY = 3 ;
final private int ELLI = 4 ;
final private int TRAN = 5 ;
private int shape;
JLabel Lcolor;
JLabel Fcolor;
JLabel headlebel,linecolorlabel,fillcolorlabel,labeldisplay;
JButton recbutton,cirbutton,polygonbutton,ellipsebutton;
JComboBox linecolor,fillcolor;
private ButtonGroup grShapes = new ButtonGroup();
private JPanel shapeSelectionPanel = new JPanel(new FlowLayout());
public PaintShapesDemo()
super("HAKIMADE");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.white);
setSize(800,600);
setLocationRelativeTo(null);
recbutton = new JButton("CIRCLE");
cirbutton = new JButton("ROUNDRECT");
polygonbutton = new JButton("ELLIPSE");
ellipsebutton = new JButton("RECTANGLE");
JPanel TP=new JPanel();
TP.setLayout(new FlowLayout(FlowLayout.CENTER));
TP.add(new JLabel("MY PAINT APPLICATION."));
JPanel panel1=new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.CENTER,10,40));
panel1.add(recbutton);
panel1.add(cirbutton);
panel1.add(polygonbutton);
panel1.add(ellipsebutton);
JPanel TP1=new JPanel();
TP1.setLayout(new BorderLayout());
TP1.add(TP,BorderLayout.NORTH);
TP1.add(panel1,BorderLayout.CENTER);
JPanel panel2=new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.CENTER,30,2));
Lcolor = new JLabel("SELECT LINE COLOR");
Fcolor = new JLabel("SELECT FILL COLOR");
panel2.add(Lcolor);
panel2.add(Fcolor);
JPanel panel3=new JPanel();
panel3.setLayout(new FlowLayout(FlowLayout.CENTER,30,2));
linecolor = new JComboBox();
linecolor.addItem("Choose the color");
linecolor.addItem("Gray");
linecolor.addItem("Orange");
linecolor.addItem("Magenta");
linecolor.addItem("Dark Gray");
fillcolor = new JComboBox();
fillcolor.addItem("Choose the color");
fillcolor.addItem("RED");
fillcolor.addItem("BLUE");
fillcolor.addItem("BLACK");
fillcolor.addItem("YELLOW");
panel3.add(linecolor);
panel3.add(fillcolor);
JPanel panel4=new JPanel();
panel4.setLayout(new BorderLayout());
panel4.add(panel2,BorderLayout.NORTH);
panel4.add(panel3,BorderLayout.CENTER);
shapeSelectionPanel.add(TP1);
shapeSelectionPanel.add(panel4);
shapeSelectionPanel.setBackground(Color.green);
shapeSelectionPanel.setBorder(BorderFactory.createLineBorder(Color.black));
shapeSelectionPanel.setPreferredSize(new Dimension(110, 100));
add(shapeSelectionPanel, BorderLayout.NORTH);
add(new DrawingPanel());
recbutton.addActionListener(this);
cirbutton.addActionListener(this);
polygonbutton.addActionListener(this);
ellipsebutton.addActionListener(this);
public static void main(final String args[])
new PaintShapesDemo().setVisible(true);
public void actionPerformed(final ActionEvent e)
shape = CIRCLE;
if(e.getSource() == cirbutton)
shape = RECT;
if(e.getSource() == recbutton)
shape = POLY;
if(e.getSource() == polygonbutton)
shape = ELLI;
if(e.getSource() == ellipsebutton)
shape = TRAN;
class DrawingPanel extends JPanel
private Image img;
private Graphics2D g2;
public DrawingPanel()
addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e){drawShape(e.getX(), e.getY());}});
public void paintComponent(final Graphics g)
if(img == null)
img = createImage(getWidth(), getHeight());
g2 = (Graphics2D)img.getGraphics();
g.drawImage(img,0,0,null);
private void drawShape(final int x, final int y)
switch (shape)
case POLY: g2.drawOval(x,y,100,100);break;
case ELLI: g2.drawOval(x,y,100,50);break;
case RECT: g2.drawRoundRect(x,y,100, 70, 20, 20);break;
case CIRCLE: g2.drawRect(x,y,100,80);break;
case TRAN: g2.drawRect(x,y,100,80);
repaint();
}use CODE tags to post source code
read selected color from combobox and set colors Or declare two Strings lineColor and fillColor and set these variables on change of combo by adding ItemListener to the combo. and use that varables to set colors ..
Refer:
http://www.java2s.com/Code/Java/2D-Graphics-GUI/Arcdemonstrationscalemoverotatesheer.htm
Maybe you are looking for
-
I have just began a second start at JAVA and I am having issue creating an exception that works..i have an app that will accept grades...average them...and if someone puts a value over 100 it should thorw an exception...or under 0 it should..i cant g
-
Keeping Row Highlighted In Master-Detail Table
JDev 11.1.2.0 I have a small .jsf page with a master-detail setup, using 2 tables. When I select a row in the master table, the detail table is populated as expected. When I select a row in the detail table, the row is no longer highlighted on the ma
-
Post Author: ftpaxa CA Forum: Other I use a SQL server DataBase on Windows server 2003 with service pack 2. i use Crystal Report 10 with ODBC connection. I read that the nice DLL is "Crdb_odbc.dll".I saw a VB code "How to format a text object" on thi
-
hi, I'm using the new version, and this is a file made with the previous version. WeTransfer As you can see it is a map with places. If you click a place an overlay appears. If you click another place, the old one goes away, the new one shows up... n
-
Open Block Diagram After Deployment on a Non-LabVIEW PC
Hello all, I have a application created in LabVIEW which will be deployed on a PC which does not have LabVIEW Development System installed in it, but only the RTE. With this application, I am also deploying the dependent VIs in a separate folder. My