Java 2D custom paint
Hi im using the following line of code to display my nubers on screen
g.drawString(this.toString(), 25, 25);
and this is the toSting method it uses
public String toString(){
return String.format("%s : %s", systolic,diastolic) ;
However this is plain and boring just like writing numbers .
I wish to make it like a nice LCD display so the numbers look like that of a calculator (more graphical)
and can anyone help me please ??
Thank You
xiaolixx wrote:
Hi im using the following line of code to display my nubers on screen
g.drawString(this.toString(), 25, 25);What Font is the Graphics object using?
Note that if you had posted an SSCCE *(<- link),* I'd have been able to find that out easily.
BTW. When posting code, code snippets, HTML/XML or input/output, please use the code tags. Using code tags helps retain the indentation and formatting of the sample. To do that, select the sample and click the CODE button.
Here is how the second snippet appears in code tags.
public String toString(){
return String.format("%s : %s", systolic,diastolic) ;
}
Similar Messages
-
Custom painting/ graphics in a panel
Ten Duke Dollars for whoever gives the best high level solution for my problem.
I'm writing a small application that displays music notation on screen and lets the user move the notes vertically to the desired locations on the staves. The user can then do various kinds of analysis on each example. The analysis stuff is done, but I'm having trouble finding an approach that will work for the graphics.
My basic approach so far is to subclass JPanel and use it to handle all the custom painting. I'm planning to add all needed JPEG's to JLabels. Some of the images (e.g. treble and bass clef images) will always be in a fixed location, while others (note images) will move vertically when the user drags them. For the lines on the staves and the measure lines, I'm planning to use g.drawLine.
The following questions occur to me:
1. How will I prevent the note images from hiding the lines? Will I need to make the images transparent GIFs or something? Or can I set some layering property in the JPanel to build up a layered drawing?
2. to detect mouse events, should I attach mouse listeners to my panel, or to each label that contains a note image? (I considered using Ellipse objects for the note heads and lines for the stems, but this will not give me a high enough quality of image.)
3. I will probably need to use absolute positioning in the panel class rather than FlowLayout or whatever, but I'm having trouble getting rid of the layout manager. Can you give me a few lines of code to do this?
4. Is my overall approach correct? Is there a better, easier way to accomplish what I'm trying to do?
thanks,
Eric>
The following questions occur to me:
1. How will I prevent the note images from hiding the
lines? Will I need to make the images transparent GIFs
or something? Or can I set some layering property in
the JPanel to build up a layered drawing?If you are going to use images (probably BufferedImages), their Transparency will probably be BITMASK or TRANSLUSCENT.
2. to detect mouse events, should I attach mouse
listeners to my panel, or to each label that contains
a note image? (I considered using Ellipse objects for
the note heads and lines for the stems, but this will
not give me a high enough quality of image.)I don't think using JLabel objects is a good idea. Instead of add labels to a panel, I would define a custom JComponent that did its own painting in paintComponent.
>
3. I will probably need to use absolute positioning in
the panel class rather than FlowLayout or whatever,
but I'm having trouble getting rid of the layout
manager. Can you give me a few lines of code to do
this?If you follow my last comment, your component isn't being used as a container, so this is not relevant.
>
4. Is my overall approach correct? Is there a better,
easier way to accomplish what I'm trying to do?
thanks,
EricCheck out forum Java 2D. That's where this topic belongs. You also need to learn the 2D API. Search for some text book references in that forum.
From the Imipolex G keyboard of...
Lazlo Jamf -
A problem with custom painting.
I was trying to make a bar chart from a given data. I used an extension JLabel (mentioned as inner class Leonardo) inside a scrollpane for the custom painting of the bars (rectangles).
The problem I am facing is the component is not visible when I open the screen. If I drag the scrool bar then the next area is painted and the component looks fine. If the frame is minimized and then maximized the custom painting is not visible. Any idea why it is doing so? I am pasting the full code in case some body wants to run it.
Thanks in advance,
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import java.awt.geom.*;
public class Reporter extends JFrame
private JPanel basePanel = new JPanel();
private Leonardo1 leo = null;
private JScrollPane scrollPane = new JScrollPane();
public Reporter()
try
jbInit();
catch(Exception e)
e.printStackTrace();
public static void main(String[] args)
Reporter reporter = new Reporter();
reporter.pack();
reporter.setSize(700,500);
reporter.setVisible(true);
private void jbInit() throws Exception
this.setSize(new Dimension(679, 497));
this.getContentPane().setLayout(null);
this.setTitle("Process Reporter");
// this.addWindowListener(new Reporter_this_windowAdapter(this));
basePanel.setLayout(null);
basePanel.setBounds(new Rectangle(15, 60, 640, 405));
basePanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
/* Hard code data */
Vector d= new Vector();
for (int j=0; j<131;j++)
Data d1 = new Data(j*j*1.0,new java.sql.Date(System.currentTimeMillis()+j*1000000000),"yy","xx",Color.red);
d.add(d1);
leo = new Leonardo1(d);
/*End of Hard Code data*/
leo.setBounds(new Rectangle(10, 65, 656, 346));
scrollPane.setBounds(new Rectangle(10, 10, 620, 330));
scrollPane.getViewport().add(leo);
basePanel.add(scrollPane, null);
this.getContentPane().add(basePanel, null);
class Data implements java.io.Serializable
public double time;
public java.sql.Date day;
public String timeText;
public String dayText;
public Color color;
public Data(double t,java.sql.Date dt, String strT,String strD,java.awt.Color col)
time = t;
day=dt;
timeText=strT;
dayText=strD;
color=col;
public void setTime(double t) {time =t;}
public void setDay(java.sql.Date t) {day =t;}
public void setTimeText(String t) {timeText =t;}
public void setDayText(String t) {dayText =t;}
public void setColor(Color t) {color =t;}
public double getTime() {return time;}
public java.sql.Date getDay() {return day;}
public String getTimeText() {return timeText;}
public String getDayText() {return dayText;}
public Color getColor() {return color;}
class Leonardo1 extends JLabel implements java.io.Serializable
private Vector dataVec = new Vector();
private double xGap = 5.0;//Gap between 2 bars
private double xWidth = 12.0;//Width of a bar
private double yGap = 40.0;//Gap from start of Y axis to first data.
private int xLength = 645;//Length of the component
private int yLength = 330;//Height of the component
private int xMargin = 50;//The gap from the corner of the axis to the y axis
private int yMargin = 20;//The gap from the corner of the axis to the x axis
private double avgTime = 0.0;
protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
public int getWidth(){ return xLength;}
public int getHeight(){ return yLength;}
public Dimension getMaximumSize(){return new Dimension(xLength,yLength);}
public Dimension getMinimumSize(){return new Dimension(xLength,yLength);}
public Dimension getSize(Dimension rv){ return new Dimension(xLength,yLength);}
public Rectangle getBounds(Rectangle rv){ return new Rectangle(xLength,yLength); }
public Leonardo1(Vector vec) {
super();
setOpaque(true);
super.setBackground(Color.white);
setData(vec);
setBorder(noFocusBorder);
protected void setData(Vector vec){
if (vec == null) return;
dataVec = (Vector)vec.clone();
public void paintComponent(Graphics gin)
super.paintComponent(gin);
Graphics2D g2 = (Graphics2D)gin;
// setBackground(Color.white);
Color bl = Color.blue;
g2.setPaint(bl);
g2.setStroke(new BasicStroke(5.0f));
drawData(g2,dataVec);
g2.setPaint(Color.gray);
g2.setStroke(new BasicStroke(0.5f));
g2.draw(new Rectangle2D.Double(0, 0,xLength,yLength));
g2.setStroke(new BasicStroke(1.5f));
g2.draw(new Line2D.Double(xMargin, yMargin,xMargin,yLength -yMargin));
g2.draw(new Line2D.Double(xMargin, yLength -yMargin,xLength -xMargin,yLength -yMargin));
System.out.println("End1 ");
public Dimension getPreferredSize(){
if (dataVec.size()*(xGap+xWidth) > xLength)
xLength = (int)(dataVec.size()*(xGap+xWidth));
return new Dimension(xLength,yLength);
else
return new Dimension(xLength,yLength);
protected void drawData(Graphics2D g2, Vector vec)
if (vec == null || vec.size() == 0)
return;
//Check if expansion is required or not
if (vec.size()*(xGap+xWidth) > (xLength - 2*xMargin))
xLength = (int)(vec.size()*(xGap+xWidth)+xGap);//Expanded
setPreferredSize(new Dimension(xLength,yLength));
double maxTime = 0.0;
double minTime = 0.0;
double t=0.0;
double total=0.0;
for (int i=0;i<vec.size();i++)
if ((t = ((Data)vec.elementAt(i)).getTime()) > maxTime)
maxTime = t;
if (t < minTime)
minTime =t;
total += t;
avgTime = total/vec.size();
System.out.println("Avg:"+avgTime+" tot:"+total);
double scale = (yLength - 2*yMargin - 2*yGap )/(maxTime - minTime);
//Now the y-axis scale is calculated, we can draw the bar.
//Currently only bar is supported
//I asume data are in the order of dates otherwise have to sort it here
for (int i=1;i<=vec.size();i++)
//Set color to fill
if (((Data)vec.elementAt(i-1)).getColor() != null)
g2.setPaint(((Data)vec.elementAt(i-1)).getColor() );
//Fill
g2.fill(new Rectangle2D.Double(xMargin+xGap+(i-1)*(xGap+xWidth), yMargin+yGap+/*length of active y axis*/
(yLength-2*yMargin-2*yGap)-/*y value converted to scale*/(((Data)vec.elementAt(i-1)).getTime()- minTime)*scale,
xWidth,(((Data)vec.elementAt(i-1)).getTime()- minTime)*scale+yGap));
g2.setPaint(Color.black);
g2.setStroke(new BasicStroke(0.5f));
g2.draw(new Rectangle2D.Double(xMargin+xGap+(i-1)*(xGap+xWidth), yMargin+yGap+/*length of active y axis*/
(yLength-2*yMargin-2*yGap)-/*y value converted to scale*/(((Data)vec.elementAt(i-1)).getTime()- minTime)*scale,
xWidth,(((Data)vec.elementAt(i-1)).getTime()- minTime)*scale+yGap));
g2.setPaint(Color.blue);
float[] dash1 = {10.0f};
g2.setStroke(new BasicStroke(1.5f,BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f));
g2.draw(new Line2D.Double(xMargin,
yMargin+yGap+/*length of active y axis*/(yLength-2*yMargin-2*yGap)-
/*y value converted to scale*/(avgTime- minTime)*scale,
xMargin+(xGap+xWidth)*vec.size()+xGap,
yMargin+yGap+/*length of active y axis*/(yLength-2*yMargin-2*yGap)-
/*y value converted to scale*/(avgTime- minTime)*scale));Replace getBounds(Rectangle) by the following.
public Rectangle getBounds(Rectangle rv){
if (rv != null) {
rv.x = 0; rv.y = 0; rv.width = xLength; rv.height = yLength;
return rv;
} else
return new Rectangle(xLength,yLength); -
Custom paint() and rare repainting
I have made custom paint() method like this:
@Override
public void paint(Graphics g){
int time;
if(renderer != null)
renderer.updateImage();
time = Simulation.getCurrentStepTime();
if(time>=0) labelCurrentTimeVal.setText(""+time);
else labelCurrentTimeVal.setText("-");
time = Simulation.getAverageStepTime();
if(time>=0) labelAvgTimeVal.setText(""+time);
else labelAvgTimeVal.setText("-");
super.paint(g);
} I have some calculations going on in the background (separate thread). 'renderer' is responsible for repainting the JLabel holding an ImageIcon (which gets changed by the calculations). The case is that my background calculations take a few seconds. After they're done I call the repaint() method, which updates the image and paints the whole thing.
My problem is that I want to have up-to-date info on how much the iteration is taking so I`ve made the labelCurrentTimeVal JLabel to display it. The label only repaints when I call the repaint() method. However when I keep moving some slider in this panel repaint gets called all the time (I can see the labelCurrentTimeVal value changing constantly as I move the knob).
So what should I do to make the repaint() method get called often enough (20-30 times /sec to get about 20-30 fps)? I tried creating a different thread that calls repaint all the time (just to test it) and it doesn't solve the case.new Runnable() {
public void run() {
while(true)
if(MainWindow.instance != null)
MainWindow.instance.repaint();
};I`ve made same code to represent the problem. The calculationThread does the calculations - in this case sets the iteration counter and the repaintThread is supposed to update the GUI and repaint it once in a while. GUI doesn't update at all and I don't get why?
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main extends JFrame{
private JPanel panel;
private JLabel label;
public static Main window;
private Runnable calcThread,repaintThread;
private static int it;
public static void main(String[] args) {
new Main();
private void createComponents(){
window = this;
panel = new JPanel();
label = new JLabel("iteration:");
panel.setPreferredSize(new Dimension(200,200));
panel.add(label);
this.add(panel);
this.pack();
this.setVisible(true);
public Main(){
createComponents();
calcThread = new Runnable(){
public void run(){
int i=0;
while(true){
Main.it = i;
System.out.println("check - iteration: "+i);
i++;
repaintThread = new Runnable(){
public void run(){
while(true){
try{
wait(30);
label.setText("iteration: "+it);
window.repaint();
}catch(InterruptedException e){}
calcThread.run();
repaintThread.run();
} -
Design advice for custom painting
Hi,
Can someone give me some high-level design advice on designing a JPanel subclass for custom painting? My panel class is becoming very complex, with lots of drawing and scaling methods, so I'm wondering if I could abstract away some of these graphical elements by creating new classes to make the design more object-oriented. However, I'm finding that there are also disadvantages in representing some of my graphic components as classes. Specifically,
1. It will lead to a much higher level of class coupling. My panel will depend on all these new classes to work correctly. In fact the situation is even worse because my panel is an inner class and, to do some of the scaling, needs to use methods from an object stored in the parent class. I would therefore have to also pass this object reference as an argument to many of these new classes.
2. It will lead to a lot of awkward passing of data between classes. For example, I need to use g2.drawImage(img, x, y, w, h, this), so I will have to pass not only the graphics context but also the panel reference itself.
Is it common for panel subclasses that do custom painting to be complex?
thanks,
EricI wrote the map view for a commercial GIS system. Drawing and scaling on a JPanel is challenging, but it need not be complex.
1. To eliminate class coupling, you need to create a couple of interfaces: Renderable (what you want drawn) and Renderer (the thing doing the low-level drawing). Renderer will have before and after setup and reset methods (to do things like scaling and rotation), and methods that the renderables can use to draw graphics. The Renderable interface can be as simple as a single method: draw(Renderer).
Every type of graphic that you draw on the screen would be a different class that implements Renderable, and which knows how to draw itself using whatever lower-level drawing commands you put in the Renderer. If you construct each Renderable in terms of java.awt.Shape, then Renderable.draw() could call a method Renderer.draw(java.awt.Shape, java.awt.Color).
2. The Panel becomes fairly simple. It has a Renderer and a collection of Renderable objects. Its paint() method calls the Renderer setup method, calls Renderable.draw(Renderer) on each object, and calls the Renderer reset method. Each Renderable in turn calls Renderable.draw(java.awt.Shape, java.awt.Color) one or more times.
Renderer should get a Graphics2D from the Panel when the setup method is called. That's when the Renderer does all of the scaling, positioning, and rotation on the Graphics2D. The Renderable implementations shouldn't even need to know about it.
I don't think custom painting code is necessarily complex, merely challenging to write. If you're only drawing a few lines and circles, you probably don't have to be too concerned about design elegance and code maintainability. The map view I designed for our GIS system, on the other hand, has to handle all kinds of map geometry, icons, text, and aerial photos. -
JScrollPane function with Custom Paint ???
Hi, I'm having a problem with scrolling with components for which I've overidden the paint method for.
I have a scrollpane which contains a ContentPanel (my own subclass of JPanel in which I implemented paint and paintComponent). The ContentPanel contains Subclasses JButton's which also have their own paintComponent methods.
Problem: Everything (including scrollbars) paint correctly initially. The problem arises when one tries to scroll. When I pull the scrollbar in any direction, the JButtons paint oscillate between painting themselves at the correct scrolled position and at the original position in the Viewport. Then when one lets go of the scroll, the component rests in exactly the same position in the Viewport as it started.
I tried implementing the Scrollable inteface, still no luck. The documentation seems to imply that custom painting should have no effect on scrolling because the content is contained in the view and the ScrollBar commissions a Viewport class to help it move around. I'm not sure, but it seems like it should not be the result of my overidding the paint methods.
I'm so confused, is there something else I need to implement to use JScrollPanes, like Adjustment Listener?
Thanks for your help, AuroraDear Tom,
It looks like the code you have was originally made for awt, not swing. In swing, one should override the paintComponent(Graphics g) method, not the paint() method.
For reasons why check out this tutotial on how painting works.
http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
The reason why you need to call super.paintComponent() in the JPanel is because the JPanel you have is not completely opaque, (I think). Anyway, it has to do with how painting works.
public class myPanel extends JPanel
public myPanel()
setVisible(true);
setSize(600,200);
setLayout(null);
setBackground(Color.white);
myBox m1 = new myBox();
//is the bounds of myBox set appropriately??? Perhaps you need to setBounds() in the constructor of mybox.
add(m1);
public void paintComponent(Graphics g)
super.paintComponent(g);
g.setColor(Color.black);
g.drawString("Test", 10, 13);
m1.paint(g);
//this is important. The subcomponents will not paint themselves unless they are told to by their containers.
In Swing, basically painting works as a hierarchy where the top level Component paints itself and then paints all it's children component, they paint their children and so on. Swing also determines many important things using the bounds of each component. To ensure correct painting and listening behavior, make sure the bounds for your myBoxes are the correct size. Also, implement public void paintComponent(Graphics g) in the myBox so that it will draw it's own rectangle when called by myPanel.
If that doesn't work, check out how myPanel is being added to the overall JFrame. It may not be displaying correctly because you have forgotten to add it or don't have a layout manager etc.
Good luck,
Aurora -
(Another) problem with custom painting using JApplet and JPanel
Hi all,
I posted regarding this sort of issue yesterday (http://forums.sun.com/message.jspa?messageID=10883107). I fixed the issue I was having, but have run into another issue. I've tried solving this myself to no avail.
Basically I'm working on creating the GUI for my JApplet and it has a few different JPanels which I will be painting to, hence I'm using custom painting. My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public class TetrisClone extends JApplet {
public void init() {
setSize( 450, 500 );
Container content = getContentPane();
content.add( new mainGUI(), BorderLayout.CENTER );
content.add( new rightGUI() , BorderLayout.LINE_END );
class mainGUI extends JPanel {
// Main bit where blocks fall
public mainGUI() {
setBackground( new Color(68,75,142) );
setPreferredSize( new Dimension( 325, 500 ) );
validate();
public Dimension getPreferredSize() {
return new Dimension( 450, 500 );
public void paintComponent( Graphics g ) {
super.paintComponent(g);
// As a test. This shows up fine.
g.setColor( Color.black );
g.fillRect(10,10,100,100);
g.setColor( Color.white );
g.drawString("Main",45,55);
class rightGUI extends JPanel {
BufferedImage img = null;
int currentLevel = 0;
int currentScore = 0;
int currentLines = 0;
public rightGUI() {
// The right panel. Has quite a few bits. Starts here..
FlowLayout flow = new FlowLayout();
flow.setVgap( 20 );
setLayout( flow );
setPreferredSize( new Dimension( 125, 500 ) );
setBackground( new Color(27,34,97) );
setBorder( BorderFactory.createMatteBorder(0,2,0,0,Color.black) );
// Next block bit
JPanel rightNext = new JPanel();
rightNext.setPreferredSize( new Dimension( 100, 100 ) );
//rightNext.setBackground( new Color(130,136,189) );
rightNext.setOpaque( false );
rightNext.setBorder( BorderFactory.createEtchedBorder(EtchedBorder.LOWERED) );
Font rightFont = new Font( "Courier", Font.BOLD, 18 );
// The player's playing details
JLabel rightLevel = new JLabel("Level: " + currentLevel, JLabel.LEFT );
rightLevel.setFont( rightFont );
rightLevel.setForeground( Color.white );
JLabel rightScore = new JLabel("Score: " + currentScore, JLabel.LEFT );
rightScore.setFont( rightFont );
rightScore.setForeground( Color.white );
JLabel rightLines = new JLabel("Lines: " + currentLines, JLabel.LEFT );
rightLines.setFont( rightFont );
rightLines.setForeground( Color.white );
JPanel margin = new JPanel();
margin.setPreferredSize( new Dimension( 100, 50 ) );
margin.setBackground( new Color(27,34,97) );
JButton rightPause = new JButton("Pause");
try {
img = ImageIO.read(new File("MadeBy.gif"));
catch (IOException e) { }
add( rightNext );
add( rightLevel );
add( rightScore );
add( rightLines );
add( margin );
add( rightPause );
validate();
public Dimension getPreferredSize() {
return new Dimension( 125, 500 );
public void paintComponent( Graphics g ) {
super.paintComponent(g);
g.setColor( Color.black );
g.drawString( "blah", 425, 475 ); // Doesn't show up
g.drawImage( img, 400, 400, null ); // Nor this!
System.out.println( "This bit gets called fine" );
}Any help would be greatly appreciated. I've read loads of swing and custom painting tutorials and code samples but am still running into problems.
Thanks,
Tristan PerryMany thanks for reminding me about the error catching - I've added a System.out.println() call now. Anywhoo, the catch block never gets run; the image get call works fine.
My problem was/is:
"My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:"
I guess I should have expanded on that. Basically whatever I try to output in the public void paintComponent( Graphics g ) method of the rightGUI class doesn't get output.
So this doesn't output anything:
g.drawString( "blah", 425, 475 ); // Doesn't show up
g.drawImage( img, 400, 400, null ); // Nor this!
I've checked and experimented with setOpaque(false), however this doesn't seem to be caused by any over-lapping JPanels or anything.
Let me know if I can expand on this :)
Many thanks,
Tristan Perry
Edited by: TristanPerry on Dec 10, 2009 8:40 AM -
Java.io.NotSerializableException: paint.Main$1
hi everybody this is my problem...
i have this code:
public class Main extends JFrame
class figura implements Serializable
Point x, y;
int tipo;
int rettipo(){ return tipo;}
public Point retx(){ return x;}
public Point rety(){ return y;}
void ponertipo(int a){ tipo = a; }
void ponerpx(Point a){ x = a; }
void ponery(Point a){ y = a;}
JFileChooser archivos = new JFileChooser();
Vector almacen = new Vector(1);
figura temp = new figura();
.... //more code....
i wanna save temp object in a file...
....//more code before this...
archivos.showSaveDialog(Main.this);
File archivo;
FileOutputStream archivo2 = null;
ObjectOutputStream obj = null;
archivo = archivos.getSelectedFile();
try{
archivo2 = new FileOutputStream(archivo.getAbsolutePath());
obj = new ObjectOutputStream(archivo2);
obj.writeObject(temp);
obj.close();
catch(Exception ex)
Throwable tro;
ex.printStackTrace();
tro=ex.getCause();
tro.getMessage();
and this is what i got:
java.io.NotSerializableException: paint.Main$1
and this:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Any ideas?why with static the problem is solved?Because a static nested class doesn't have a hidden reference to the outer object.
i understand
that static makes that all instance of the class will
share the same values of their attributesNo it doesn't. It just means the above, and also that the class doesn't have access to instance data members of the enclosing class.
if the class is static i wont be able to save more
than one figure. am i right?No you're not, see above. -
Custom Painting in Swing Panels.
I am trying to implement a custom painted panel on a JFrame. The panel performs custom painting in a separate thread. In additon, the frame also adds other swing panels (containing standard components) dynamically as per menu selection. I use box layout on frame to add / remove panels.
The paint panel doesnt render properly whenever other panels are added or replaced. The paint panel is rendered only when no other are panels added to the frame.
There is no problem however with adding / replacing components-only panels containing no custom painting.
Please help me understand what I am missing. Any clues / suggestions most welcome
sridharHi,
You have problem only when adding custom painting JPanel to the same custom painting JPanel??? Are you layering your painting methods??? Like the most upper JPanel paints and then the childs??? What do you get for drawings??? Do you use invoque later method??? What is your priority on the Threads you are using???
JRG -
I have an app that does custom painting in a extended JWindow, however, when I add controls (an extended JButton that does custom painting) the entire window, not including any components turns gray. This happens if I use paint or paintComponent. I am starting to think that the delegate UI is causing a problem, this is because if I remove the paintComponents, I get the image as usual. Any ideas???
A code snippet shows the gist
class sWindow extends JWindow {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(mainform, null, 0, 0);
paintComponents(g);
class sButton extends JButton {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
switch(state) {
case DEFAULT:
g2.drawImage(defaultImage, 0, 0, getSize().width, getSize().height, this);
break;
case PRESSED:
g2.drawImage(pressedImage, 0, 0, getSize().width, getSize().height, this);
break;
case HIGHLIGHTED:
g2.drawImage(hilightedImage, 0, 0, getSize().width, getSize().height, this);
break;
case DISABLED:
g2.drawImage(disabledImage, 0, 0, getSize().width, getSize().height, this);
break;
}Hi,
You have problem only when adding custom painting JPanel to the same custom painting JPanel??? Are you layering your painting methods??? Like the most upper JPanel paints and then the childs??? What do you get for drawings??? Do you use invoque later method??? What is your priority on the Threads you are using???
JRG -
I have created a JPanel which is a long rectangle "setPreferredSize(new Dimension(321, 21));" that performs custom painting . The custom painting is to represent a loop; a colored rectangle moves along the length of the panel when the process loops it repeats the painting. I have to create many instances of this panel and add these instances to the program's main panel. I have managed to get the colored rectangle to move through every instance of the panel but as each one progress they are not in sync, they each need to be at the same point of the panel at the same time. I have used a thread to control the custom painting and I think because each instance of the panel uses its own thread they are being interleaved which is resulting in time lags. Can anyone give me some ideas of how I can imlement this so each colored rectangle is at the same point at the same time. Here are some relevent code snippets:
* This method is called from within paintComponent
private void moveRect(Graphics g){
if(looped==true){
Dimension d = getSize();
offscreen = createImage(d.width, d.height);
offscreensize = d;
offgraphics = offscreen.getGraphics();
offgraphics.setColor(new Color(115,212,236));
offgraphics.fillRect(xpos+1, 1, 19 ,19);
g.drawImage(offscreen, 0, 0, this);
public void run(){
while(true){
for(xpos = 0;xpos<=320;xpos = xpos+20){
repaint();
try{
Thread.sleep(116);
}catch(InterruptedException e){}
Thanks for your reply. The Timer seems to work better. I have created a separate class for the Timer and when a new instance of the Bar JPanel is created a Timer is also created. I have made the Time class a JPanel, the problem I am having now is I need to place the Time JPanel on top of the Bar JPanel but below the Graphics on the Bar JPanel. When I try to do it the Time JPanel just sits on top of the Bar JPanel and all the graphics are not seen. The Time JPanel needs to be in the back ground; Is there a method call like setBackground that accepts components, or any ideas on how this can be achieved?
-
Custom painting on jpanel with scrollable
i have a jpanel with custom painting. because the painting can be wider than the view of the panel i need to implement scrollbars. i have experimented with implementing scrollable and using scrollpanes but i have no result. i need a hint or a tutorial how this can be done
ok, that was the key. but perhaps you can help me with two other problems:
because i dont know how large my panel ( or my scroll-area) has to be, i need to expand it on demand. i tried setpreferredsize for that reason, but nothing happens. i think this method is only for initializing but doesnt seem to function properly at a later point.
next prop:
when i scroll my custom panting area the jpanel isnt repainted. i have some difficulties finding the right eventlistener so that i can get scrollbar events (repaint after each move) -
Hi,
I'm not sure if this is supposed to go here but I want to get my iPhone 5 custom-painted like how ColorWare do it but since I live in London I'm looking for somewhere in London that does this?
I'd prefer it if it's somewhere I can physically go and ask and enquire.
But anything in London is good.
Thanks,
Yousef
PS - here's some visual aid: http://www.anostyle.com/includes/images/gallery/home_1.jpg
http://uncrate.com/p/2012/10/colorware-iphone-5-xl.jpgI am not concerned
So take it to the US
You are not going to get advice on voiding your warranty on an APPLE HOSTED Forum -
I am trying to paint a pattern within the visible rect of a JTree. I am doing the painting in a custom TreeUI class. My pattern should always appear at the bottom of the tree even while a user is scrolling.
This sounded very easy. I would just retreive the visibleRect of the JTree the UIDelegate is managing within paint(Grphics,JComponent), and simply call g2D.setPaint(texturePattern), g2D.fill(rect);. This does not work well at all. What happens is the tree does not show the pattern while scrolling, although the paint is being called. When I expand a node, then it works. If I scroll up and then back down, I noticed a smeared version of pattern near the bottom of the tree.
Here is my little test. I am putting it here so someone can try it out. This painting issue is hard to explain but easy to recreate. This version just tries to draw a red 20X20 rectangle at the top left corner of the tree, following the visibleBounds.
public class TestTreeUI extends BasicTreeUI
public static ComponentUI createUI(JComponent c)
return new TestTreeUI();
public void paint(Graphics g, JComponent c)
Rectangle r = tree.getVisibleRect();
// this always prints the right rect but does not always paint correctly
System.out.println(r);
g.setColor(Color.red);
g.drawRect(r.x, r.y, 20, 20);
super.paint(g,c);
}Any clues would be greatly appreciated.bump
-
Java Logigng, Custom FileHandler level problem.
Dears,
I would like to use java builin logigng facility, but the problem is that it is not providing the facility of daily file rolling in FIleHandler as log4J is providing the facility in DailyRollingFileAppender
I found the custom File handler form the following thread:
http://forum.java.sun.com/thread.jspa?forumID=256&threadID=421131
But the problem is that now I cannot able to change the logger level at runtime using
Logger.setLevel() or using JMX Mbeans exposed by java.util.logging.
I was able to change the loglevel when I was using java.util.logging.FileHandler
I found that level setting is done at Logger also at handler level.
So how can I handle this?
I want to log file on daily basis + also want to provide facility to change level using JMX.
thanks.Okay, I figured out my problem, but I'm not sure how much it's going to help you. My problem was the same as yours (I just didn't know it). It had nothing to do with multiple threads, but had to do with the fact that I was reinitializing the LogManager multiple times (I have the init in a static class that multiple classes use and didn't realize the number of times it was getting called).
Now, I do have a possible suggestion for changing handlers, if you're okay doing it inside code (instead of using a config file). Technically, you could creat your own config file and change some stuff.
Anyway, here's what I do to change handlers:
private static Logger logger = Logger.getLogger(Archive.class.getName());
(in function)
try {
logger.removeHandler(reportArchiveHandler);
} catch (NullPointerException e) {
// ignore
reportArchiveHandler = new FileHandler(this.getCurrentLogDir() + "/log.txt", 50000, 1, true);
reportArchiveHandler.setLevel(Level.INFO);
reportArchiveHandler.setFormatter(new AuditFormatter());
logger.addHandler(reportArchiveHandler);
LogManager.getLogManager().addLogger(logger);
}That changes the handler and doesn't create any new files. The only problem is you can't just read a new config file.
Hope that helps a little,
Mike
Maybe you are looking for
-
How do you delete game center without deleting the data from the games?
Our family has 4 apple products all assigned to one apple id. When my son set up his game center account it link all of your games together. We have tried many times to delete it without any luck. Is there any way to delete in with out wiping out
-
Dear All, We plan to upgrade Oracle 9.2.0.1 under Windows 2003 Server 32-bit to Oracle 11g. There are two methods to upgrade using Database Upgrade Assistant (DBUA) and Manual. Which one is tter? Would there be any performance issues? Do we need DBUA
-
Problem About J2EE RI and PetStore Demo
Hello ^^ I have a problem about j2ee & petstore. I trird to set up sun j2ee RI 1.3.1 + pet store on win2000 or redhat. Everything run ok. But when I changed web port 8000 to any port (included 80), j2ee ri server showed the error message below : java
-
MIME type "application/x-mplayer2", but you don't have a plug-in installed.
I went to http://www.microsoft.com/Windows/MediaPlayer/ and installed Windows Media Player 9 for Mac OS X, but it still doesn't work. All I want to do is listen to Sirius online... Thank you!!!
-
How to view database performance in OEM back 8 hour
Hello All, I have recently installed OEM 11g. Please can I know how to view the performance of the database back 8 hour as I can see the performance for an hour only on the performance page. Thanks.