Want to draw some rectangles inside a swing panel object
HI,
I want to draw some rectangles inside one JPanel object in swing. The JPanel object should also hold some buttons, labels, etc.. I can add simple buttons, label etc. easily to the panel object but how do I add graphics (like lines, rectangles) to it ??
an immediate response would be highly appreciated!!
I am not sure why you are talking about the rectangle.
To repeat I fill in a bit of code (subject to compiler errors since I Do not have a machine where I can compile or test on at the moment):
private class ColourCube extends JPanel
// The size of each rectangle with colour
private static final int ROWS = 10;
private static final int COLS = 10;
// To store current selection
private int selectedIndex[] = null;
public ColourCube()
addMouseListener( new MouseAdapter() {
public void mouseReleased(MouseEvent me)
// Find the rectangle index by dividing
// x and y positions then set selectedIndex
// unless it is the same positions as previous
// then set it to be null
fireActionEvent();
// needed listener methods for firing events
public void addActionListener( ActionListener al)
// add to list
// remove etc....
protected void fireActionEvent()
// Construct action event
// call actionPerformed( ae ) on all listeners
public void paintComponent(Graphics g)
// Depending on size and height of this component
// calculate out colWidth and rowHeight
// Loop and paint the rectangles in their different colours
for(int i = 0; i < ROWS; i++)
for(int j = 0; j < COLS; j++)
// set the colour to the graphics object here from the list of colours available
g.setColor( ... );
// Added a little bit extra to have some space between
// each rectangle
g.fillRect( i * rowHeight + 1, j * colWidth + 1, colWidth - 2, rowHeight - 2 );
if( selectedIndex != null )
// We have a selection, lets paint the selection
g.setColor( Color.white ); // Selection colour
// The index contains the row in index 0 and the col in index 1
g.drawRect( selectedIndex[0] * rowHeight, selectedIndex[1] * colWidth, colWidth, rowHeight );
}Lacking from the above component is lacking stuff like preferedSize.
Now, all you do is instantiate the ColourChooser, add it to your applet iether by drag and drop if you have an WYSIWYG editor, or by hand if you are so inclined.
Voila! A composite component appears, doing the stuff it needs to be doing.
Regards,
Peter Norell
Similar Messages
-
Drawing a rectangle inside a label with a picture
Hi everyone,
i want to know how you can draw a rectangle inside a label that have an iconimage
thanks in advance,
kimosIt depends if you want it only to show on the GUI or really change the image inside the IconImage.
If you just want it to show in your GUI, extend JLabel and implement paintComponent to draw a rectangle on top.
JLabel label = new JLabel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(x, y, width, height);
}; -
I want to draw rounded rectangle with dashed border
Hello,
I am working on flex 4.5 air 2.7 . And i want to draw rounded rectangle which has dashed border or solid border as per user's selection. Also rectangle can be rounded or simple. I am able to draw simple rectangle with dashed border. I want a solution for rounded rectangle.
If anyone have any idea then post as soon as possible..
Thanks
DhwaniGood day!
Could you please post a screenshot with the Layers Panel visible?
Is the iten by any chance a Shape Layer and therefore does have a Vector Mask?
Regards,
Pfaffenbichler -
Who wants to earn some dukes in the swing forum?
just take a look at my riddle:
http://forum.java.sun.com/thread.jspa?threadID=5117753&tstart=0
Cheers!
AnnetteOk, rookie :)
Imagine a servlet as just a regular java class that happens to be able to be called from a webpage using Jakarta-Tomcat or one of the other JSP/Servlet engines out there. If you are familiar with server-side programming then passing information from a Servlet to your GUI should be easy. As for passing info from a GUI to a servlet, I'm not too sure how, but that's just because I haven't written many applets in Java yet. I suggest highly "Using Java Server Pages and Servlets Special Edition" from Que as a good reference book for a technically minded programmer starting in Servlets. Now, enough of the rookie-speak, and on to the problem. If you want to pass information from a servlet to an applet, there are probably many ways to do this, but the first way I can think of is to:
a) create a servlet from scratch.
b) In the doGet() or doPost() methods, instantiate any variables you need to pass.
c) Attach these variables to the datastream using the method .setAttribute() in the HttpServletRequest object
d) Redirect your page to the page containing the <APPLET> tag using the following line:
getServletContext().getRequestDispatcher(URL).forward(request,response);
e) Inside your page with the <APPLET>, use <% String blah = (String) request.getAttribute("Whatever"); %>
f) To reference the passed variable, use <%=blah%> and it will output a string in that place.
g) MAKE SURE YOU RENAME THAT PAGE FROM *.html to *.jsp IF IT HAS <% %> tags.
Thats about all the help I can give online.....if I've totally confused you, try looking in that book. It's really helpful....
Dan from Canada -
I want to draw a rectangle - not a filled rectangle, I can do that but say a rectangle about 5 pixels wide that I can then drag to resize and use like a frame. The pre-defined shapes increase their line thickness as you make them bigger which is not what I want.
I could of course draw an outer rectangle in colour and then a smaller white one inside to simulate the effect I want but I'm using transparency so I don't want a filled white area.
Please tell me I've missed something simple!File>new> blank file
Access rectangular marquee tool. In the tool's option bar, one can establish a fized size
Edit>stroke. The width of the stroke can be configured in pixels.
Any intervening color can be removed by selecting with magic wand tool -
Drawing a rectangle around a group of components
I want to draw a rectangle around a group of rectangular adjacent components that are in a Canvas. I can't seem to find the right component to do this, or I am just not doing it properly. I tried using a Canvas inside the Canvas with the inner borders set and adding the components to the inner Canvas and placing the inner Canvas at the location of the components it now contains, but it doesn't show up. I also tried a transparent Canvas with backgroundAlpha set to 0. Canvas is probably not the proper component to do this with. Is there an easier way?
I want to draw a rectangle around a group of rectangular adjacent components that are in a Canvas. I can't seem to find the right component to do this, or I am just not doing it properly. I tried using a Canvas inside the Canvas with the inner borders set and adding the components to the inner Canvas and placing the inner Canvas at the location of the components it now contains, but it doesn't show up. I also tried a transparent Canvas with backgroundAlpha set to 0. Canvas is probably not the proper component to do this with. Is there an easier way?
-
Draw a rectangle on an image in an applet
Hello
I have an applet that has 3 buttons. Each of them creates an image, which is displayed on the screen. Now, I want to draw a rectangle on these images. Since I already have a paint method for displaying the images correctly, I would need a second paint method for the rectangle. (I can't put everything in the same paint() method, because I have an horrible resukt)
Does anyone have an idea of a method that would be able to replace a paint method?
Any help would be appreciated
Thanks
PhilippeHave you thought about using one of your button to get the action done? You could use the Graphics method to create your object rectangle.
Don't know if it would work but seems like a good idea to try. -
Can we draw a RECTANGLE of 1.5 (fractional ) height ??
hi ,
I am designing an GUI for scollbar for list elements ( may vary from 1- 2000 elements ) .For a better designing option , i want to draw a rectangle of fractional hieght ( say 1.5 ).
can anyone tell me, is it possible to draw such a rectangle .read the Graphics javadoc page and you will have your answer
-
Can we draw a RECTANGLE of 1.5 (fractional ) height in J2ME ???
hi ,
I am designing an GUI for scollbar for list elements ( may vary from 1- 2000 elements ) .For a better designing option , i want to draw a rectangle of fractional hieght ( say 1.5 ).
can anyone tell me, is it possible to draw such a rectangle .http://developers.sun.com/techtopics/mobility/midp/articles/s2dvg/index.html
-
MFC: Draw rectangle inside a rectangle
Hi,
I have drawn a rectangle:
dc.Rectangle(10,10,200,100);
Now i want to draw rectangle inside it by reducing 10 from each side. i.e the new rectangle will be: CRect(20,20,190,90).
I am manually adjusting the co-ordinate, Is there any API to do this.
offsetRect() is not solving my issue.
ThanksHi,
I have drawn a rectangle:
dc.Rectangle(10,10,200,100);
Now i want to draw rectangle inside it by reducing 10 from each side. i.e the new rectangle will be: CRect(20,20,190,90).
I am manually adjusting the co-ordinate, Is there any API to do this.
offsetRect() is not solving my issue.
Thanks
Just write yourself a function and use it as needed. Programming is not manual work; the computer does the heavy lifting.
Edit: Actually, I think CRect::DeflateRect() does what you want.
David Wilkinson | Visual C++ MVP -
I want to find if the user is inactive inside my swing application
i want to find if the user is inactive inside my swing application i.e he has not used the keyboard or mouse over a period of time
Hai,
This is code to notify you when the keyboard is left inactive for 10 seconds it will throw a message then the sytem will get exit.
For mouse event i don't how to do the same process.
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
* InactiveTest.java
* Created on October 9, 2006, 12:33 PM
public class InactiveTest extends javax.swing.JFrame {
int timeCnt = 0;
Thread th;
/** Creates new form InactiveTest */
public InactiveTest() {
initComponents();
th = new Thread() {
public void run() {
while(true) {
try {
th.sleep(1000);
timeCnt++;
System.out.println("Time Cnt"+timeCnt);
if(timeCnt == 10) {
JOptionPane.showMessageDialog(objInactiveTest,"Inactive for 10 seconds");
System.exit(0);
th.stop();
break;
}catch(Exception e){}
th.start();
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent event) {
timeCnt=0;
//th.stop();
//th.start();
return false;
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setLayout(new java.awt.GridLayout());
jLabel1.setText("Enter the Name :");
jPanel1.add(jLabel1);
jPanel1.add(jTextField1);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
// </editor-fold>
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
objInactiveTest = new InactiveTest();
objInactiveTest.setVisible(true);
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
private static InactiveTest objInactiveTest;
}rgds,
rdRose -
I want to draw rectangle like corelDraw?
i want to draw rectangle just like corelDraw?
so any body know about how to draw such things please tell meCheckout Graphics and Graphics2D.
-
Can you define a specific size of a Drawing Markup rectangle?
Hi all,
I am using Acrobat X and have been asked to find an answer to a 'problem' someone is having.
If you have a site plan of one's property and they submit it to me for comment (as a pdf file) can I draw a box to a specific size? Say I set the 'scale ratio' to what the drawing scale is, I go to 'comments' and from the 'Drawing Markups' pane I choose 'draw rectangle; square', I then draw a rectangle to represent a shed of a specific size. I can dimension how far the rectangle/shed is to be from the property lines and I can dimension the rectangle/shed but I have to play with stretching it to get it to my desired size based on the scale I set.
My question; is there anyway, when I am drawing the box, to either specify an x by y size or see the lenghts of their sides once I pick a corner and start to drag the box to the other corner?
If not, would there be a java script that could accomplish this task?
Any help would be appreciated.
Thanks in advance.
PaulThanks Sabian, I understand that Acrobat is not a vector drawing application and I have been using all those programs (illustrator, AutoCAD, CorelDRAW etc.) for the past 20+ years. It wouldn't seem too much to ask considering that I can set a scale to my page (in Acrobat) and I can get Acrobat to give me a dimension from point A to point B based on that said scale, so why couldn't I expect to put a rectangle markup based on that same scale?
As for the right tool? We are a municipality that is trying to make it easier for the public to submit applications online. Those submissions are in the format of a PDF because it is unrealistic to assume the everyone in the public has access to or can afford a program like AutoCAD or illustrator. Likewise it is too COSTLY to have everyone in the city have say 'AutoCAD' or even 'illustrator' to view the application documents to markup and send back.
I believe In 1991, Adobe Systems co-founder John Warnock outlined a system called "Camelot"[3] that evolved into PDF (from Wikipedia) and it was a way to have an independent viewing format regardless of what software application created it. I truly believe that Acrobat for what it's initial intent was that it should incorporate some of these features as it only makes sense in an evolutionary sense. Not to be a 'drawing package' but in it's markup/comments palette to expand on them.
So keep your comments to 'no at this time acrobat does not allow this type of functionality but who knows in the future' and don't treat me as though I don't know anything about anything. In my decades of using these applications I have seen them evolve to include more functions and do more then when the product was originally released.
I will now go on and recommend that they seriously look at Bluebeam Revu as it is not only cheaper but it has a ton more functionality specifically designed for the needs as listed above working with PDF's (and bitmap images to boot). I was just wanting to cover all bases and give all programs a fair look.
Thanks again for your intuitive insight.
Paul -
"I want to draw a line, and it will highlight when I click it."
I am currently working on a project right now. My project is a structural analysis software for civil engineers. Our project is already at it's infant
stage of development. I am having trouble with how to implement drawing on a canvas. Heres the specs:
-There are nodes on the drawing board illustrated by dots.
-Lines must be drawn connecting the nodes.
-Nodes must be a separate object where it could respond to mouse
events.
-Lines must also be a separate object where it could respond to mouse
events.
-Nodes and lines contain mathematical attributes, color information.
-I can instantly delete a line, or change its attributes by selecting
it.
Heres what I have imagined:
-I am going to draw my Nodes in a JPanel which implements a
mouseListener.
-Whenever I want to add nodes to the drawing board, I only have to add
the Node objects i created.
No problem with the nodes. Problem is in the lines i will be drawingconnecting one node to another.
-I tried manual live drawing of the lines as the mouse moves. Now its
flat on the drawing board. It can't be touched!
-I still don't have any idea how to implement the line that it could
respond to mouse events.
-If I try to draw it in a JPanel with mouseListener, a JPanel is square
so if I move my mouse to point in to the line drawn on the JPanel, it
will already respond before the mouse could reach the line image. One
thing also, it could overlap other JPanels.
-The JPanel idea came up to my mind coz I thought these objects could
be
selectable custom components.
-Now I realized JPanel is not the ANSWER!
In simple saying:
"I want to draw a line, and it will highlight when I click it."
Stubborn Newbie,
Edgarimport java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class SelectingLines extends JPanel
Line2D.Double[] lines;
int selectedIndex = -1;
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(lines == null)
initLines();
for(int j = 0; j < lines.length; j++)
Color color = Color.blue;
if(j == selectedIndex)
color = Color.green.darker();
g2.setPaint(color);
g2.draw(lines[j]);
public void setSelection(int index)
selectedIndex = index;
repaint();
private void initLines()
lines = new Line2D.Double[3];
int w = getWidth();
int h = getHeight();
lines[0] = new Line2D.Double(w/8, h/8, w/3, h/6);
lines[1] = new Line2D.Double(w/3, h/6, w/2, h/2);
lines[2] = new Line2D.Double(w/2, h/2, w*5/8, h*7/12);
public static void main(String[] args)
SelectingLines selectPanel = new SelectingLines();
selectPanel.addMouseListener(new LineSelector(selectPanel));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(selectPanel);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
class LineSelector extends MouseAdapter
SelectingLines selectingLines;
Rectangle r;
final int S = 4;
public LineSelector(SelectingLines sl)
selectingLines = sl;
r = new Rectangle(S, S);
public void mousePressed(MouseEvent e)
Point p = e.getPoint();
r.setLocation(p.x-S/2, p.y-S/2);
Line2D.Double[] lines = selectingLines.lines;
int index = -1;
for(int j = 0; j < lines.length; j++)
if(lines[j].intersects(r))
index = j;
break;
if(index != selectingLines.selectedIndex)
selectingLines.setSelection(index);
} -
Simply put, can I use an SWT component inside of a JDialog, JFrame, or JInternalFrame?
I've been searching for this answer all over and while apparently I can use a Swing component in SWT I cant find any example of using SWT inside of Swing.SWT only provides a way to embed swing and not the other way around (as far as I know of) so you might have a problem.
If you want to embed a native browser look at the JDIC project which has this ability.
https://jdic.dev.java.net/
1 small warning though, I have played around with this and when switching between visible and non visible panels (some contain this brower) I saw some native code errors and the entire app crashed so just be carefull how you use it.
Maybe you are looking for
-
Laptop won't power up with AC adapter and won't charge battery
Here is the thing. 1) the laptop doesn't power on without a battery when directly connected to ac adapter. 2) the light which would indicate that the laptop is plugged into the ac adapter is not on when the ac adapter is plugged in. 3) the battery ch
-
Printer turns off even though is connected on MacBook
Hi all, I got my dad a MacBook to replace his Dell. A lot of complains aroused since the switch and managed to answer most to him. However, one I cannot figure out is the following. When we had the Dell we left the printer connected to the laptop and
-
Looking for BPA training in EMEA
Hi all, I am looking for courses or other events providing in-depth training of the BPA tool. Living in Norway so events should be held in Europe. Have been looking for it a while now, without any luck. Does anyone of you know of a scheduled/planned
-
Proper location of the "Logic" Folder?
I've updated my system several times and have several boot disks with different OS installed and have noticed that I have "Logic" folders located in the following directories: Users/"home folder"/Movies/Music/Logic Users/"home folder"/Music/Logic iTu
-
Hi, I had made a mistake in my previous post. I need information on LiveCache concepts in APO and not "Live Cash" as previously mentioned. Sorry about that.. Thanks, Sruthy