Color of a JDialog

I want to set the background color of a JDialog. I used the follwing code but it doesn't work:
Object[] options = {"Oui","Non"};
          JOptionPane optionViderChamps = new JOptionPane(
               "�tes-vous certain de vouloir vider les champs ?",
               JOptionPane.QUESTION_MESSAGE,JOptionPane.YES_NO_OPTION,
               null,options,options[0]);
          optionViderChamps.setBackground(Color.white);
          JDialog dialogViderChamps = optionViderChamps.createDialog
               (framePrincipal, "VIDER LES CHAMPS");
          dialogViderChamps.getContentPane().setBackground(Color.white);
          dialogViderChamps.show();

Hi,
remove that getContentPane() and call setBackGround(Color.white) directly on the JDialog object.
It should work.
durga

Similar Messages

  • JDialog - change border color?

    Hi!
    Im trying to change the border color of a jdialog box. There is no setBorder method as there is for other components... also if I use getContentPane() - there is still no setBorder function that I can access.
    I figure that I can make a custom border object and use it in the program - but perhaps this is the wrong way to accomplish this...
    any ideas?

    also if I use getContentPane() - there is still no setBorder function that I can accessThe default content pane for a JDialog or JFrame is a JPanel. So you need to cast the content pane to a JPanel first before using the setBorder() method.
    You would also need to make the dialog undecorated (or is it decorated, I can never remember) to get rid of the default border.

  • JDialog + Image + Label

    Dear all,
    i try to insert an animated gif into a JDialog that already contains a label. But,when the applications is running, the Dialog shows only the gif and the background color of the JDialog is grey and not the color that i chosen. Why?
    Here is a code:
    public class WaitDialog extends JDialog {
    JPanel panel1 = new JPanel();
    JLabel textLabel = new JLabel();
    XYLayout xYLayout1 = new XYLayout();
    Frame frame;
    Vector waitDialog_language;
    JPanel panelImage = new JPanel();
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Image imageContainer;
    XYLayout xYLayout2 = new XYLayout();
    public WaitDialog(Frame frame, String title, boolean modal, Vector waitDialog_language) {
    super(frame, title, modal);
    this.frame = frame;
    this.waitDialog_language = waitDialog_language;
    try {
    jbInit();
    //pack();
    catch(Exception ex) {
    ex.printStackTrace();
    void jbInit() throws Exception {
    panel1.setLayout(xYLayout1);
    panel1.setBackground(new Color(255, 118, 79));
    textLabel.setBackground(new Color(255, 118, 79));
    textLabel.setFont(new java.awt.Font("Dialog", 1, 30));
    textLabel.setHorizontalTextPosition(SwingConstants.LEFT);
    textLabel.setText("Please wait....");
    this.getContentPane().setBackground(new Color(255, 118, 79));
    this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    this.setModal(true);
    this.setResizable(false);
    xYLayout1.setWidth(400);
    xYLayout1.setHeight(150);
    panelImage.setLayout(xYLayout2);
    panelImage.setBackground(new Color(255, 118, 79));
    panelImage.setMinimumSize(new Dimension(160, 120));
    panelImage.setPreferredSize(new Dimension(160, 120));
    getContentPane().add(panel1);
    panel1.add(panelImage, new XYConstraints(5, 28, 123, 95));
    panel1.add(textLabel, new XYConstraints(143, 56, 282, -1));
    this.setSize(new Dimension(443, 150));
    int x = (frame.getSize().width - this.getSize().width) / 2;
    int y = (frame.getSize().height - this.getSize().height) / 2;
    this.setLocation(x + frame.getLocationOnScreen().x, y + frame.getLocationOnScreen().y);
    //gif animated
    imageContainer = toolkit.getImage("images/wheel.gif");
    validate();
    pack();
    public void paint(Graphics g) {
    Graphics g2 = panelImage.getGraphics();
    g2.drawImage(imageContainer, 0, 0, this);
    public void update(Graphics g) {
    paint(g);
    Thanks in advance.
    Angelo

    label.setOpaque( true );
    Check out the Swing tutorial on "Painting" for more information on why setOpaque(...) method is important:
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html

  • Help converting my class to Paint

    A while back I wrote this class, ColorGradient (see below)
    Before you start telling me about GradientPaint, this class is pretty different from GradientPaint - it handles multiple colors, and it doesn't cycle (last color goes on forever)
    The way I built it at the time was to extend BufferedImage and draw on that. I got critique at the time suggesting that I should detach it from being a BufferedImage; I agree, it would be great if I could turn this class into a Paint, where here is no Image, just basically the algorithm for creating a multicolor color gradient.
    From what I know, it seems like creating my own implementation of Paint could be the way to go. Looking into this, it isn't Paint that confuses me so much as how to create a SampleModel and a Raster. I just took a stab at creating a SampleModel - it seems like I've got to give it a width and a height, which I already didn't want to do.
    Anyone have any experience with this, or advice about the best way to decouple the painting algorithm from a BufferedImage?
    * Created on Jun 14, 2006 by @author Tom Jacobs
    package tjacobs.ui.ex;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.Polygon;
    import java.awt.Rectangle;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import javax.swing.JComponent;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import tjacobs.MathUtils;
    import tjacobs.print.StandardPrint;
    import tjacobs.ui.drag.Draggable;
    import tjacobs.ui.shape.PolygonFactory;
    import tjacobs.ui.util.WindowUtilities;
    public class ColorGradient extends BufferedImage {
         private Color[] mColors;
         private double mSpan;
         private Point mCenter;
         private int mOrientation;
         private boolean mAutoRender = false;
         private boolean mOptimized;
         private int[] mDrawColors;
         public static final int BOTH_EUCLID = 0;
         public static final int HORIZONTAL = 1;
         public static final int VERTICAL = 2;
         public static final int BOTH_MANHATTAN = 3;
         public ColorGradient(int width, int height) {
              super(width, height, BufferedImage.TYPE_INT_RGB);
              setSpan(MathUtils.distance(width, height) / 7);
              setCenter(0,0);
              setOrientation(BOTH_EUCLID);
              setColors(getROYGBIV());
              render();
              mAutoRender = true;
         public void setAutoRender(boolean b) {
              mAutoRender = b;
         public boolean getAutoRender() {
              return mAutoRender;
         public ColorGradient(int width, int height, boolean autoRender) {
              this(width, height);
              mAutoRender = autoRender;
          * sets the span of the color gradient
         public void setSpan(double d) {
              mSpan = d;
              if (mAutoRender) {
                   render();
         public double getSpan() {
              return mSpan;
          * sets the center of the color gradient. Default is 0,0
         public void setCenter(int x, int y) {
              if (mCenter == null) {
                   mCenter = new Point(x,y);
              else {
                   mCenter.x = x; mCenter.y = y;
              if (mAutoRender) render();
         public Point getCenter() {
              return mCenter;
          * sets the colors to use in the color gradient. Default is ROYGBIV
         public void setColors(Color[] colors) {
              mColors = colors;
              if (mAutoRender) render();
         public Color[] getColors() {
              return mColors;
         public int getOrientation() {
              return mOrientation;
          * sets the orientation of the gradient in case you want a gradient
          * just in one direction. default is both directions
         public void setOrientation(int orientation) {
              mOrientation = orientation;
              if (mAutoRender) render();
         protected double getScore(int CenterX, int CenterY, int x2, int y2) {
              double distance = 0;
              if (mOrientation == BOTH_EUCLID) {
                    distance = MathUtils.distance(CenterX, CenterY, x2, y2);
              else if (mOrientation == BOTH_MANHATTAN) {
                   distance = (Math.abs(CenterX - x2) + Math.abs(CenterY - y2)) / 2;
              else if (mOrientation == HORIZONTAL) {
                   distance = Math.abs(CenterX - x2);
              else {
                   distance = Math.abs(CenterY - y2);
              return distance;
         public void renderMoveCenter(int x1, int y1, int x2, int y2) {
              if (mColors == null) {
                   return;
              int width = getWidth();
              int height = getHeight();
              int x = mCenter.x;
              int y = mCenter.y;
              float parts1[] = new float[3], parts2[] = new float[3], partsEnd[] = new float[3];
              int xDiff = x2 - x1;
              int yDiff = y2 - y1;
              int absXDiff = xDiff, absYDiff = yDiff;
              if (absXDiff < 0) absXDiff = -absXDiff;
              if (absYDiff < 0) absYDiff = -absYDiff;
              if (xDiff >= 0) {
                   for (int i = width - 1; i < width - absXDiff ; i--) {
                        if (yDiff >= 0) {
                             for (int j = height - 1; j < height -absYDiff; j--) {
              else {
                   for (int i = 0; i < width - absXDiff ; i++) {
              for (int i = 0; i < width - absXDiff ; i++) {
                   for (int j = 0; j < height - absYDiff; j++) {
                        double distance;
                        double seg;
                        int low;
                        int high;
                        distance = getScore(x, y, i, j);
                        seg = distance / mSpan;
                        low = (int) seg;
                        high = low + 1;
                        if (low >= mColors.length) {
                             low = mColors.length - 1;
                             high = low;
                        if (high >= mColors.length) {
                             high = mColors.length - 1;
                        float lowPart = (float) seg - low ;
                        mColors[low].getColorComponents(parts1);
                        mColors[high].getColorComponents(parts2);
                        float hipart = (1 - lowPart);
                        for (int k = 0; k < 3; k++) {
                             partsEnd[k] = parts2[k] * lowPart + parts1[k] * hipart;
                        int rgb = (((int) (partsEnd[0]*255+0.5)) & 0xff) << 16 |
                        (((int) (partsEnd[1]*255+0.5)) & 0xff) << 8 |
                        (((int) (partsEnd[2]*255+0.5)) & 0xff);
                        super.setRGB(i, j, rgb);
         public void render() {
              if (mColors == null) {
                   return;
              int width = getWidth();
              int height = getHeight();
              int x = mCenter.x;
              int y = mCenter.y;
              if (!mOptimized) {
                   float parts1[] = new float[3], parts2[] = new float[3], partsEnd[] = new float[3];
                   for (int i = 0; i < width; i++) {
                        for (int j = 0; j < height; j++) {
                             double distance = getScore(x, y, i, j);
                             double seg = distance / mSpan;
                             int low = (int) seg;
                             int high = low + 1;
                             if (low >= mColors.length) {
                                  low = mColors.length - 1;
                                  high = low;
                             if (high >= mColors.length) {
                                  high = mColors.length - 1;
                             float lowPart = (float) seg - low ;
                             mColors[low].getColorComponents(parts1);
                             mColors[high].getColorComponents(parts2);
                             float hipart = (1 - lowPart);
                             for (int k = 0; k < 3; k++) {
                                  partsEnd[k] = parts2[k] * lowPart + parts1[k] * hipart;
                             int rgb = (((int) (partsEnd[0]*255+0.5)) & 0xff) << 16 |
                             (((int) (partsEnd[1]*255+0.5)) & 0xff) << 8 |
                             (((int) (partsEnd[2]*255+0.5)) & 0xff);
                             super.setRGB(i, j, rgb);
              } else {
                   for (int i = 0; i < width; i++) {
                        for (int j = 0; j < height; j++) {
                             int distance = (int)Math.round(getScore(x, y, i, j));
                             if (distance >= mDrawColors.length) {
                                  distance = mDrawColors.length - 1;
                             setRGB(i, j, mDrawColors[distance]);
         public static Color[] getROYGBIV() {
              return new Color[] {Color.RED, Color.ORANGE, Color.YELLOW,
                                       Color.GREEN, Color.BLUE,
                                       new Color(75, 0, 130), Color.MAGENTA};
         public static class GradientPane extends JComponent {
              private static final long serialVersionUID = 0;
              private ColorGradient mGradient;
              private JPopupMenu mPopup;
              private MouseListener mPopupListener;
              public class ReportColorMenuItem extends ColorMenuItem {
                   private static final long serialVersionUID = 0;
                   public ReportColorMenuItem(Color c) {
                        super(c);
                   public ReportColorMenuItem(Color c, boolean addListener) {
                        super(c, addListener);
                   public void setColor(Color c) {
                        super.setColor(c);
                        updateColorsFromPopup();
              public GradientPane(int width, int height) {
                   setSize(width, height);
                   setPreferredSize(new Dimension(width, height));
                   mGradient = new ColorGradient(width, height);
                   mGradient.render();
              public ColorGradient getGradient() {
                   return mGradient;
              private void updateColorsFromPopup() {
                   Color[] colors = new Color[mPopup.getComponentCount() - 2];
                   for (int i = 0; i < colors.length; i++) {
                        colors[i] = ((ColorMenuItem)mPopup.getComponent(i)).getColor();
                   getGradient().setColors(colors);
                   if (!getGradient().getAutoRender()) {
                        getGradient().render();
                   repaint();
              public void useColorSelectorPopup(boolean b) {
                   if (b && mPopup == null) {
                        mPopup = new JPopupMenu();
                        ColorGradient grad = getGradient();
                        Color[] colors = grad.getColors();
                        for (int i = 0; i < colors.length; i++) {
                             mPopup.add(new ReportColorMenuItem(colors));
                        final JMenu remove = new JMenu("Remove");
                        ActionListener al = new ActionListener() {
                             public void actionPerformed(ActionEvent ae) {
                                  //int num = Integer.parseInt(ae.getActionCommand());
                                  int num = -1;
                                  Object src = ae.getSource();
                                  for (int i = 0; i < remove.getMenuComponentCount(); i++) {
                                       if (remove.getMenuComponent(i) == src) {
                                            num = i;
                                            break;
                                  if (num == -1) {
                                       System.out.println("Trouble");
                                  getGradient().removeColor(num);
                                  repaint();
                                  mPopup.remove(num);
                                  remove.remove(num);
                        for (int i = 0; i < colors.length; i++) {
                             JMenuItem item = new ColorMenuItem(colors[i], false);
                             item.setActionCommand(String.valueOf(i));
                             item.addActionListener(al);
                             remove.add(item);
                        JMenuItem add = new JMenuItem("Add");
                        add.addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent ae) {
                                  JMenuItem src = (JMenuItem) ae.getSource();
                                  mPopup.remove(src);
                                  mPopup.remove(remove);
                                  Color toAdd = Color.WHITE;
                                  mPopup.add(new ReportColorMenuItem(toAdd));
                                  ColorGradient cg = getGradient();
                                  cg.addColor(toAdd);
                                  if (!cg.getAutoRender()) {
                                       cg.render();
                                  mPopup.add(src);
                                  mPopup.add(remove);
                                  remove.add(new ReportColorMenuItem(toAdd, false));
                                  repaint();
                        mPopup.add(add);
                        mPopup.add(remove);
                        mPopupListener = WindowUtilities.addAsPopup(mPopup, this);
                   else if (!b && mPopup != null) {
                        mPopup = null;
                        removeMouseListener(mPopupListener);
                        mPopupListener = null;
              public void paintComponent(Graphics g) {
                   g.drawImage(mGradient, 0, 0, null);
         public void addColor(Color c) {
              Color[] nc = new Color[mColors.length + 1];
              for (int i = 0; i < mColors.length; i++) {
                   nc[i] = mColors[i];
              nc[nc.length - 1] = c;
              mColors = nc;
              render();
         public void removeColor(int colorNum) {
              Color[] nc = new Color[mColors.length -1];
              for (int i = 0; i < mColors.length - 1; i++) {
                   nc[i] = mColors[i < colorNum ? i : i + 1];
              mColors = nc;
              render();
         public void setOptimized(boolean b) {
              mOptimized = b;
              if (b) {
                   int maxDistance = (int) MathUtils.distance(getWidth(), getHeight()) + 1;
                   mDrawColors = new int[maxDistance];
                   float[] parts1 = new float[3], parts2 = new float[3], partsEnd = new float[3];
                   for (int distance = 0; distance < maxDistance; distance++) {
                        double seg = distance / mSpan;
                        int low = (int) seg;
                        int high = low + 1;
                        if (low >= mColors.length) {
                             low = mColors.length - 1;
                             high = low;
                        if (high >= mColors.length) {
                             high = mColors.length - 1;
                        float lowPart = (float) seg - low ;
                        mColors[low].getColorComponents(parts1);
                        mColors[high].getColorComponents(parts2);
                        float hipart = (1 - lowPart);
                        for (int k = 0; k < 3; k++) {
                             partsEnd[k] = parts2[k] * lowPart + parts1[k] * hipart;
                        int rgb = (((int) (partsEnd[0]*255+0.5)) & 0xff) << 16 |
              (((int) (partsEnd[1]*255+0.5)) & 0xff) << 8 |
              (((int) (partsEnd[2]*255+0.5)) & 0xff);
                        mDrawColors[distance] = rgb;
                        //super.setRGB(i, j, rgb);               
              else {
                   mDrawColors = null;
         public static void main(String args[]) {
              final GradientPane gp = new GradientPane(800, 800);
              gp.getGradient().setOptimized(true);
              CreatePopupWindow cpw = new CreatePopupWindow() {
                   public Window createPopupWindow(Point p) {
                        //ParamDialog pd = new ParamDialog((JFrame)SwingUtilities.windowForComponent(gp), new String[] {"Center", "Colors", "Orientation", "Span"});
                        //JDialog pd = new JDialog((JFrame)SwingUtilities.windowForComponent(gp));
                        //pd.setDefaultCloseOperation(pd.DISPOSE_ON_CLOSE);
                        JWindow pd = new JWindow();
                        pd.add(new JLabel("Hello"));
                        //PopupFactory fac = PopupFactory.getSharedInstance();
                        //Popup pd = fac.getPopup(gp, new JLabel("Hello"), p.x, p.y);
                        return pd;
              gp.useColorSelectorPopup(true);
              //gp.setPreferredSize(new Dimension(200, 200));
              //gp.getGradient().setCenter(100,100);
              final JPanel handle = new JPanel();
              handle.setSize(5,5);
              handle.setLocation(10,10);
              handle.setBackground(Color.PINK);
              handle.addComponentListener(new ComponentAdapter() {
                   public void componentMoved(ComponentEvent ev) {
                        gp.getGradient().setCenter(handle.getX(), handle.getY());
                        gp.repaint();
              gp.setLayout(null);
              new Draggable(handle);
              gp.add(handle);
              Dimension d = new Dimension(800,800);
              gp.setPreferredSize(d);
              gp.setSize(d);
              WindowUtilities.visualize(gp);
              GradientPane gp2 = new GradientPane(200,200);
              gp2.getGradient().setOrientation(HORIZONTAL);
              WindowUtilities.visualize(gp2);
              GradientPane gp3 = new GradientPane(200,200);
              gp3.getGradient().setOrientation(VERTICAL);
              GradientPane gp4 = new GradientPane(200,200);
              gp4.getGradient().setOrientation(BOTH_MANHATTAN);
              Window w3 = WindowUtilities.visualize(gp3);
              WindowUtilities.visualize(gp4);
              final Polygon gon = PolygonFactory.createPolygon(6, 0, new Rectangle(0,0,200,200));
              GradientPane gp5 = new GradientPane(200,200) {
                   public void paintComponent(Graphics g) {
                        g.setClip(gon);
                        super.paintComponent(g);
              WindowUtilities.visualize(gp5);
              //StandardPrint sp1 = new StandardPrint(gp);
              //StandardPrint sp2 = new StandardPrint(w3);
              //WindowUtilities.visualize(StandardPrint.preview(200, 200, sp1, sp1.getPageFormat(0), 0));
              //WindowUtilities.visualize(StandardPrint.preview(200, 200, sp2, sp2.getPageFormat(0), 0));          
              WindowUtilities.setWindowCloseOnEscape(true);

    Okay I have solved this, kind of.
    I changed ColorGradient so that rather than extending BufferedImage it has a BufferedImage member (mIm)
    then I added the following to get a Paint object from it. Hopefully this will prove a useful example to someone in the future :)
         public Paint getMyPaint() {
              return new MyPaint();
         public class MyPaint extends TexturePaint {
              TexturePaint mTP;
              public MyPaint() {
                   super(ColorGradient.this.getImage(), new Rectangle(0, 0, mIm.getWidth(null), mIm.getHeight(null)));
                   mTP = this;
              public PaintContext createContext(ColorModel cm,Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {
                   //System.out.println("Create context: db: " + deviceBounds + " ub: " + userBounds);
                   //picking userBounds arbitrarily
                   if (userBounds.getWidth() > mIm.getWidth() || userBounds.getHeight() > mIm.getHeight()) {
                        mIm = new BufferedImage((int)Math.max(mIm.getWidth(), userBounds.getWidth()), (int) Math.max(mIm.getHeight(), userBounds.getHeight()), BufferedImage.TYPE_INT_RGB);
                        mTP = new TexturePaint(ColorGradient.this.getImage(), new Rectangle(0, 0, mIm.getWidth(null), mIm.getHeight(null)));
                   setCenter((int) userBounds.getWidth() / 2, (int) userBounds.getHeight() / 2);
                   render();
                   if (mTP == this) return super.createContext(cm, deviceBounds, userBounds, xform, hints);
                   return mTP.createContext(cm, deviceBounds, userBounds, xform, hints);
         }

  • Problem in Setting Background Color for JButton

    Hi,
    I am using Background color for JButton (color is selected from the customized JColorChooser created by us) where it contains the option of transparency. If we choose light color, then the background is set to JButton, but when we mouse-over the JButton, other components inside the container (JPanel) is getting displayed inside the button.
    Can anyone help to sort out this problem.
    Thanks in advance.

    Hi,
    Here is the code.
    DialogWrapper is JDialog and ColorEditorPane is JPanel.
    DialogWrapper     dlg         = new DialogWrapper();
    ColorEditorPane colorPanel = new ColorEditorPane();
    colorPanel.setValue( _data.getTransparentColor());
    dlg.showWrappedDialog( colorPanel, "color_help", "color_dialog" );
    if( dlg.isOK())
    Color chosenColor = (Color) colorPanel.getValue().getContent();
    _data.setTransparentColor( chosenColor );
    _transparentColorDisplay.setBackground( chosenColor );
    _transparentColorDisplay.setOpaque( true );
    this.repaint();
    this.doLayout();
    this.validate();
    }I've several components like JCheckBox, JRadioButton, JTextField in "this".

  • Problems with 'background' JFrame focus when adding a modal JDialog

    Hi all,
    I'm trying to add a modal JDialog to my JFrame (to be used for data entry), although I'm having issues with the JFrame 'focus'. Basically, at the moment my program launches the JFrame and JDialog (on program load) fine. But then - if I switch to another program (say, my browser) and then I try switching back to my program, it only shows the JDialog and the main JFrame is nowhere to be seen.
    In many ways the functionality I'm looking for is that of Notepad: when you open the Find/Replace box (albeit it isn't modal), you can switch to another program, and then when you switch back to Notepad both the main frame and 'JDialog'-esque box is still showing.
    I've been trying to get this to work for a couple of hours but can't seem to. The closest I have got is to add a WindowFocusListener to my JDialog and I hide it via setVisible(false) once windowLostFocus() is fired (then my plan was to implement a similar functionality in my JFrame class - albeit with windowGainedFocus - to show the JDialog again, i.e. once the user switches back to the program). Unfortunately this doesn't seem to work; I can't seem to get any window or window focus listeners to actually fire any methods, in fact?
    I hope that kind of makes sense lol. In short I'm looking for Notepad CTRL+R esque functionality, albeit with a modal box. As for a 'short' code listing:
    Main.java
    // Not all of these required for the code excerpt of course.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GraphicsEnvironment;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import java.awt.event.WindowListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.basic.BasicSplitPaneDivider;
    import javax.swing.plaf.basic.BasicSplitPaneUI;
    public class Main extends JFrame implements ActionListener, WindowFocusListener, WindowListener, FocusListener {
         static JFrame frame;
         private static int programWidth;
         private static int programHeight;
         private static int minimumProgramWidth = 700;
         private static int minimumProgramHeight = 550;
         public static SetupProject setupProjectDialog;
         public Main() {
              // Setup the overall GUI of the program
         private static void createSetupProjectDialog() {
              // Now open the 'Setup Your Project' dialog box
              // !!! Naturally this wouldn't auto-open on load if the user has already created a project
              setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );
              // Okay, for this we want it to be (say) 70% of the progamWidth/height, OR *slightly* (-25px) smaller than the minimum size of 700/550
              // Change (base on programWidth/Height) then setLocation
              int currProgramWidth = getProgramWidth();
              int currProgramHeight = getProgramHeight();
              int possibleWidth = (int) (currProgramWidth * 0.7);
              int possibleHeight = (int) (currProgramHeight * 0.7);
              // Set the size and location of the JDialog as needed
              if( (possibleWidth > (minimumProgramWidth-25)) && (possibleHeight > (minimumProgramHeight-25)) ) {
                   setupProjectDialog.setPreferredSize( new Dimension(possibleWidth,possibleHeight) );
                   setupProjectDialog.setLocation( ((currProgramWidth/2)-(possibleWidth/2)), ((currProgramHeight/2)-(possibleHeight/2)) );
               else {
                   setupProjectDialog.setPreferredSize( new Dimension( (minimumProgramWidth-25), (minimumProgramHeight-25)) );
                   setupProjectDialog.setLocation( ((currProgramWidth/2)-((minimumProgramWidth-25)/2)), ((currProgramHeight/2)-((minimumProgramHeight-25)/2)) );
              setupProjectDialog.setResizable(false);
              setupProjectDialog.toFront();
              setupProjectDialog.pack();
              setupProjectDialog.setVisible(true);
         public static void main ( String[] args ) {
              Main frame = new Main();
              frame.pack();
              frame.setVisible(true);
              createSetupProjectDialog();
            // None of these get fired when the Jframe is switched to. I also tried a ComponentListener, but had no joy there either.
         public void windowGainedFocus(WindowEvent e) {
              System.out.println("Gained");
              setupProjectDialog.setVisible(true);
         public void windowLostFocus(WindowEvent e) {
              System.out.println("GainedLost");
         public void windowOpened(WindowEvent e) {
              System.out.println("YAY1!");
         public void windowClosing(WindowEvent e) {
              System.out.println("YAY2!");
         public void windowClosed(WindowEvent e) {
              System.out.println("YAY3!");
         public void windowIconified(WindowEvent e) {
              System.out.println("YAY4!");
         public void windowDeiconified(WindowEvent e) {
              System.out.println("YAY5!");
         public void windowActivated(WindowEvent e) {
              System.out.println("YAY6!");
         public void windowDeactivated(WindowEvent e) {
              System.out.println("YAY7!");
         public void focusGained(FocusEvent e) {
              System.out.println("YAY8!");
         public void focusLost(FocusEvent e) {
              System.out.println("YAY9!");
    SetupProject.java
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import java.awt.event.WindowListener;
    import java.io.IOException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class SetupProject extends JDialog implements ActionListener {
         public SetupProject( final JFrame frame, String title, boolean modal ) {
              // Setup the JDialog
              super( frame, title, modal );
              setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
              // Bad code. Is only temporary
              add( new JLabel("This is a test.") );
              // !!! TESTING
              addWindowFocusListener( new WindowFocusListener() {
                   public void windowGainedFocus(WindowEvent e) {
                        // Naturally this now doesn't get called after the setVisible(false) call below
                   public void windowLostFocus(WindowEvent e) {
                        System.out.println("Lost");
                        setVisible(false); // Doing this sort of thing since frame.someMethod() always fires a null pointer exception?!
    }Any help would be very much greatly appreciated.
    Thanks!
    Tristan

    Hi,
    Many thanks for the reply. Isn't that what I'm doing with the super() call though?
    As in, in Main.java I'm doing:
    setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );Then the constructor in SetupProject is:
    public SetupProject( final JFrame frame, String title, boolean modal ) {
              // Setup the JDialog
              super( frame, title, modal );
              And isn't the super call (since the class extends JDialog) essentially like doing new JDialog(frame,title,modal)?
    If not, that would make sense due to the null pointer exception errors I've been getting. Although I did think I'd done it right hence am confused as to the right way to handle this,if so.
    Thanks,
    Tristan
    Edited by: 802573 on 20-Oct-2010 08:27

  • Setting color of a specific line?

    okay so in swing is it possible to set a portion of the text in a text field to a different color? Like in my chat program(below) can I make it so all incoming chat(instring) is blue and all outgoing text(string) is red?
    Am I using the wrong text component for changing the color of a line? Should I even be using J text components for this?
    The tutorial often puts tons of different text components in to its examples, and uses odd methods to change the color.
    It seems that I have to use something like setCaretColor, but i am not clear on how to use this in the way I want to use it.
    here is the code:
    import java.io.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.JOptionPane;
    import javax.swing.JDialog;
    import javax.swing.JTextField;
    import java.beans.*; //property change stuff
    import java.awt.*;
    import java.awt.event.*;
    public class server extends JFrame implements ActionListener
         JButton recieve;
         String string;
            String instring;
         String aft = " ";
         String bef = " ";
         String allchat=" ";
         JTextField towrite;
         boolean stop = false;
         String name;
         JTextArea chatbox;
         public server(){
                             setSize(490,550);
                             getContentPane().setLayout(null);
                             recieve = new JButton("send message");
                             recieve.setBounds(30,150,150,35);
                             getContentPane().add(recieve);
                                       recieve.addActionListener(this);
                             chatbox = new JTextArea("chat goes here");
                             chatbox.setEditable(false);
                             chatbox.setBounds(10,200,460,270);
                             getContentPane().add(chatbox);
                                            towrite = new JTextField("Write message here");
                             towrite.setBounds(10,475,460,35);
                             getContentPane().add(towrite);
                                            towrite.addActionListener(this);
                             setVisible(true);
                   name = (String)JOptionPane.showInputDialog(null,"Enter your name");
              while(stop==false){
                   try
                   ServerSocket socket = new ServerSocket(4019);
                   Socket insocket =socket.accept();
                   BufferedReader in = new BufferedReader (new InputStreamReader(insocket.getInputStream()));
                   instring = in.readLine();
                   socket.close();
                   bef = instring;
                   if(bef.equals(aft)){}else{
                        allchat=instring+"\n"+allchat;
                        chatbox.setText(allchat);
    catch(Exception e){}
             public void actionPerformed(ActionEvent evt)
            if(evt.getActionCommand().equals("send message"))
    try
    Socket socket = new Socket("67.166.126.246",4020);
    OutputStream out = socket.getOutputStream();
    string=name+": "+towrite.getText();
    byte buffer[] = string.getBytes();
    out.write(buffer);
    socket.close();
    catch(Exception e){}
                   bef = string;
                   if(bef.equals(aft)){}else{
                        allchat=string+"\n"+allchat;
                        chatbox.setText(allchat);
                   aft=bef;
    public static void main(String[] args)
    server s = new server();}}

    Hmmmm im sorry but Im not quite sure I understand how to do this.
    Do you have to know the exact digits at which the text starts and ends?
    or can you, as mentioned just use html tags to set the text color?
    If i were to highlight a line of the text, would that text be highlighted even if its location in the string changed?
    It would seem that tags would be easier but from what I have tried they don't seem to work in editor panes, but the ydo work in buttons
    Im sorry, Im being a bit of a pest, but I have not been doing java for that long, and I do not have a teacher, so all of my questions have to go here.

  • Jdialog doesn't show the label text

    Hi can any one plese tell me whats wrong with my code,
    public JDialog createDialog(){
    jl.setText("testing");
    jl.setFont(new Font("Luxi Sans", Font.BOLD, 12));
    jl.setForeground(Color.BLACK);
    jl.setBackground(Color.WHITE);
    JOptionPane pane= new JOptionPane(jl,JOptionPane.INFORMATION_MESSAGE,JOptionPane.YES_NO_CANCEL_OPTION,null,new Object[] {new JButton()});
    dia = pane.createDialog(parentComponent, title);
    dia.getContentPane().setLayout(new BorderLayout(5, 5));
    dia.setSize(300,100);
    return dia;
    i am callin this method from the thread, it does show the JDialog window but empty, show nothing, if some can help plz....thanks in advance.
    public void run(){
    while(true){ 
    dia=createDialog(this,"Scannin F....plz wait");
    dia.setVisible(true);
    try{Thread.sleep(10000);}catch(Exception e){System.out.println("Error in " +
                                          "OutputPage Msg Thread "+e);} break;}
    }

    sorry, i should have explaind it, i want my msg box to be closed by my thread like when the background process is finished...i don't want to display any button either on my msg box just a msg like 'plz wait' and yes u r right i want to bock user to click on anyother option....i have no choice but to use Dialog, because i need an object of my msg box so i can use it to close the window after my process....i did notice that after my Threads finished thier process the Dialog box JLabel does show me the msg string but not during the process...
    mm=new MyMessage();
    thy=new Thread(mm);
    thy.start();
    dosomebackgroundwork();
    Thread.sleep(1000);
    mm.closemsgbox();
    ================================
    class MyMessage extends JOptionPane implements Runnable
    public void run(){
    dia=createDialog(this,"Scannin Flags..plz wait");
    dia.setVisible(true);
    try{Thread.sleep(10000);}catch(Exception e){System.out.println("Error in " +
                  "OutputPage Msg Thread "+e);}
    public JDialog createDialog(Component parentComponent, String title) throws HeadlessException {
    jl.setText(title);
    jl.setFont(new Font("Luxi Sans", Font.BOLD, 12));
    jl.setForeground(Color.BLACK);
    jl.setBackground(Color.WHITE);
    JOptionPane pane= new JOptionPane(jl,JOptionPane.INFORMATION_MESSAGE,JOptionPane.YES_NO_CANCEL_OPTION,null,new Object[] {});
    dia = pane.createDialog(parentComponent, title);
    dia.setSize(300,100);
    return dia;
    }

  • Value from JDialog to another class

    Hi:
    I have a trouble with getting my values from a JDialog box to another class.
    Here's what I have:
    This is an ftp application. I have a main frame where if the user selects File->New Connection
    it pops up a Connect dialog box. The connect dialog box has various fields such as profile name, host address, user name, and so on. In addition, there are three buttons, Add, Connect and Cancel.
    After the user types info and clicks Connect, all these information should be sent to the main frame from where it would send the information to another class which would connect to the ftp server.
    I have a class called Profile which is used to wrap these information to be sent to the main frame.
    Now, how can i get this info to the main frame? Here's the code in main frame:
    class MainFrame extends JFrame {
    JMenuItem newconnection = new JMenuItem("New Connection", 'N');
    newconnection.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    Profile p = new Profile();
    ConnectDialog con = new ConnectDialog();
    p = con.getProfile();
    makeNewConnection(p); //this is the method i use to make a new connection
    The problem is that by the time i get to the line p = con.getProfile(),
    con object no longer exists.
    Should i use threads or should i just send the main frame as the parameter to create the Connect dialog. If i use threads, how should i code it, and if i use main frame as the parent frame for connect dialog, how do i get the info to main frame. Please help. Here's the code for ConnectDialog. Also, please advice if ConnectDialog code can be improved since i am new to swing. Thanks for helping a needy student.
    public class ConnectDialog extends JDialog{
    private MainFrame parent;
    private String defaultDownloadPath;
    private static Profile currProfile;
    private JList profileList;
    private JPanel listPanel;
    private JPanel infoPanel;
    private JPanel labelPanel;
    private JPanel buttonPanel;
    private JPanel arrangedComponents;
    private Vector data;
    private JLabel ProfileName;
    private JLabel HostAddress;
    private JLabel Account;
    private JLabel PortNo;
    private JLabel login;
    private JLabel password;
    private JLabel DownLoadPath;
    private JButton addButton;
    private JButton cancelButton;
    private JButton connectButton;
    private JButton browseButton;
    private JButton clearButton;
    private JLabel Anonymous;
    private JCheckBox anonymous;
    private JTextField profileName;
    private JTextField hostAddress;
    private JTextField account;
    private JTextField portNo;
    private JTextField loginName;
    private JTextField passwd;
    private JTextField downloadPath;
    private final int textSize = 20;
    private final int fontSize = 12;
    private Container cp;
    public ConnectDialog(MainFrame main) {
    super(main, true);
    parent = main;
    data = new Vector();
    currProfile = new Profile();
    profileList = new JList(data);
    listPanel = new JPanel();
    labelPanel = new JPanel();
    infoPanel = new JPanel();
    buttonPanel = new JPanel();
    arrangedComponents = new JPanel();
    ProfileName = new JLabel("Profile Name:");
    ProfileName.setForeground(Color.black);
    HostAddress = new JLabel("Host Address:");
    HostAddress.setForeground(Color.black);
    Account = new JLabel("Account:");
    Account.setForeground(Color.black);
    PortNo = new JLabel("Port:");
    PortNo.setForeground(Color.black);
    login = new JLabel("Login:");
    login.setForeground(Color.black);
    password = new JLabel("Password:");
    password.setForeground(Color.black);
    DownLoadPath = new JLabel("Download Path:");
    DownLoadPath.setForeground(Color.black);
    addButton = new JButton("Add");
    addButton.setMnemonic('A');
    addButton.setForeground(Color.black);
    cancelButton = new JButton("Cancel");
    cancelButton.setForeground(Color.black);
    clearButton = new JButton("Clear");
    clearButton.setForeground(Color.black);
    connectButton = new JButton("Connect");
    connectButton.setForeground(Color.black);
    connectButton.setMnemonic('C');
    browseButton = new JButton("Browse");
    browseButton.setForeground(Color.black);
    browseButton.setMnemonic('B');
    Anonymous = new JLabel("Anonymous: ");
    Anonymous.setForeground(Color.black);
    anonymous = new JCheckBox();
    profileName = new JTextField(textSize);
    profileName.setText("");
    profileName.setBorder(BorderFactory.createLoweredBevelBorder());
    profileName.setBorder(BorderFactory.createLineBorder(Color.black));
    profileName.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    hostAddress = new JTextField(textSize);
    hostAddress.setText("");
    hostAddress.setBorder(BorderFactory.createEtchedBorder());
    hostAddress.setBorder(BorderFactory.createLineBorder(Color.black));
    hostAddress.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    account = new JTextField(textSize);
    account.setText("");
    account.setBorder(BorderFactory.createLoweredBevelBorder());
    account.setBorder(BorderFactory.createLineBorder(Color.black));
    account.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    portNo = new JTextField(5);
    portNo.setText("");
    portNo.setText("21");
    portNo.setBorder(BorderFactory.createEtchedBorder());
    portNo.setBorder(BorderFactory.createLineBorder(Color.black));
    portNo.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    loginName = new JTextField(textSize);
    loginName.setText("");
    loginName.setBorder(BorderFactory.createEtchedBorder());
    loginName.setBorder(BorderFactory.createLineBorder(Color.black));
    loginName.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    passwd = new JTextField(textSize);
    passwd.setText("");
    passwd.setBorder(BorderFactory.createEtchedBorder());
    passwd.setBorder(BorderFactory.createLineBorder(Color.black));
    passwd.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    downloadPath = new JTextField(textSize);
    downloadPath.setText("");
    downloadPath.setBorder(BorderFactory.createEtchedBorder());
    downloadPath.setBorder(BorderFactory.createLineBorder(Color.black));
    downloadPath.setFont(new Font("Dialog",Font.PLAIN,fontSize));
    cp = this.getContentPane();
    this.setBounds(200,200,600,300);
    this.setResizable(false);
    cp.setLayout(new BorderLayout());
    setListPanel();
    setLabelPanel();
    setButtonPanel();
    setActionListeners();
    this.setBackground(Color.lightGray);
    this.setVisible(true);
    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    public String getDefaultDownloadPath() {
    return defaultDownloadPath;
    // public Profile getProfile() {
    // try {
    // this.wait();
    // } catch (Exception e) {}
    // return currProfile;
    public void setListPanel() {
    profileList.setFont(new Font("Dialog", Font.PLAIN, 12));
    profileList.setBackground(Color.white);
    profileList.setForeground(Color.black);
    profileList.setPrototypeCellValue("MMMMMMMMM");
    listPanel.setPreferredSize(profileList.getPreferredScrollableViewportSize());
    listPanel.setBorder(BorderFactory.createEtchedBorder());
    listPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    listPanel.setBackground(Color.white);
    listPanel.add(profileList);
    cp.add(listPanel, "West");
    public void setLabelPanel() {
    arrangedComponents = new JPanel();
    arrangedComponents.setLayout(new BorderLayout());
    labelPanel = new JPanel();
    labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS));
    labelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
    JPanel row1 = new JPanel();
    row1.add(ProfileName);
    labelPanel.add(row1);
    JPanel row2 = new JPanel();
    row2.add(HostAddress);
    labelPanel.add(row2);
    JPanel row3 = new JPanel();
    row3.add(Account);
    labelPanel.add(row3);
    JPanel row4 = new JPanel();
    row4.add(PortNo);
    labelPanel.add(row4);
    JPanel row5 = new JPanel();
    row5.add(login);
    labelPanel.add(row5);
    JPanel row6 = new JPanel();
    row6.add(password);
    labelPanel.add(row6);
    JPanel row7 = new JPanel();
    row7.add(DownLoadPath);
    labelPanel.add(row7);
    infoPanel.setLayout(new BoxLayout(infoPanel,BoxLayout.Y_AXIS));
    infoPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT);
    row1 = new JPanel();
    row1.add(profileName);
    row1.add(profileName);
    infoPanel.add(row1);
    row2 = new JPanel();
    row2.add(hostAddress);
    row2.add(hostAddress);
    infoPanel.add(row2);
    row3 = new JPanel();
    row3.add(account);
    infoPanel.add(row3);
    row4 = new JPanel();
    row4.setLayout(new FlowLayout());
    row4.add(portNo);
    row4.add(Box.createHorizontalStrut(57));
    row4.add(Anonymous);
    row4.add(anonymous);
    infoPanel.add(row4);
    row5 = new JPanel();
    row5.add(loginName);
    infoPanel.add(row5);
    row6 = new JPanel();
    row6.add(passwd);
    infoPanel.add(row6);
    row7 = new JPanel();
    row7.setLayout(new FlowLayout());
    row7.add(downloadPath);
    row7.add(browseButton);
    infoPanel.add(row7);
    arrangedComponents.add(labelPanel, "West");
    arrangedComponents.add(infoPanel, "Center");
    cp.add(arrangedComponents, "Center");
    public void setButtonPanel() {
    buttonPanel.setLayout(new FlowLayout());
    buttonPanel.add(addButton);
    buttonPanel.add(connectButton);
    buttonPanel.add(cancelButton);
    buttonPanel.add(clearButton);
    cp.add(buttonPanel, "South");
    public void setActionListeners() {
    anonymous.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         if(anonymous.isSelected()) {
         loginName.setText("anonymous");
         passwd.setText("your email here");
         else {
         loginName.setText("");
         passwd.setText("");
    addButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         if(profileName.getText() != "" && !data.contains(profileName.getText())){
         data.add(profileName.getText());
         profileList.setListData(data);
    connectButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         connectButtonPressed();
    cancelButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         JButton b = (JButton) e.getSource();
         ConnectDialog c = (ConnectDialog) b.getTopLevelAncestor();
         c.dispose();
    clearButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         profileName.setText("");
         hostAddress.setText("");
         account.setText("");
         portNo.setText("");
         loginName.setText("");
         passwd.setText("");
         downloadPath.setText("");
    browseButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         JFrame browseFrame = new JFrame("browse for folder");
         browseFrame.setBounds(230,230,200,200);
         JDirectoryChooser fileChooser = new JDirectoryChooser();
         fileChooser.setFileSelectionMode(JDirectoryChooser.DIRECTORIES_ONLY);
         int option = fileChooser.showDialog(browseFrame);
         if(option==JFileChooser.APPROVE_OPTION) {
         File f = fileChooser.getSelectedFile();
         defaultDownloadPath = f.getAbsolutePath();
         downloadPath.setText(defaultDownloadPath);
    public void connectButtonPressed() {
    if(!profileName.getText().equals("") && !hostAddress.getText().equals("") &&
    !loginName.getText().equals("") && !passwd.getText().equals("")) {
    currProfile.setProfileName(profileName.getText());
    currProfile.setHostAddress(hostAddress.getText());
    currProfile.setAcct(account.getText());
    currProfile.setUserName(loginName.getText());
    currProfile.setPassword(passwd.getText());
    currProfile.setDownloadPath(downloadPath.getText());
    parent.setProfile(currProfile);
    this.dispose();
    else {
    JFrame f = new JFrame("Error!");
    JOptionPane.showMessageDialog(f, "Some fields empty!", "", JOptionPane.ERROR_MESSAGE);
    }

    If the dialog is modal then you can just call show and wait for it to close by the user, then grab the info:
    ConnectDialog dialog = new ConnectDialog();
    dialog .show();
    Profile profile = con.getProfile();
    makeNewConnection( profile );

  • How to set the size of a class that extends JDialog

    Hi,
    I was trying to set the size of my dialog window to be 600 by 600, but couldn't change it. Here is my code:
    public class alii extends JDialog {
    /** Creates new form alii */
    public alii(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    private void initComponents() {
    Container contentPane = getContentPane();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    closeDialog(evt);
    pack();
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    alii a = new alii(new javax.swing.JFrame(), true);
    frame.setSize(600,500);
    frame.setLocation(200,200);
    frame.setVisible(true);}}
    Please help me with this and explain to me what is the problem and what needs to be changed.
    Cheers

    Hi,
    The code you sent me doesn't work, and the code I posted wasn't a complete, but there is the complete one. You can see now what the code does.
    * alii.java
    * Created on 15 November 2003, 13:31
    * @author Ali
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    import java.applet.*;
    import java.net.*;
    public class sun extends JDialog {
    int x[] = new int[4];
    int y[] = new int[4];
    int w[] = new int[4];
    int h[] = new int[4];
    int Y_ax = 310;
    double DrawGraf[][] = new double[4][4];
    String line[] = new String[9];
    double Perc[] = new double[4];
    double Sum=0;
    GUICanvas can;
    double graphvalue[] = new double [5];
    /** Creates new form alii */
    public sun(Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    //setVisible(true);
    //setSize(600,500);
    //setLocation(200,200);
    /** 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.
    private void initComponents() {
    //Container contentPane = getContentPane();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    closeDialog(evt);
    //contentPane.setSize(700,700);
    //pack();
    public void drawthegraph(String s)
    /* try {
    URL url = new URL(
    "http://localhost:111/test/servlet/Compare?value="+s);
    BufferedReader in = new BufferedReader(
    new InputStreamReader(url.openStream()));
    for (int c = 0; c<9; c++)
    line[c] = in.readLine();
    in.close();
    }catch (Exception e){
    e.printStackTrace();
    graphvalue[0] = 200;
    graphvalue[1] = 200;
    graphvalue[2] = 100;
    graphvalue[3] = 300;
    graphvalue[4] = 20;
    //graphvalue[4] = can.d2i(graphvalue[4]);
    //System.out.println(line[8]);
    Sum = graphvalue[0]+graphvalue[1]+graphvalue[2]+graphvalue[3];
    Perc[0] = graphvalue[0]/Sum*200;
    Perc[1] = graphvalue[1]/Sum*200;
    Perc[2] = graphvalue[2]/Sum*200;
    Perc[3] = graphvalue[3]/Sum*200;
    System.out.println(Perc[0]);
    DrawGraf[0][0] = 130;
    DrawGraf[0][1] = Y_ax - Perc[0];
    DrawGraf[0][2] = 60;
    DrawGraf[0][3] = Perc[0];
    DrawGraf[1][0] = DrawGraf[0][0]+60;
    DrawGraf[1][1] = Y_ax - Perc[1];
    DrawGraf[1][2] = 60;
    DrawGraf[1][3] = Perc[1];
    DrawGraf[2][0] = DrawGraf[1][0]+60;
    DrawGraf[2][1] = Y_ax - Perc[2];
    DrawGraf[2][2] = 60;
    DrawGraf[2][3] = Perc[2];
    DrawGraf[3][0] = DrawGraf[2][0]+60;
    DrawGraf[3][1] = 310 - Perc[3];
    DrawGraf[3][2] = 60;
    DrawGraf[3][3] = Perc[3];
    for(int d=0;d<4;d++)
    x[d]=d2i(DrawGraf[d][0]);
    y[d]=d2i(DrawGraf[d][1]);
    w[d]=d2i(DrawGraf[d][2]);
    h[d]=d2i(DrawGraf[d][3]);
    repaint();
    static int d2i(double d) {return (int) Math.round(d);}
    public void paint (Graphics g)
    g.setColor(Color.red);
    for(int d=0;d<4;d++)
    g.fill3DRect(x[d],y[d],w[d],h[d],true);
    g.setColor(Color.blue);
    g.drawLine(130,130,130,310);
    g.drawLine(130,310,370,310);
    g.setColor(Color.black);
    g.drawString("WELCOME TO Ali",150,100);
    g.drawString("Region: Lambeth",430,150);
    g.drawString("Manger: ",430,170);
    g.drawString("Location: ",430,190);
    g.drawString("Number of Staff: "+graphvalue[4],430,210);
    g.drawString("Week1",135,345);
    g.drawString("Week2",195,345);
    g.drawString("Week3",255,345);
    g.drawString("Week4",315,345);
    g.drawString(" "+"20 -",100,295);
    g.drawString(" "+"40 -",100,255);
    g.drawString(" "+"60 -",100,215);
    g.drawString(" "+"80 -",100,175);
    g.drawString("100 -",100,135);
    g.setColor(Color.yellow);
    g.drawLine(130,290,370,290);
    g.drawLine(130,250,370,250);
    g.drawLine(130,210,370,210);
    g.drawLine(130,170,370,170);
    g.drawLine(130,130,370,130);
    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {
    setVisible(false);
    dispose();
    * @param args the command line arguments
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    sun sn = new sun(frame, true);
    frame.setSize(600,500);
    frame.getContentPane().add(sn);
    frame.setLocation(200,200);
    frame.setVisible(true);
    You were right that I am know to this, but getting there slowly and thanks for your help.
    Cheers

  • Create an Image in JDialog

    Hi,
    I am using Eclipse to create a GUI application.
    My problem is this... When I run it in Eclipse it finds the images just fine and they show up perfectly... But when I export to a JAR file, the image files either are distorted or don't show up at all... I am not sure if this is my coding or the JAR file...
    package iWeatherGrabber;
    imports... I got them
    public class WindowSplash extends JDialog {
    private JLabel useForImage;
    ImageIcon logo = new ImageIcon("logo.gif");
    Container contentPane;
    public WindowSplash () {
    contentPane = getContentPane();
    setTitle("iWeatherGrabber");
    setSize(FRAME_WIDTH, FRAME_HEIGHT);
    setLocationRelativeTo(null);
    setUndecorated(true);
    setForeground(Color.blue);
    setLayout(null);
    contentPane.setBackground(Color.LIGHT_GRAY);
    JPanel Border = new JPanel();
                   Border.setLayout(null);
                   Border.setBackground(Color.LIGHT_GRAY);
                   Border.setBounds(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
                   contentPane.add(Border);
                   JPanel main = new JPanel();
                   main.setLayout(null);
                   main.setBackground(Color.WHITE);
                   main.setBounds(5, 5, FRAME_WIDTH-10, FRAME_HEIGHT-10);
                   Border.add(main);
              useForImage = new JLabel(logo);
              useForImage.setBounds(5,10,440,51);
              main.add(useForImage);
    Message was edited by:
    jay2cool

    That seems to be working for the moment. Why does that work when
    ImageIcon logo = new ImageIcon("logo.gif");does not?

  • Non modal JDialog

    Hi All,
    I want a non modal JDialog which is used to show the message to the user that it is searching for the records, when a search is performed and records are retrieved from the database. When the search is going on user might hit cancel on the JDialog to cancel the search. My problem is, the cancel button on the Search dialog is not catching the event and user is not able to select the cancel option on the dialog.
    Here is my code :
    class SearchWindow extends JDialog {
    private JPanel btnPanel;
    private JLabel lblSearch;
    private JButton btnCancel;
    * Constructor
    public SearchWindow() {
    super((Frame)null, false);
    setTitle("Searching Shipment Legs");
    cancelled = false;
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
    close();
    Container contentPane = getContentPane();
    contentPane.setLayout(null);
    addButtons();
    pack();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setSize(new Dimension(300, 100));
    setSize(300,100);
    setLocation((screenSize.width-700)/2,(screenSize.height-450)/2);
    private void addButtons() {
    btnPanel = new JPanel();
    btnPanel.setLayout(new BorderLayout());
    lblSearch = new JLabel("Searching..........");
    btnCancel = new JButton("Cancel");
    btnPanel.setBackground(Color.lightGray);
    lblSearch.setBackground(Color.lightGray);
    btnCancel.setBackground(Color.lightGray);
    btnPanel.add(lblSearch, BorderLayout.CENTER);
    btnPanel.add(btnCancel, BorderLayout.SOUTH);
    btnCancel.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent evt) {
    System.out.println("cancel");
    cancelled = true;
    close();
    btnPanel.setBounds(0,0,200,50);
    this.getContentPane().add(btnPanel);
    lblSearch.setVisible(true);
    btnCancel.setVisible(true);
    this.getContentPane().validate();
    public void close() {
    this.setVisible(false);
    this.dispose();
    public void show() {
    super.show();
    paintComponents(getGraphics());
    this.setModal(false);
    Any help is greatly appreciated.
    Thanks,
    Bhaskar

    Hi Haroldsmith
    I am calling this search window in one of my programs where on button click it will fetch the records from the database. When this process is on, search dialog is shown up. Ths dialog is shown correctly and its getting closed as soon as the search is completed. But the probelm is its not allowing me to click on cancel button.
    Bhaskar

  • JOptionPane and JDialog

    Hi guys,
    I've been scooting around the net trying to find an answer to this problem. Basically I have a JDialog that users enter registration details. If they haven't completed all fields or if the password confirmation is wrong then a JOptionPane.showMessageDialog appears telling users what has happened. However if they were to then click ok in the OptionPane it closes both the option pane and the original Dialog window. Have you guys any idea?
    A code snippet below:
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class Register extends JDialog implements ActionListener {
         //declare components
         JLabel lblHeading;
         JLabel lblUserName;
         JLabel lblUserPwd;
         JLabel lblCnfUserPwd;
         JLabel lblFrstName;
         JLabel lblLstName;
         JLabel lblAge;
         JLabel lblEmpId;
         JLabel lblSex;
         JLabel lblEmail;
         String usrName;
         String strUsrPwd;
         String strCnfPwd;
         String frstName;
         String lstName;
         String age;
         String empid;
         String email;
         String sex;
         Socket toServer;
         ObjectInputStream streamFromServer;
         PrintStream streamToServer;
         JComboBox listSex;
         JTextField txtUserName;
         JPasswordField txtUsrPwd;
         JPasswordField txtCnfUsrPwd;
         JTextField txtFrstName;
         JTextField txtLstName;
         JTextField txtAge;
         JTextField txtEmpId;
         JTextField txtEmail;
         Font f;
         Color r;
         JButton btnSubmit;
         JButton btnCancel;
         public Register() {
              this.setTitle("Registration Form");
            JPanel panel=new JPanel();
              //apply the layout
               panel.setLayout(new GridBagLayout());
               GridBagConstraints gbCons=new GridBagConstraints();
              //place the components
              gbCons.gridx=0;
              gbCons.gridy=0;
              lblHeading=new JLabel("Please register below");
               Font f = new Font("Monospaced" , Font.BOLD , 12);
              lblHeading.setFont(f);
              Color c=new Color(0,200,0);
              lblHeading.setForeground(new Color(131,25,38));
              lblHeading.setVerticalAlignment(SwingConstants.TOP);
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(lblHeading, gbCons);
              gbCons.gridx = 0;
              gbCons.gridy = 1;
              lblUserName = new JLabel("Enter Username");
              gbCons.anchor=GridBagConstraints.WEST;
              panel.add(lblUserName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=1;
              txtUserName=new JTextField(15);
              panel.add(txtUserName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=2;
              lblUserPwd=new JLabel("Enter Password ");
              panel.add(lblUserPwd, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 2;
              txtUsrPwd = new JPasswordField(15);
              panel.add(txtUsrPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=3;
              lblCnfUserPwd=new JLabel("Confirm Password ");
              panel.add(lblCnfUserPwd, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=3;
              txtCnfUsrPwd=new JPasswordField(15);
              panel.add(txtCnfUsrPwd, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=4;
              lblEmpId=new JLabel("Employee ID");
              panel.add(lblEmpId, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=4;
              txtEmpId=new JTextField(15);
              panel.add(txtEmpId, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=5;
              lblFrstName=new JLabel("First Name");
              panel.add(lblFrstName, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=5;
              txtFrstName=new JTextField(15);
              panel.add(txtFrstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=6;
              lblLstName=new JLabel("Last Name");
              panel.add(lblLstName, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy = 6;
              txtLstName=new JTextField(15);
              panel.add(txtLstName, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=7;
              lblAge=new JLabel("Age");
              panel.add(lblAge, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=7;
              txtAge=new JTextField(3);
              panel.add(txtAge, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=8;
              lblEmail=new JLabel("Email address");
              panel.add(lblEmail, gbCons);
              gbCons.gridx=1;
              gbCons.gridy=8;
              txtEmail=new JTextField(20);
              panel.add(txtEmail, gbCons);
              gbCons.gridx=0;
              gbCons.gridy=9;
              lblSex=new JLabel("Sex");
              panel.add(lblSex, gbCons);
              gbCons.gridx = 1;
              gbCons.gridy=9;
              String [] sex= {"Male", "Female"};
              listSex = new JComboBox(sex);
              listSex.setSelectedIndex(0);
              panel.add(listSex, gbCons);
              JPanel btnPanel=new JPanel();
              btnSubmit=new JButton("Submit");
              btnPanel.add(btnSubmit);
              btnSubmit.addActionListener(this); //add listener to the Submit button
              btnCancel=new JButton("Cancel");
              btnPanel.add(btnCancel);
              btnCancel.addActionListener(this); //add listener to the Cancel button
              gbCons.gridx=0;
              gbCons.gridy=10;
              gbCons.anchor=GridBagConstraints.EAST;
              panel.add(btnPanel, gbCons);
              getContentPane().add(panel);
             setDefaultCloseOperation(DISPOSE_ON_CLOSE); //get rid of this window only on closing
              setVisible(true);
              setSize(450,400);
             }//end Register()
              public void actionPerformed(ActionEvent ae) {
                   Object o = ae.getSource(); //get the source of the event
                   if(o == btnCancel)
                        this.dispose();
                   if(o == btnSubmit){
                        usrName = txtUserName.getText();
                        strUsrPwd = txtUsrPwd.getText();
                        strCnfPwd = txtCnfUsrPwd.getText();
                        frstName = txtFrstName.getText();
                        lstName = txtLstName.getText();
                        age = txtAge.getText();
                        empid = txtEmpId.getText();
                        email = txtEmail.getText();
                        sex = (String)listSex.getItemAt(0);
                        if ((usrName.length() == 0) || (strUsrPwd.length() == 0) ||
                        (strCnfPwd.length() == 0) || (frstName.length() == 0) ||
                        (lstName.length() == 0) || (age.length() == 0) ||
                        (empid.length() == 0) || (email.length() == 0))
                        JOptionPane.showMessageDialog(null,
                        "One or more entry is empty. Please fill out all entries.", "Message", JOptionPane.ERROR_MESSAGE);
                        if ((!strUsrPwd.equals(strCnfPwd))){
                             JOptionPane.showMessageDialog(null,
                             "Passwords do not match. Please try again", "Message", JOptionPane.ERROR_MESSAGE);
                        Thanks,
    Chris

    try something like this:
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ActionListener;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    public class About extends JDialog {
    /** Creates new form About */
    public About(JFrame parent) {
    super(parent,true);
    initComponents();
    pack();
    Rectangle parentBounds = parent.getBounds();
    Dimension size = getSize();
    // Center in the parent
    int x = Math.max(0, parentBounds.x + (parentBounds.width - size.width) / 2);
    int y = Math.max(0, parentBounds.y + (parentBounds.height - size.height) / 2);
    setLocation(new Point(x, y));
    and from the main dialog:
    new About(this).setVisible(true);

  • JProgressBar in a JDialog ?

    I wished to display my progress bar in a JDialog.
    I tried adding the progress bar to an independent JDialog and displayed it and
    it seemed to work.
    But I wanted a modal JDialog to be part of the JFrame of my application while
    showing the progress. This time neither the progress bar that was added is showing up
    nor it is getting updated !!
    How is this typically implemented ?
    It will be great to see a reply from the Swing gurus around so that I complete my application
    in a style!
    Thanks in advance.

    Hi,
    I have the same problem. I am trying to add a JProgressBar to a JDialog. I add the timer for the progressbar before the dialog is made visible. But my progressbar fails to display.
    A part of my code to illustrate my procedure --
    public class ClusterProgressDialog extends JDialog {
        JProgressBar progressBar;
        JLabel currentProcessLabel;
        Timer timer;
        final ClusterProcess clusterProcess;
        public ClusterProgressDialog(Frame parent, String title,
                ClusterProcess process) {
            super(parent, title, false);
            setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            clusterProcess = process;
            currentProcessLabel = new JLabel();
            currentProcessLabel.setBackground(Color.WHITE);
            initialize(parent);
            setVisible(true);
        public void initialize(Frame parent) {
            setSize(300, 100);
            if (!Platform.isMac())
                setBackground(Color.WHITE);
            progressBar = new JProgressBar();
            progressBar.setIndeterminate(true);
            timer = new Timer(100, new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    progressBar.setValue((progressBar.getMaximum() - clusterProcess
                            .getClusterCount()));
                    if (clusterProcess.isDone()) {
                        Toolkit.getDefaultToolkit().beep();
                        timer.stop();
                        setVisible(false);
                        dispose();
            JPanel contentPane = new JPanel();
            contentPane.setLayout(new BorderLayout());
            contentPane.add(currentProcessLabel, BorderLayout.NORTH);
            contentPane.add(progressBar, BorderLayout.CENTER);
            Border border = BorderFactory.createMatteBorder(10, 10, 10, 10,
                    Color.WHITE);
            contentPane.setBorder(border);
            setContentPane(contentPane);
        public void setLimits(int min, int max) {
            progressBar.setIndeterminate(false);
            progressBar.setMinimum(min);
            progressBar.setMaximum(max);
            progressBar.setValue(min);
            progressBar.setStringPainted(true);
        public void startTimer() {
            timer.start();
    }I reuse the progress bar, alternating it between indeterminate and determinate states for different functions in my process being monitored.
    Can anyone help me in this?

  • JDialog jdk1.5 vs jdk1.6

    Hi,
    I'm having a different behaviour when I'm executing the following code on jdk1.5 and 1.6 :
    import java.awt.BorderLayout;
    import java.awt.Color;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    class test extends JFrame {
         private JTabbedPane tabbedPane;
         private JPanel panel1;
         private JPanel panel2;
         private JPanel panel3;
         // Main method to get things started
         public static void main(String args[]) {
              // Create an instance of the test application
              test mainFrame = new test();
              mainFrame.setVisible(true);
         public test() {
              // NOTE: to reduce the amount of code in this example, it uses
              // panels with a NULL layout. This is NOT suitable for
              // production code since it may not display correctly for
              // a look-and-feel.
              setTitle("Tabbed Pane Application");
              setSize(300, 200);
              setBackground(Color.gray);
              JPanel topPanel = new JPanel();
              topPanel.setLayout(new BorderLayout());
              getContentPane().add(topPanel);
              // Create the tab pages
              createPage1();
              createPage2();
              // Create a tabbed pane
              tabbedPane = new JTabbedPane();
              tabbedPane.addTab("Page 1", panel1);
              tabbedPane.addTab("Page 2", panel2);
              topPanel.add(tabbedPane, BorderLayout.CENTER);
              tabbedPane.addChangeListener(new ChangeListener() {
                   // This method is called whenever the selected tab changes
                   public void stateChanged(ChangeEvent evt) {
                        JTabbedPane pane = (JTabbedPane) evt.getSource();
                        // Get current tab
                        int sel = pane.getSelectedIndex();
                        if (sel == 1) {
                             JDialog dial = new JDialog();
                             dial.setModal(true);
                             dial.setVisible(true);
         public void createPage1() {
              panel1 = new JPanel();
              panel1.setLayout(null);
              JLabel label1 = new JLabel("Username:");
              label1.setBounds(10, 15, 150, 20);
              panel1.add(label1);
              JTextField field = new JTextField();
              field.setBounds(10, 35, 150, 20);
              panel1.add(field);
              JLabel label2 = new JLabel("Password:");
              label2.setBounds(10, 60, 150, 20);
              panel1.add(label2);
              JPasswordField fieldPass = new JPasswordField();
              fieldPass.setBounds(10, 80, 150, 20);
              panel1.add(fieldPass);
         public void createPage2() {
              panel2 = new JPanel();
              panel2.setLayout(new BorderLayout());
              panel2.add(new JButton("North"), BorderLayout.NORTH);
              panel2.add(new JButton("South"), BorderLayout.SOUTH);
              panel2.add(new JButton("East"), BorderLayout.EAST);
              panel2.add(new JButton("West"), BorderLayout.WEST);
              panel2.add(new JButton("Center"), BorderLayout.CENTER);
    }On jdk1.5 when I press the 2nd tab, the popup is displayed but the tab 2 is only displayed when I close the popup.
    On jdk1.6 when I press the 2nd tab, the popup is displayed and tab 2 is also displayed even when I don't close the popup.
    Does anyone had this kind of problem ?
    I would expect to have the same behaviour on 1.5 and 1.6..
    Is there any workaround to display the 2nd tab only when popup is close on jdk 1.6 ?
    Regards
    Tiago

    It can easily be solved by inelegant kludge.
    class test extends JFrame
      private JTabbedPane tabbedPane;
      private JPanel panel1;
      private JPanel panel2;
      private JPanel panel3;
      private boolean dlgShown = false; // *** class variable
        tabbedPane.addChangeListener(new ChangeListener()
          public void stateChanged(ChangeEvent evt)
            JTabbedPane pane = (JTabbedPane) evt.getSource();
            int sel = pane.getSelectedIndex();
            if (sel == 1)
              if (!dlgShown) // ***
                pane.setSelectedIndex(0); // ***
                JDialog dial = new JDialog();
                dial.setModal(true);
                dial.setPreferredSize(new Dimension(200, 100));
                dial.pack();
                dial.setLocationRelativeTo(null);
                dial.setVisible(true);
                dlgShown = !dlgShown; // ***
                pane.setSelectedIndex(1); // ***
              else
                dlgShown = !dlgShown;
    }note: more elegant solutions most welcome!

Maybe you are looking for