Multiple transparent JPanels paint problem (smearing strings)
I created full screen JWindow application.
I created three panels:
MainPanel - non transparent
PPIPanel - transparent
GlassPanel - transparent.
All three panel and JWindow has the same bounds. Then I added PPIPanel and GlassPanel to MainPanel and then I added MainPanel to JWindow.
MainPanel.add(PPIPanel);
MainPanel.add(GlassPanel);
JWindow.getContentPane().add(MainPanel);
Whole application displays Air Traffic Situation comming from RADAR. MainPanel is a black background with airways, PPIPanel displays aircrafts and GlassPanel is MouseEvent listener for ZOOM, CENTER and other mouse operations.
The painting code is always placed in paint(Graphics g) metod of each component. All aircraft are painted on the transparent PPIPanel with small dot fillOval() and two BOLD strings g.drawString("Aircraft")descibing aircraft.
paint(Graphics g) {
g.setColor(Color.GREEN);
g.setFont(bold font);
iterate Collection of aicrafts {
g.fillOval(x,y,4,4);
g.drawString(x+3,y+3,"Aircraft xxx");
g.drawString(x+3,y+18,"Flight level");
The situation is changing every 4 seconds and every 4 seconds special Thread calls repaint() method on PPIPanel to referesh the situation.
The main problem is garbage remaining after refresh. Some aircrafts has smeared label after repaint ( probably because multiple transparent panels).
What are your proposals to solve the problem. I'm just a java begginer so I need clear explenation (i.e. code example).
just to make it clear
paint(Graphics g) {
super.paint(g)
g.setColor(Color.GREEN);
g.setFont(bold font);
iterate Collection of aicrafts {
g.fillOval(x,y,4,4);
g.drawString(x+3,y+3,"Aircraft xxx");
g.drawString(x+3,y+18,"Flight level");
or
paintComponent(Graphics g) {
g.setColor(Color.GREEN);
g.setFont(bold font);
iterate Collection of aicrafts {
g.fillOval(x,y,4,4);
g.drawString(x+3,y+3,"Aircraft xxx");
g.drawString(x+3,y+18,"Flight level");
should work..
Cheers
Mike
Similar Messages
-
Problem with multiple transparent JPanels
Hi,
I'm currently trying to implement some kind of message box that can fade in and out. This message box is a subclass of JComponent, the message it contains can be an arbitrary Swing-Component.
The message container and the message itself have the same background color. When fading, the (partly transparent) colors of the of the container and the message are added, which I do not want.
Here are two images to illustrate my problem:
What I have: http://www.inf.tu-dresden.de/~ab023578/javaforum/reality.gif
What I want: http://www.inf.tu-dresden.de/~ab023578/javaforum/wish.gif
Here is the code:
import java.awt.*;
import javax.swing.*;
public class Main {
static float transparency = 0f;
public static void main(String[] args) {
JPanel jpBack = new JPanel() {
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.clearRect(0, 0, getWidth(), getHeight());
g2d.setColor(getBackground());
AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency);
g2d.setComposite(alpha);
g2d.fillRect(0, 0, getWidth(), getHeight());
jpBack.setBackground(Color.WHITE);
jpBack.setLayout(null);
JPanel jpContainer = new JPanel();
jpContainer.setBackground(Color.RED);
jpContainer.setLayout(null);
JPanel jpMessage = new JPanel();
jpMessage.setBackground(Color.RED);
JLabel jlMessage = new JLabel("MESSAGE");
jpBack.add(jpContainer);
jpContainer.add(jpMessage);
jpMessage.add(jlMessage);
jpContainer.setBounds(10, 10, 120, 100);
jpMessage.setBounds(10, 10, 100, 50);
JFrame frame = new JFrame();
frame.setBounds(0, 0, 150, 150);
frame.setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(jpBack);
frame.setVisible(true);
for (double a = 0; true; a += 0.01D) {
try {
Thread.sleep(10);
catch (InterruptedException e) {}
transparency = (float)Math.abs(Math.sin(a));
jpBack.repaint();
}I understand that the Porter-Duff-Rule SRC_OVER causes the container to be drawn over the message (or vice versa) and both of them over the background. I think what I need is a way to handle the whole jpContainer-Panel and all its subcomponents as a single source image. Is that possible?Thank you for your answer, Sarcommand. Unfortunately the test program I provided is a bit too simple as your solution works here but not for my original problem. :|
Let me explain what I want to achieve and why.
I'm writing a tool for algorithm visualisation. Currently I am dealing with a parsing algorithm (having compontents such as an automaton with an input tape, output tape and a stack). Those components (containers) can contain multiple JComponents (GraphicalObjects), which display a BufferedImage that can be altered during the animation.
I want to create my message windows the same way. A container that contains GraphicalObjects (or, if necessary, any other Swing component). One GraphicalObject has a very limited field of responsibility: mereley displaying its information.
Aligning the GraphicalObject is one of the container's responsibilities.
What I'm currently trying to do is to put my GraphicalMessage into the center of a container, leaving an offset on the left/right/upper/lower side. This is why I need the same background color for both the GraphicalMessage and the MessageContainer, I don't want the user to see that there are actually two JComponents on top of each other.
While I could use another approach for text messages I prefer this one as I would be able to fade arbitrary Containers and their GraphicalObjects .
Here is the code:
import java.awt.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
public class Main {
static float transparency = 0f;
public static void main(String[] args) {
JPanel jpBack = new JPanel() {
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
g2d.clearRect(0, 0, getWidth(), getHeight());
g2d.setColor(getBackground());
AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency);
g2d.setComposite(alpha);
g2d.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
jpBack.setBackground(Color.WHITE);
jpBack.setLayout(null);
JPanel jpContainer = new JPanel();
jpContainer.setBackground(Color.RED);
jpContainer.setLayout(null);
GraphicalMessage msg = new GraphicalMessage();
jpBack.add(jpContainer);
jpContainer.add(msg);
jpContainer.setBounds(10, 10, 120, 100);
msg.setBounds(10, 10, 160, 60);
JFrame frame = new JFrame();
frame.setBounds(0, 0, 150, 150);
frame.setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(jpBack);
frame.setVisible(true);
float stepSize = 0.01f;
float step = stepSize;
for (float a = 0; true; a += step) {
try {
Thread.sleep(10);
catch (InterruptedException e) {}
if (a >= 1) {
step = -stepSize;
a -= stepSize;
if (a <= 0) {
step = stepSize;
a += stepSize;
msg.updateInternalContent();
msg.redraw();
transparency = a;
jpBack.repaint();
class GraphicalMessage extends JComponent {
private String text;
private Graphics2D ig2d;
private BufferedImage image;
public GraphicalMessage() {
setLayout(null);
image = new BufferedImage(100, 50, BufferedImage.TYPE_INT_ARGB);
ig2d = image.createGraphics();
ig2d.setColor(Color.BLACK);
ig2d.setBackground(Color.RED);
ig2d.setFont(new Font("Courier New", Font.BOLD, 20));
updateInternalContent();
redraw();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(image, 0, 0, null);
public void redraw() {
ig2d.clearRect(0, 0, image.getWidth(), image.getHeight());
ig2d.drawString(text, 0, 20);
public void updateInternalContent() {
text = String.valueOf((int)(Math.random() * 10000));
}A possibility to erase the text from the BufferedImage without having to draw a rectangle would help me as well. -
How to draw an image on transparent JPanel?
I want to draw an image on the transparent JPanel. How to do it?
I do like this:
( In constructor )
setOpaque(false);
String imageName = "coral.jpg";
iimage_Bg = Toolkit.getDefaultToolkit().getImage(imageName);
( In paintComponent( Graphics g ) )
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage( iimage_Bg, 0, 0, getWidth() , getHeight() , Color.white, null );
But it doesn't work. Please help me!
Thank you very much.
coral9527Check the values that are returned from getWidth() and getHeight(). If they either are zero, then paintComponent(Graphics g) never gets called by the components paint(Graphics g) method. I cannot see the how this component has been added or displayed so can give no advice on how you can guarantee getting a valid size. If you have simply added it to a JFrame and called pack(), the size will be zero, as the panel does not contain any components (you would not have this problem if you were adding a JLabel with an ImageIcon for example). Try not packing the frame, and giving it a valid size.
-
An Image JPanel, A semi-transparent JPanel, and non-opaque components
This is a more intelligent re-asking of the question I posed here: http://forum.java.sun.com/thread.jspa?threadID=579298&tstart=50.
I have a class called ImagePane, which is basically a JPanel with an image background. The code is much like the ImagePanel posted by camickr, discussed in this topic: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=316074 (except mine only draws the image, it does not tile or scale it).
On top of my ImagePane, I can place another component, TransparentContainer. This again extends JPanel, only a color is specified in the constructor, and it is drawn at about 70% opacity. This component is meant to help increase the readability of text components that blend with the background image, without blocking out the background image completely.
This works very well, until I need to add a component, like, say, a non-opaque JRadioButton in a ButtonGroup. When you select a new JRadioButton at runtime, the semi-transparent JPanel fills with a combination of a completely opaque color (the one specifies to the TransparentContainer) and garbage from the non-opaque component being redrawn.
I have noticed that the UI is restored to being non-messed up if you place another application window on top of it and then move it. So apparently, one solution is to redraw the entire UI, or just the part that has the JRadioButton on it, every time the radio button is clicked. However, this seems unnecessarily complicated. It seems to me that I am missing something in my TransparentContainer's paintComponent() method. Does anyone have any ideas?
Here is my TransparentContainer code, if it will help:
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JPanel;
public final class TransparentContainer extends JPanel
/* Private Fields: For use only by this class.
* These fields hold information needed by more
* than one method of this class.
private boolean fullTransparencyEnabled;
private Color baseColor;
private Color outerBorderColor;
private Color innerBorderColor;
private int obw;
private int ibw;
private int cbw;
/* -- START OF METHODS -- */
/* public TransparentContainer(Color color, boolean fullTrans)
* Initiallizes the transparent container object
* with 'color' as its base color.
public TransparentContainer(Color color, boolean fullTrans)
fullTransparencyEnabled = fullTrans;
baseColor = color;
Color borders[] = findBorderColors();
outerBorderColor = borders[0];
innerBorderColor = borders[1];
obw = 3;
ibw = 1;
cbw = obw + ibw;
/* private Color[] findBorderColors(Color base)
* Calculates the colors for the outer and inner
* borders of the object based on the base color.
private Color[] findBorderColors()
Color borders[] = new Color[2];
int colorData[] = new int[9];
colorData[0] = getBaseColor().getRed();
colorData[1] = getBaseColor().getGreen();
colorData[2] = getBaseColor().getBlue();
colorData[3] = colorData[0] - 50; // outerBorder red
colorData[4] = colorData[1] - 45; // outerBorder green
colorData[5] = colorData[2] - 35; // outerBorder blue
colorData[6] = colorData[0] + 30; // innerBorder red
colorData[7] = colorData[1] + 30; // innerBorder green
colorData[8] = colorData[2] + 20; // innerBorder blue
/* Make sure the new color data is not out of bounds: */
for (int i = 3; i < colorData.length; i++)
if (colorData[i] > 255)
colorData[i] = 255;
else if (colorData[i] < 0)
colorData[i] = 0;
borders[0] = new Color(colorData[3], colorData[4], colorData[5]);
borders[1] = new Color(colorData[6], colorData[7], colorData[8]);
return borders;
/* public Color getBaseColor()
* Returns the baseColor of this object.
public Color getBaseColor()
return baseColor;
/* public Color getOuterColor()
* Returns the outerBorderColor of this object.
public Color getOuterColor()
return outerBorderColor;
/* public Color getInnerColor()
* Returns the innerBorderColor of this object.
public Color getInnerColor()
return innerBorderColor;
/* public boolean getFullTransEnabled()
* Returns whether or not this object will render
* with all of its transparency effects.
public boolean getFullTransEnabled()
return fullTransparencyEnabled;
/* protected void paintComponent(Graphics g)
* Paints the component with the borders and colors
* that were set up in above methods.
protected void paintComponent(Graphics g)
Graphics2D g2d = (Graphics2D) g;
AlphaComposite alphaComp;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setColor(getBaseColor());
/* Draw the main body of the component */
if (getFullTransEnabled())
alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
g2d.setComposite(alphaComp);
else
alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g2d.setComposite(alphaComp);
g2d.fillRect(cbw, cbw, super.getWidth() - 2 * cbw, super.getHeight() - 2 * cbw);
alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
g2d.setComposite(alphaComp);
/* Draw the inner border: */
g2d.setColor(getInnerColor());
g2d.fillRect(obw, obw, ibw, super.getHeight() - obw * 2); // left border
g2d.fillRect(obw, obw, super.getWidth() - obw, ibw); // top border
g2d.fillRect(super.getWidth() - cbw, obw, ibw, super.getHeight() - obw * 2); // right border
g2d.fillRect(obw, super.getHeight() - cbw, super.getWidth() - obw * 2, ibw); // bottom border
/* Draw the outer border: */
g2d.setColor(getOuterColor());
g2d.fillRect(0, 0, obw, super.getHeight()); // left border
g2d.fillRect(0, 0, super.getWidth() + obw, obw); // top border
g2d.fillRect(super.getWidth() - obw, 0, obw, super.getHeight()); // right border
g2d.fillRect(0, super.getHeight() - obw, super.getWidth(), obw); // bottom border
alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g2d.setComposite(alphaComp);
g2d.dispose();
}I added the main method to your TransparentContainer class ...
public static void main(String[] args) {
JFrame f = new JFrame("test transparent container");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TransparentContainer tc = new TransparentContainer(Color.RED, true);
JLabel label = new JLabel("Hello, World!");
tc.add(label);
f.getContentPane().add(tc);
f.setSize(800, 600);
f.setVisible(true);
}...using the code you posted the label was not shown. I modified your paintComponent(Graphics g) method and I did this (see the areas in bold):
/* protected void paintComponent(Graphics g)
* Paints the component with the borders and colors
* that were set up in above methods.
protected void paintComponent(Graphics g)
// Call super so components added to this panel are visible
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
AlphaComposite alphaComp;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setColor(getBaseColor());
/* Draw the main body of the component */
if (getFullTransEnabled())
alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
g2d.setComposite(alphaComp);
else
alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g2d.setComposite(alphaComp);
g2d.fillRect(cbw, cbw, super.getWidth() - 2 * cbw, super.getHeight() - 2 * cbw);
alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
g2d.setComposite(alphaComp);
/* Draw the inner border: */
g2d.setColor(getInnerColor());
g2d.fillRect(obw, obw, ibw, super.getHeight() - obw * 2); // left border
g2d.fillRect(obw, obw, super.getWidth() - obw, ibw); // top border
g2d.fillRect(super.getWidth() - cbw, obw, ibw, super.getHeight() - obw * 2); // right border
g2d.fillRect(obw, super.getHeight() - cbw, super.getWidth() - obw * 2, ibw); // bottom border
/* Draw the outer border: */
g2d.setColor(getOuterColor());
g2d.fillRect(0, 0, obw, super.getHeight()); // left border
g2d.fillRect(0, 0, super.getWidth() + obw, obw); // top border
g2d.fillRect(super.getWidth() - obw, 0, obw, super.getHeight()); // right border
g2d.fillRect(0, super.getHeight() - obw, super.getWidth(), obw); // bottom border
alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
g2d.setComposite(alphaComp);
// Do not dispose the graphics
// g2d.dispose();
}...seems to work fine now. Perhaps you should also add methods or additional constructors so the user can easily change the transparency level...and add some javadoc comments to your constructors ...at a first glance I did not know what fullTrans was
public TransparentContainer(Color color, boolean fullTrans)good luck!! -
Help Please, with Annoying painting problem.
Hi:
I keep running in to this annoying problem:
Swing Components not being re-drawn properly after:
Windows turns on the screensaver
or to a lesser degree if the Java program is Iconified / deiconified.
Components with Images on them get corrupted and the image is not drawn properly, maybe just the top cm or so, but it is annoying..
And I can't figure out what or if anything I am doing wrong.
It happens in a few of my applications.........
mostly those wher I have overidden paintComponent()
If someone would like to see if they have the same thing happen, below is an example that demonstrates the problem.
You will probably need to fiddle with you power settings so that you monitor blanks after 1 min. to avoid having to wait too long.
Run the program, wait for screen to blank out, bring screen back,...
If the java picture is not corrupt try re-sizing the JFrame and see what happens.
I am using Win98SE
I have Java:
java version "1.4.2-beta"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2-beta-b19)
Java HotSpot(TM) Client VM (build 1.4.2-beta-b19, mixed mode)
I would appreciate someone trying this out. Even if it doesn't happen for them.
Or maybe there is a glaring Error in my code.... And if so I could fix it..
Here is an exmple program to demonstrate this.
Two classes, The JPanel was obviously meant to do other things but I cut it down..
The main:
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.net.*;
public class Test extends JFrame
public Test()
super("Test");
Container content = this.getContentPane();
content.setLayout( new BorderLayout() );
URL url = null;
Class ThisClass = this.getClass();
url=ThisClass.getResource("Background.jpg");
StarPanel panel = new StarPanel( url );
content.add( panel , BorderLayout.CENTER );
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(400,400);
this.setVisible( true );
public static void main( String[] args )
Test Example = new Test();
}The JComponent - with overrriden paintComponent()
import java.awt.Image;
import javax.swing.JComponent;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.net.*;
cut down version
public class StarPanel extends JPanel
private Image image = null;
private boolean imageLoaded = false;
public StarPanel( URL imageLocation )
super();
this.setOpaque( true );
loadImage( imageLocation );
public boolean isOpaque()
return true;
public Image getImage()
return this.image;
public boolean hasImage()
return imageLoaded;
public void loadImage( URL imageLocation )
boolean goodLoad = true;
boolean Test = false;
Toolkit T = this.getToolkit();
image = T.getImage( imageLocation );
prepareImage(image, this);
MediaTracker Tracker = new MediaTracker( this );
Tracker.addImage( image , 0 );
try
Tracker.waitForID( 0 );
catch( InterruptedException IE )
System.out.println( "Interrupted loading Image for StarPanel: " + IE.getMessage() );
goodLoad = false;
Test = Tracker.isErrorID( 0 );
if( Test )
goodLoad = false;
if( !goodLoad )
imageLoaded = false;
else
imageLoaded = true;
Tracker = null;
sans any error checking
protected void paintComponent(Graphics g)
super.paintComponent( g );
Graphics2D g2D = (Graphics2D) g;
boolean T = g2D.drawImage(this.getImage(), 0, 0, this.getWidth(), this.getHeight(), this );
}I have tried quite a few different approaches to remove or minimize this problem, and have read everything I can here on paintComponent() and etc
Help would be appreciated.
No dukes cos I somehow have less than 0.
Arrg my code was all neat - before I pasted it in to the code tags.I tried your code and did not notice any painting problems. I'm using JDK1.4.1 on Windows 98.
I don't see any problems with your code. Here is the thread I usually recommend when people want to add an image to a component, in case you want to run another test:
http://forum.java.sun.com/thread.jsp?forum=57&thread=316074 -
Hello!
I have a JFrame with a background painted on it and everything works fine so far, but when I create a JPanel in the JFrame the JPanels grey colour is laying on top of the background. So my question is how to make the JPanel transparent. I read about overriding the paintComponent method, but it didn't work, I'm probably doing something wrong.
This is what I did:
class Transparency extends JPanel {
public Transparency() {}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
contentPanel = new JPanel();
contentPanel.setPreferredSize(new Dimension(mainFrame.getWidth(), 200));
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.add(new Transparency());
mainPanel.add(contentPanel);I would really appreciate some help!Newly created JPanel's have their opacity set to true. This means "I guarantee that I will paint all the pixels within my bounds." For many components this amounts to simply filling in the entire bounds of the component with the background color as the first thing they paint. So by setting the opacity to false the JPanel in question will no longer be a gray blob and will allow any components beneath it to show through.
JPanel#setOpacity(false); The panel in question doesn't even need to be a custom subclass (read: delete that Transparency JPanel subclass). -
Hi,
I have painting problem with adding the JMenuItems dynamically. In the screen1 figure shown below, Menu 2 has has total 10 items, but initially we will show only three items. When the user clicks on the menu item ">>" all the Ten Items in Menu 2 are shown. But, All the 10 items are inserted in a compressed manner as shown in screen 2. When i click on the Menu 2 again, is shows properly as shown in screen 3.
screen 1:
<img src="http://img.photobucket.com/albums/v652/petz/Technical/screen1.jpg" border="0" alt="Screen 1"/>
screen 2:
<img src="http://img.photobucket.com/albums/v652/petz/Technical/screen2.jpg" border="0" alt="Screen 2"/>
screen 3:
<img src="http://img.photobucket.com/albums/v652/petz/Technical/screen3.jpg" border="0" alt="Screen 3"/>
Here is the code:
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class MenuUI implements MouseListener
JFrame frame;
JMenuBar menubar;
JMenu menu1,menu2;
JMenuItem menuItem;
JMenuItem lastMenuItem;
String MENU1_ITEMS[] = {"ONE","TWO","THREE","FOUR","FIVE"};
String MENU2_ITEMS[] = {"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","TEN"};
int MIN_MENU = 3;
public MenuUI()
menubar = new JMenuBar();
/*menu1 = new JMenu("Menu 1");
menu1.setMnemonic(KeyEvent.VK_1);
menu1.getPopupMenu().setLayout(new GridLayout(5,1));
menu2 = new JMenu("Menu 2");
menu2.setMnemonic(KeyEvent.VK_2);
menu2.getPopupMenu().setLayout(new GridLayout(5,2));*/
menu1 = new JMenu("Menu 1");
menu1.setMnemonic(KeyEvent.VK_1);
menu2 = new JMenu("Menu 2");
menu2.setMnemonic(KeyEvent.VK_2);
menubar.add(menu1);
menubar.add(menu2);
createMinMenuItems();
frame = new JFrame("MenuDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(menubar);
frame.setSize(500, 300);
frame.setVisible(true);
public void createMinMenuItems()
for (int i = 0; i < MIN_MENU; i++)
menuItem = new JMenuItem(MENU1_ITEMS);
menu1.add(menuItem);
lastMenuItem = new JMenuItem(">>");
lastMenuItem.addMouseListener(this);
menu1.add(lastMenuItem);
for (int i = 0; i < MIN_MENU; i++)
menuItem = new JMenuItem(MENU2_ITEMS[i]);
menu2.add(menuItem);
lastMenuItem = new JMenuItem(">>");
lastMenuItem.addMouseListener(this);
menu2.add(lastMenuItem);
private void showAllMenuItems(int menuNo)
if(menuNo == 1)
menu1.remove(MIN_MENU);
for (int i = MIN_MENU; i < MENU1_ITEMS.length; i++)
menuItem = new JMenuItem(MENU1_ITEMS[i]);
menu1.add(menuItem);
menu1.updateUI();
else if(menuNo == 2)
menu2.removeAll();
menu2.getPopupMenu().setLayout(new GridLayout((MENU2_ITEMS.length),1));
for (int i = 0; i < MENU2_ITEMS.length; i++)
menuItem = new JMenuItem(MENU2_ITEMS[i]);
//menuItem.setMinimumSize(new Dimension(35,20));
menu2.add(menuItem);
menu2.updateUI();
//menu2.getPopupMenu().invalidate();
//menu2.getPopupMenu().repaint();
//menubar.repaint();
//menubar.invalidate();
//menubar.getParent().repaint();
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
public void mousePressed(MouseEvent arg0)
System.out.println("mousePressed: Menu 1 selected: "+menu1.isSelected());
System.out.println("mousePressed: Menu 2 selected: "+menu2.isSelected());
if(menu1.isSelected())
System.out.println("mousePressed: Menu 1: Show All Items");
showAllMenuItems(1);
else if(menu2.isSelected())
System.out.println("mousePressed: Menu 2: Show All Items");
showAllMenuItems(2);
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
public void mouseClicked(MouseEvent evt)
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
public void mouseEntered(MouseEvent arg0)
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
public void mouseExited(MouseEvent arg0)
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
public void mouseReleased(MouseEvent arg0)
public static void main(String[] args)
MenuUI ui = new MenuUI();// menu2.updateUI();
menu2.getPopupMenu().setVisible(false);
menu2.getPopupMenu().setVisible(true); -
Hello,
I have been teaching my self Java and I have become quite proficient with it, however, I have a problem that I can not fix, or get around.
I have a JMenuBar in a JFrame with some JMenu�s containing JMenuItems. I also have a JPanel that I draw inside (I Know that is probably not the wisest way to draw things, but it was the way I first learned to draw and now my program is too big and it is not worth while to change). Any ways, I draw some graphics inside of this JPanel.
The menu items change the drawings; this is done by repainting the JPanel Graphic. However, when I click one of the menu items, the JPanel paints but there is a residual of the JMenu in the background that will not disappear.
The menu is closed and if I open and then close the menu the residual goes away.
=> I would like to know how to prevent the residual from appearing?
The problem also occurs when I use the popup menus outside of the JmenuBar.
What I think is wrong.
I think my problem is with the repaint. I don�t think the JFrame is repainting. I think I am simply repainting all the components in the JFrame but not the JFrame itself and thus the residual is not cleared from the JFrame. I don�t know how to fix this but I believe that is the problem because when I minimize the JFrame then Maximize it the JFrame will not paint, and I can see right through the JFrame, but the components paint fine.
Sorry for the long question, but I don�t know what would be helpful.
Any advice would be appreciated,
Thank you
Seraj// This is the code that listens for the menu item
private void RBmmActionPerformed(java.awt.event.ActionEvent evt) {
calc.setIN(false);
updateData(); // updates some data
paint2(); // my special draw fuction shown below
public void paint2() // this the special paint that draws on the JPanel
Graphics page = jPanel1.getGraphics();
if(start_end)
myPic.draw(page);
else
page.setColor(Color.WHITE);
page.fillRect((int)(OFFSET.getX()), (int)(OFFSET.getY()), (int)(R_BOUND-OFFSET.getX()), (int)(L_BOUND-OFFSET.getY()));
repaint();
public void paint(Graphics g) // this is the regular paint methode
MessageHandler();
ATD_age.repaint();
StanderdCal.repaint();
ChildSRF.repaint();
MessageArea.repaint();
}I hope that is helpful -
How to replace multiple occurences of space in a string to a single space?
How to replace multiple occurences of space in a string to a single space?
Hi,
try this code.
data : string1(50) type c,
flag(1) type c,
dummy(50) type c,
i type i,
len type i.
string1 = 'HI READ THIS'.
len = strlen( string1 ).
do len times.
if string1+i(1) = ' '.
flag = 'X'.
else.
if flag = 'X'.
concatenate dummy string1+i(1) into dummy separated by space.
clear flag.
else.
concatenate dummy string1+i(1) into dummy.
endif.
endif.
i = i + 1.
enddo.
write : / string1.
write : / dummy. -
I am new to Java Programming.
I have a line of code that works and does what is supposed to.
faceData.getProfile("Lisa").removeFriend("Curtis");
If I assign the strings to variables such as-
String name = "Lisa";
String fName = "Curtis";
and then plug those into the same line of code, it does not work
faceData.getProfile(name).removeFriend(fName);
What could be causing the problem?
I even added some lines to print out what is stored in the variables to verify that they are what they should be, but for some reason the variables do not work while putting the strings in quotes does. Any ideas?I guarantee that something about your assertions are incorrect. Those variables are either not equal to the values you claim, or something else is going on. But it's not a problem with string variables versus string constants.
Edit: My best guess in lack of a real example from you, is that the strings in question have non-printable characters in them, such as trailing spaces or line feeds. -
Little problem with Strings.
I have an little problem with Strings, i make one comparision like this.
String nombre="Javier";
if( nombre.equalsIgnoreCase(output.getStringValue("CN_NOMBRESf",null)) )
Wich output.getStringValue("CN_NOMBRESf",null) is "Javier" too, because I display
this before and are equals.
What I do wrong?.
You are actually making your users key in things like
"\026"? Not very user-friendly, I would say. But
assuming that is the best way for you to get your
input, or if it's just you doing the input, the way to
change that 4-character string into the single
character that Java represents by '\026', you would
use a bit of code like this:char encoded =
(char)Integer.parseInt(substring(inputString, 1),
16);
DrClap has the right idea, except '\026' is octal, not hex. So change the radix from 16 to 8. Unicode is usually represented like '\u002A'. So it looks like you want:String s = "\\077";
System.out.println((char)Integer.parseInt(s.substring(1), 8));Now all you have to do is parse through the String and replace them, which I think shouldn't be too hard for you now :) -
Will multiple Lan cards cause problems using rmi?
Will multiple Lan cards cause problems using rmi? If a host has two or more network cards (only one of which is Internet-enabled), how does RMI know which IP address to use? There seems to be a problem when such a client registers with an RMI service, and has a client-side callback method invoked by the server.
You can tell RMI the address you want by defining java.rmi.server.hostname at the JVM which exports the remote object.
-
Paint problems in 1.4-RC1
Is anyone else experiencing repaint problems with RC1? I've seen two intermittent things so far:
1) When a modal JDialog is shown above its owner window, the contents of the owner window are being painted inside the JDialog
2) Scroll bars (JScrollPane) are not being repainted properly when window is resized. Phantom scroll buttons remain at the old position.
Any others out there?My JDK 1.4.0 Swing application does not paint very well on 2 out of 4 NT / SP5-6machines tested. Its OK on 2 machines and NOT OK on 2 others... The machines have mixture of different graphics cards.
The base problem reminds me of 'running out of paint handles' in Win 3.1 days... i.e. the GUI fails to refresh and gets cluttered with 'random' strips, streched painting, general 'junk' that won't clear. Its quite serious because when the application window is moved the edit-box / buttons etc don't necessarily move at same time and get partially 'off the window' and stop working. Minimize/Maximize and drag overs by other apps don't clear it. The problem seems to get worse the longer the application is executed and seems to be even worse when there's more than 1 window up a time... i.e. it almost seems like 'lack of horsepower' in CPU but these machines are PIII 400MHZ with OK RAM so there should be enough CPU.
Note that JDK 1.3 'corrects' the problem - i.e. running same code on JDK 1.3 (instead of JDK 1.4) works just fine and does NOT have the paint problems.
ANY HELP APPRECIATED!! -
Problem with String to Int conversion
Dear Friends,
Problem with String to Int conversion
I am having a column where most of the values are numeric. Only 4 values are non numeric.
I have replaces those non numeric values to numeric in order to maintain the data type.
CASE Grade.Grade WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade END
This comes the result as down
Grade
_0_
_1_
_10_
_11_
_12_
_13_
_14_
_15_
_16_
_17_
_18_
_19_
_2_
_20_
_21_
_22_
_23_
_24_
_3_
_4_
_5_
_6_
_7_
_8_
_9_
Refresh
Now I want to convert this value to numeric and do some calculation
So I changed the formula as below
cast (CASE Grade.Grade WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade END as INT)
Now I get the following error
View Display Error
_ Odbc driver returned an error (SQLExecDirectW)._
Error Details
Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
_State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 17001] Oracle Error code: 1722, message: ORA-01722: invalid number at OCI call OCIStmtFetch. [nQSError: 17012] Bulk fetch failed. (HY000)_
SQL Issued: SELECT cast ( CASE Grade.Grade WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' ELSE Grade.Grade END as Int) saw0 FROM "Human Capital - Manpower Costing" WHERE LENGTH(CASE Grade.Grade WHEN 'E1' THEN '20' WHEN 'E2' THEN '21' WHEN 'E3' THEN '22' WHEN 'E4' THEN '23' ELSE Grade.Grade END) > 0 ORDER BY saw_0_
Refresh
Could anybody help me
Regards
Mustafa
Edited by: Musnet on Jun 29, 2010 5:42 AM
Edited by: Musnet on Jun 29, 2010 6:48 AMDear Kart,
This give me another hint, Yes you are right. There was one row which returns neither blank nor any value.
I have done the code like following and it works fine
Thanks again for your support
Regards
Code: cast (CASE (CASE WHEN Length(Grade.Grade)=0 THEN '--' ELSE Grade.Grade END) WHEN 'E4' THEN '24' WHEN 'E3' THEN '23' WHEN 'E2' THEN '22' WHEN 'E1' THEN '21' when '--' then '-1' ELSE Grade.Grade END as Int) -
Multiple Transparent Mode Devices
Hi all,
Just wondering if anyone out there has experience chaining together multiple transparent/bridged mode devices.
An example in this case would be:
Routed Device --> Packet Shaper (Bridged) --> ASA (Transparent) --> IPS (Transparent) --> Routed Device
All of these devices are different physical boxes and have no communication to/from one another. My concern is mostly to do with failover scenarios and ensuring that failover over 3 "bump in the wire" devices goes smoothly.
Has anyone implemented anything like this, am I worrying for nothing?
Thanks for your time.Is there any document to support this? I would be getting my hands on a ASA pretty soon hope to test this feature out.
-Hoogen
Maybe you are looking for
-
Golden triangle authentication problem
Hi, Im trying to set up the golden triangle on our AD/Mac network. I have bound to AD fine and now Im trying to set up an OD Master. After clicking "Kerberize Services" I click on "Remain connected and set up an Open Directory Master". Upon doing thi
-
When printing from v10.1.3 or v9 from OSX Lion get Adobe Reader quit unexpectedly
When printing from v10.1.3 or v9 from OSX Lion get Adobe Reader quit unexpectedly Click on the print button get the Print screen Click Print then get the error Am able to print fine from other applications Have tried uninstalling and restalling Adobe
-
How to get connected to OIPM from Oracle WebCenter Document Capture
Hi, How we get connected from Oracle WebCenter Document Capture(ODC) to Oracle WebCenter Cintent:Imaging (OIPM). OIPM is 11g and ODC is 10g. Pls suggest any doc or link. Thanks and Warm Regards, RR.
-
Hi I have a problem when using the ant deploy command in the hello1 app in the tutorial. I get an error: BUILD FAILED E:\dev\javaeetutorial5\examples\bp-project\app-server-ant.xml:417: Property javaee.server.passwordfile not specified. Please specify
-
How do I install photoshop 4 into my computer?
how do I install a copy of photoshop cs4 that has been elevated to photshop5