Help Painting in Swing

I'm new to Swing, and am having trouble painting both buttons and other graphics.
For instance:
package example.src;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import example.src.*;
public class Example extends JFrame {
    public Example() {
         this.setSize(500, 500);
         this.setTitle("Example");
         addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e)
                    System.exit(0);
          Container c = this.getContentPane();
          c.add(new DrawPanel());
          c.add(new ButtonPanel());
    public static void main(String[] args) {
         JFrame Drawing_Ex = new Example();
         Drawing_Ex.setVisible(true);
package example.src;
import java.awt.*;
import javax.swing.*;
public class DrawPanel extends JPanel implements Runnable
     private boolean x = true;
     public DrawPanel() {
          Thread thread = new Thread(this);
          thread.start();
     public void run() {
         int counter = 0;
         while (true) {
              counter++;
              if (counter == 500) {
                   if (x) {
                        x = false;
                   else {
                        x = true;
                   counter = 0;
              this.repaint();
              try {
                   Thread.sleep(1);
              catch (InterruptedException ex) {
                   System.out.println("Failed.");
    public void paintComponent(Graphics g) {
         super.paintComponent(g);
         g.setColor(Color.blue);
         if (x) {
              g.drawString("YES", 100, 100);
         else g.drawString("NO", 100, 100);
package example.src;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.event.*;
import java.awt.*;
public class ButtonPanel extends JPanel {
public static JButton play;
public static JButton changeCpu;
    public ButtonPanel() {
         super();
         this.setLayout(null);
         play = new JButton("Restart");
        play.setBounds(420, 170, 80, 30);
        play.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent event) {
        this.add(play);
        play.setVisible(true);
        changeCpu = new JButton("Change Level");
        changeCpu.setBounds(300, 170, 120, 30);
        changeCpu.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent event) {
        changeCpu.setVisible(true);
        this.add(changeCpu);
}This should have two buttons, as well as a string yes/no that switches. However, if the buttons get added last to the content pane, the string doesn't show, and if the drawing gets added last, the buttons won't show. Any help?
(This is for a pong game - I want two buttons, one that changes the Cpu's level and another that restarts the game, and I need the player, enemy, and ball to be drawn).

Both using and understanding layouts, is vital in the Java X-plat language. The sooner people realize that, the better off they are.
There were other things in the code that were either questionable or could be improved, but I stuck to concentrating of the layout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example extends JFrame {
  public Example() {
    this.setSize(500, 500);
    this.setTitle("Example");
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e)
        System.exit(0);
    Container c = this.getContentPane();
    // 'when EAST meets WEST' otherwise they are
    // stacked, and only one is visible!
    c.add(new DrawPanel(), BorderLayout.WEST);
    c.add(new ButtonPanel(), BorderLayout.EAST);
    // always (validate or) pack() the main UI
    // otherwise unpredictable behaviour will be seen
    pack();
  public static void main(String[] args) {
    JFrame Drawing_Ex = new Example();
    Drawing_Ex.setVisible(true);
class DrawPanel extends JPanel implements Runnable
  private boolean x = true;
  public DrawPanel() {
    Thread thread = new Thread(this);
    thread.start();
    // important, so the layout does not collapse the empty
    // panel to 0x0
    setPreferredSize( new Dimension(200,200) );
  public void run() {
    int counter = 0;
    while (true) {
      counter++;
      if (counter == 500) {
        if (x) {
          x = false;
        else {
          x = true;
        counter = 0;
      this.repaint();
      try {
        Thread.sleep(1);
      catch (InterruptedException ex) {
        System.out.println("Failed.");
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.blue);
    if (x) {
      g.drawString("YES", 100, 100);
    else g.drawString("NO", 100, 100);
class ButtonPanel extends JPanel {
  public static JButton play;
  public static JButton changeCpu;
  public ButtonPanel() {
    super();
    // don't do that, except in a layout manager..
    //this.setLayout(null);
    play = new JButton("Restart");
    // use a layout manager with appropriate padding,
    // or add borders to the components
    //play.setBounds(420, 170, 80, 30);
    play.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
    this.add(play);
    play.setVisible(true);
    changeCpu = new JButton("Change Level");
    changeCpu.setBounds(300, 170, 120, 30);
    changeCpu.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
    changeCpu.setVisible(true);
    this.add(changeCpu);
}Edited by: AndrewThompson64 on May 31, 2008 6:56 AM

Similar Messages

  • Help menu in Swing

    Hi all,
    can anyone tell me how to create an Help menu in Swing??
    i mean, like the Help menu options that you can see in Windows.
    I mean, again, by clicking on the Help option, you should see Contents etc..
    is it possible to do it in Swing? if so, how?
    thanx and regards
    marco

    There's no class called "HelpMenu" or anything like that, you'd have to create your own using tabbed panes and JTrees.

  • Help!!  swing painter!!!

    I have the homework that is to write a swing painter like microsoft windows mspaint.
    but, the problem is that if i change the swing window size, the picture drawn will partially disappear.
    how to solve this problem?
    have any good references for me?
    thx.........

    The usual reason for this is that you are drawing to the components graphics object outside the paint method so that when the component is repainted, it does not know what used to be there to repaint. You have a couple options.
    1. Remember all the 'shapes' which where drawn and paint them all in the paint method
    2. Draw to an offscreen image and just paint that image in the paint method
    #1 is more memory intensive and #2 will take a bit more programming
    Here is a tutorial about #1
    http://java.sun.com/docs/books/tutorial/uiswing/painting/drawingShapes.html
    Here is a search of the forums for #2
    http://onesearch.sun.com/search/developers/index.jsp?qt=%2B%22offscreen+image%22&col=devforums

  • Custom Painting in Swing Panels.

    I am trying to implement a custom painted panel on a JFrame. The panel performs custom painting in a separate thread. In additon, the frame also adds other swing panels (containing standard components) dynamically as per menu selection. I use box layout on frame to add / remove panels.
    The paint panel doesnt render properly whenever other panels are added or replaced. The paint panel is rendered only when no other are panels added to the frame.
    There is no problem however with adding / replacing components-only panels containing no custom painting.
    Please help me understand what I am missing. Any clues / suggestions most welcome
    sridhar

    Hi,
    You have problem only when adding custom painting JPanel to the same custom painting JPanel??? Are you layering your painting methods??? Like the most upper JPanel paints and then the childs??? What do you get for drawings??? Do you use invoque later method??? What is your priority on the Threads you are using???
    JRG

  • Incremental Painting in Swing

    Hello All!
    How can I achieve incremental painting in a JPanel or in general JComponents.. By "incremental painting" I mean I do not want to lose my previous drawings on the panel aka. I want to update the drawing by adding more drawings.
    An example would help this is the code:
    import java.awt.*;
    import javax.swing.*;
    public class CustomPanel extends JPanel{
    public final static int CIRCLE = 1, SQUARE = 2;
    private int shape;
    public void paintComponent(Graphics g){
    super.paintComponent(g);
    if(shape == CIRCLE)
    g.fillOval(50,10,60,60);
    else if(shape == SQUARE)
    g.fillRect(150,110,60,60);
    public void draw(int s){
    shape = s;
    repaint();
    This class is used by the following class:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CustomPanelTest extends JFrame{
    private JPanel buttonPanel;
    private CustomPanel myPanel;
    private JButton circle, square;
    public CustomPanelTest()
    super("Custom Panel Test");
    myPanel = new CustomPanel();
    myPanel.setBackground(Color.green);
    square = new JButton("Square");
    square.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e)
    myPanel.draw(CustomPanel.SQUARE);
    circle = new JButton("Circle");
    circle.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e)
    myPanel.draw(CustomPanel.CIRCLE);
    buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1,2) );
    buttonPanel.add(circle);
    buttonPanel.add(square);
    Container c = getContentPane();
    c.add(myPanel, BorderLayout.CENTER);
    c.add(buttonPanel, BorderLayout.SOUTH);
    setSize(300,150);
    show();
    public static void main ( String args[] )
    CustomPanelTest app = new CustomPanelTest();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing (WindowEvent e )
    System.exit(0);
    While executing, either a circle or square is drawn by erasing the previous drawing. What I want to achieve is for example drawing a series of circles and/or squares without losing the previous drawings.
    Thank you!!!!

    This will do it. I added a bufferedimage.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.BufferedImage;
    public class CustomPanel  extends JPanel
         public final static int CIRCLE = 1, SQUARE = 2;
         private int           shape;
         private BufferedImage I = null;
         private Graphics      G;
    public void paintComponent(Graphics g)
         if (I == null)
              I = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_ARGB);     
              G = I.getGraphics();
              G.setColor(Color.white);
              G.fillRect(0,0,getWidth(),getHeight());
         super.paintComponent(g);
         G.setColor(Color.red);
         if(shape == CIRCLE) G.fillOval(50,10,60,60);
         if(shape == SQUARE) G.fillRect(150,110,60,60);
         g.drawImage(I,0,0,null);
    public void draw(int s)
         shape = s;
         repaint();
    }Noah

  • Help with implementing Swing GUI within jpg image

    Dear Java Experts,
    I have a question, is there a way to implement java swing objects (ie jbutton, jcombobox, etc) within an imageicon. Basically, i am trying to juggle between ways of getting JSwing GUI into a background jpg image. Please help me. I thank you all in advance.

    You've it back to front.
    Create an transparent extension of JPanel that paints an image on it's
    background before running it's super class paint method.
    You'll need to extend this example to stretch, center or tile the image
    but otheriwse it's complete.
    BTW - you have to pass an argument to this example that is the path of
    the image you want on the background of the panel, like:
    java -cp <whatever> MyJavaProject1 images/something.gif
    Enjoy.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class MyJavaProject1
         static class BackgroundPanel
              extends JPanel
              private ImageIcon mIcon;
              public BackgroundPanel(ImageIcon icon) {
                   mIcon= icon;
                   super.setOpaque(false);
              public void setOpaque(boolean flag) { }
              public void paint(Graphics g)
                   g.drawImage(mIcon.getImage(), 0, 0, null);
                   super.paint(g);
         public static void main(String[] argv)
              JFrame frame= new JFrame(argv[0]);
              BackgroundPanel panel= new BackgroundPanel(new ImageIcon(argv[0]));
              panel.setLayout(new GridLayout(0,2,4,4));
              panel.setBorder(new EmptyBorder(4,4,4,4));
              panel.add(new JLabel("Name"));
              panel.add(new JTextField());
              panel.add(new JLabel("Address"));
              panel.add(new JTextField());
              panel.add(new JLabel("Phone"));
              panel.add(new JTextField());
              frame.getContentPane().add(panel, BorderLayout.CENTER);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setResizable(false);
              frame.setVisible(true);
    }

  • Need help writing custom Swing JComponent

    Hi, I am trying to write my own version of a "comboBox" that does not have a drop-down box, and doesn't have a down-arrow icon on it. What I would really like to do is basically write a class that is a JLabel, but will accept KeyEvents and FocusEvents. Here is an example of exactly what I want, but it is written using an uneditable JTextArea(Hit the up and down arrow Keys to scroll through the options):
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.text.JTextComponent;
    import java.awt.event.KeyListener;
    import java.awt.event.FocusListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.FocusEvent;
    import java.awt.Color;
    import java.awt.Font;
    public class Test implements KeyListener, FocusListener
         Color colorBackgroundFocus = new java.awt.Color(240, 240, 240);
         Color colorText = new Color(0, 0, 128);
         Font fontText = new java.awt.Font("SansSerif", 1, 12);
         JTextArea jTextAreaPOPayment;
         public static void main(String[] args)
              new Test();
         * The Constructor for Test
         public Test(){
              JFrame jFrame = new JFrame("�:o)");
              jFrame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        ((JFrame)e.getComponent()).setVisible(false);
                        ((JFrame)e.getComponent()).dispose();
                        System.exit(0);
              jTextAreaPOPayment = new JTextArea();
              setUnEditableTextProperties(jTextAreaPOPayment, "jTextAreaPOPayment", "Cash", 60, 15, 10, 10);
              jFrame.getContentPane().add(jTextAreaPOPayment);
              jFrame.pack();
              jFrame.setVisible(true);
         * The Following is used to set all the properties for the JTextArea
         public void setUnEditableTextProperties(JTextComponent jTextComponent, String stringVariableName, String stringText, int intSizeX, int intSizeY,
         int intLocationX, int intLocationY){
              jTextComponent.setSize(new java.awt.Dimension(intSizeX, intSizeY));
              jTextComponent.setLocation(new java.awt.Point(intLocationX, intLocationY));
              jTextComponent.setName(stringVariableName);
              jTextComponent.setVisible(true);
              jTextComponent.setForeground(colorText);
              jTextComponent.setBackground(null);
              jTextComponent.setFont(fontText);
              jTextComponent.addFocusListener(this);
              jTextComponent.addKeyListener(this);
              jTextComponent.setEditable(false);
              jTextComponent.setText(stringText);
         * The Following is used to Cycle the Payment Types
         public void cyclePOPayment(boolean booleanUp){
              if (jTextAreaPOPayment.getText().compareTo("Cash") == 0)
                   jTextAreaPOPayment.setText(booleanUp ? "Check" : "Credit");
              else if (jTextAreaPOPayment.getText().compareTo("Credit") == 0)
                   jTextAreaPOPayment.setText(booleanUp ? "Cash" : "Check");
              else if (jTextAreaPOPayment.getText().compareTo("Check") == 0)
                   jTextAreaPOPayment.setText(booleanUp ? "Credit" : "Cash");
         * The Following are needed to implement KeyListener Class
        public void keyTyped(KeyEvent e) {
        public void keyPressed(KeyEvent e) {
              if (e.getComponent().getName().compareTo("jTextAreaPOPayment") == 0)
                   if (e.getKeyText(e.getKeyCode()).equalsIgnoreCase("Up")){
                        cyclePOPayment(true);
                   else if (e.getKeyText(e.getKeyCode()).equalsIgnoreCase("Down")){
                        cyclePOPayment(false);
        public void keyReleased(KeyEvent e) {
         * The Following is needed to implement FocusListener Class
         public void focusGained(FocusEvent e) {
              if (e.getComponent().getName().compareTo("jTextAreaPOPayment") == 0){
                   jTextAreaPOPayment.setBackground(colorBackgroundFocus);
                   jTextAreaPOPayment.select(-1, 0);
        public void focusLost(FocusEvent e) {
              if (e.getComponent().getName().compareTo("jTextAreaPOPayment") == 0){
                   jTextAreaPOPayment.setBackground(null);
    }Here is what I tried to do, but I think I need to write the "fireFocusEvent" method?? I read something about tha tsomewhere, but can't find it again. I tried just implementing the focusListener and KeyListener, and that didn't work...Can someone Help me please!!
    what I tried:
    import javax.swing.JComponent;
    import java.awt.event.FocusListener;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.FocusEvent;
    import java.awt.Graphics;
    import java.awt.Dimension;
    class ComboJLabel extends JComponent implements FocusListener, KeyListener
         String stringText;
         // The preferred size of the gauge
         int Height = 20;  
         int Width  = 20;
         public ComboJLabel(){
              this.stringText = "Test";
         public ComboJLabel(String stringText){
              this.stringText = stringText;
              this.addKeyListener(this);
              this.addFocusListener(this);
         public void keyPressed(KeyEvent e){
              System.out.println("KeyPressed");
         public void keyTyped(KeyEvent e){
              System.out.println("KeyTyped");
         public void keyReleased(KeyEvent e){
              System.out.println("KeyReleased");
         public void focusGained(FocusEvent e){
              System.out.println("Focus Gained");
         public void focusLost(FocusEvent e){
              System.out.println("Focus lost");
         public void setText(String stringNewText){
              stringText = stringNewText;
         public void paint(Graphics g){
           g.setColor(java.awt.Color.black);
           g.drawString(stringText, 3, 15);
         public Dimension getPreferredSize() {
              return new Dimension(Width, Height);
         public Dimension getMinimumSize() {
              return new Dimension(Width, Height);
    import javax.swing.JFrame;
    class TestComboJLabel
         public static void main(String[] args)
              JFrame jFrame = new JFrame();
              ComboJLabel comboJLabel = new ComboJLabel();
              jFrame.getContentPane().add(comboJLabel);
              jFrame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        ((JFrame)e.getComponent()).setVisible(false);
                        ((JFrame)e.getComponent()).dispose();
                        System.exit(0);
              jFrame.pack();
              jFrame.setVisible(true);
    }But that didn't work! If anyone can help, or show me a good site that tells me how to, It would greatly appreciated! Thanks in advanced,
    Jeff �:o)

    Yeah,sorry about the length...If you just grab the first piece of code(that works BTW0, you will see Exactly what I am trying to do...I just don't want to use anything that already exists and Jerry-Rig it...I want to try and create a new JComponent, more as a learning experience than anything else.
    But thanks for the response!

  • Trying Very Hard to Paint in Swing

    I'm sorry that this is such a newbie question, and yes I've been through the forums and the web and everywhere, but the problem isn't so much that I can't find answers to this question, so much as nothing I try will work. I'm just trying to paint into a JFrame in Swing, but I can't get anything to show up. I've tried using both paint(Graphics g) and paintComponent(Graphics g), but neither of those did anything. Then I tried calling super.paintComponent(g), but I got a "cannot resolve symbol" error, and I think I spelled everything correctly and imported everything, but I may be wrong. Here's my code... I hope someone can help me.
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Board extends Thread{
        private BufferedReader readIn;
        private String readFromServer;
        private PrintWriter sendOut;
        public Board(BufferedReader in, PrintWriter out){
         readIn = in;
         sendOut = out;
        public void run() {
         JFrame board = new JFrame("Board");
         board.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                  System.exit(0);
         board.pack();
         board.setVisible(true);
         try {
         readFromServer = readIn.readLine();
            while (true) {
             if (readFromServer.length()<2) {
             readFromServer = readIn.readLine();
             if (readFromServer.startsWith("fics%") && readFromServer.length()<10) {
                  readFromServer = readIn.readLine();
              readFromServer = readIn.readLine();
                //window.append(readFromServer);
             //window.append("\n");
             readFromServer = readIn.readLine();
         catch (IOException sio) { }
        public void paintComponent(Graphics g) {
         super.paintComponent(g);
         Image image = Toolkit.getDefaultToolkit().getImage("e:\\desktop\\page02b.jpg");
         g.drawImage(image, 0, 0, null);
         g.setColor(Color.red);
         g.drawRect(0,0,100,100);
         g.setColor(Color.blue);
         g.drawRect(0,0,100,100);
        //public void update(Graphics g) {
        //paint(g);
    }

    No offense,but it looks like you have total mess in your head.
    Here is working animation application i took from book "Java Thread Programming". Maybe it will help you.
    Why you need to construct your class in a thread that IS this class still mystery to me. Don't forget that you can create a lot of other threads which will do whatever you want.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Slide extends JComponent {
      private BufferedImage[] slide;
      private Dimension slideSize;
      private volatile int currSlide;
    private Thread interThread;
    private volatile boolean noStopRequested;
    public Slide() {
       currSlide = 0;
       slideSize = new Dimension(50, 50);
       buildSlides();
       setMinimumSize(slideSize);
       setPreferredSize(slideSize);
       setMaximumSize(slideSize);
       setSize(slideSize);
       noStopRequested = true;
      Runnable r = new Runnable() {
              public void run() {
                   try {
                        runWork();
                         }catch(Exception x) {
                          x.printStackTrace();
       interThread = new Thread(r, "Slides");
       interThread.start();
    private void buildSlides() {
             slide = new BufferedImage[20];
        Color rectColor = new Color(100, 160, 250);
        Color circleColor = new Color(250, 250, 150);
        for(int i=0; i < slide.length; i++) {
         slide[i] = new BufferedImage(
             slideSize.width,
             slideSize.height,
           BufferedImage.TYPE_INT_RGB);
       Graphics2D gg = slide.createGraphics();
    gg.setColor(rectColor);
    gg.fillRect(0, 0, slideSize.width, slideSize.height);
    gg.setColor(circleColor);
    int d = 0;
    if(i < (slide.length/2)) {
    d = 5 + (8*i);
    }else {
    d = 5 + (8*(slide.length-i));
    int inset = (slideSize.width - d)/2;
    gg.fillOval(inset, inset, d, d);
    gg.setColor(Color.black);
    gg.drawRect(
    0, 0, slideSize.width-1, slideSize.height-1);
    gg.dispose();
    public void paint(Graphics g) {
    g.drawImage(slide[currSlide], 0, 0, this);
    private void runWork() {
    while(noStopRequested) {
    try {
    Thread.sleep(100);
    currSlide =
    (currSlide +1 )%slide.length;
    repaint();
    }catch(InterruptedException x) {
    Thread.currentThread().interrupt();
    public void stopRequest() {
    noStopRequested = false;
    interThread.interrupt();
    public boolean isAlive() {
    return interThread.isAlive();
    public static void main(String[] args) {
    Slide s = new Slide();
    JPanel p = new JPanel(new FlowLayout());
    p.add(s);
    JFrame f = new JFrame("Slide Show");
    f.setContentPane(p);
    f.setSize(250, 150);
    f.setVisible(true);

  • Please help: RMI and Swing/AWT issue

    Hi guys, I've been having a lot of trouble trying to get a GUI application to work with RMI. I'd appreciate any help. Here's the story:
    I wrote a Java application and its GUI using Netbeans. In a nutshell, the application is about performing searches. I am now at the point where I need exterior programs to use my application's search capabilities, thus needing RMI. Such exterior programs are to call methods currently implemented in my application.
    I implemented RMI, and got the client --> server communication working. However, the GUI just breaks. It starts outputting exceptions, gets delayed, doesn't update properly, some parts of it stop working.... basically hysterical behavior.
    Now take a look at this line within my server class:
    Naming.rebind("SearchProgram", mySearchProgram);
    If I take it out, RMI obviously does not work... but the application and its GUI work flawlessly. If I put it in, the RMI calls work, but the GUI's above symptoms occur again. Among the symptoms are null pointer exceptions which all look similar, are related to "AWT-EventQueue-0", and keep ocurring. Here's just snippet of the errors outputted:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalScrollBarUI.getPreferredSize(MetalScrollBarUI.java:102)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1615)
    at javax.swing.JScrollBar.getMinimumSize(JScrollBar.java:704)
    at javax.swing.ScrollPaneLayout.minimumLayoutSize(ScrollPaneLayout.java:624)
    at java.awt.Container.minimumSize(Container.java:1598)
    at java.awt.Container.getMinimumSize(Container.java:1583)
    at javax.swing.JComponent.getMinimumSize(JComponent.java:1697)
    at java.awt.BorderLayout.minimumLayoutSize(BorderLayout.java:634)
    at java.awt.Container.minimumSize(Container.java:1598)
    at java.awt.Container.getMinimumSize(Container.java:1583)
    at javax.swing.JComponent.getMinimumSize(JComponent.java:1697)
    at java.awt.BorderLayout.minimumLayoutSize(BorderLayout.java:634)
    at java.awt.Container.minimumSize(Container.java:1598)
    at java.awt.Container.getMinimumSize(Container.java:1583)
    at javax.swing.JComponent.getMinimumSize(JComponent.java:1697)
    at javax.swing.BoxLayout.checkRequests(BoxLayout.java:433)
    at javax.swing.BoxLayout.layoutContainer(BoxLayout.java:375)
    at java.awt.Container.layout(Container.java:1401)
    at java.awt.Container.doLayout(Container.java:1390)
    at java.awt.Container.validateTree(Container.java:1473)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validateTree(Container.java:1480)
    at java.awt.Container.validate(Container.java:1448)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:379)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:113)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicMenuItemUI.getPreferredMenuItemSize(BasicMenuItemUI.java:400)
    at javax.swing.plaf.basic.BasicMenuItemUI.getPreferredSize(BasicMenuItemUI.java:310)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1615)
    at javax.swing.BoxLayout.checkRequests(BoxLayout.java:434)
    at javax.swing.BoxLayout.preferredLayoutSize(BoxLayout.java:251)
    at javax.swing.plaf.basic.DefaultMenuLayout.preferredLayoutSize(DefaultMenuLayout.java:38)
    at java.awt.Container.preferredSize(Container.java:1558)
    at java.awt.Container.getPreferredSize(Container.java:1543)
    at javax.swing.JComponent.getPreferredSize(JComponent.java:1617)
    at javax.swing.JRootPane$RootLayout.layoutContainer(JRootPane.java:910)
    at java.awt.Container.layout(Container.java:1401)
    at java.awt.Container.doLayout(Container.java:1390)
    at java.awt.Container.validateTree(Container.java:1473)
    at java.awt.Container.validate(Container.java:1448)
    at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:379)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:113)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    There are no complaints about anything within my code, it's all GUI related whenever I make a bind() or rebind() call.
    Again, any help here would be great... cause this one's just beating me.
    Thanks!

    Maybe you want to change that worker thread to
    not do RMI but anything else (dummy data) to see if it really is RMI, I doubt it, I think you are updating some structures that have to do with swing GUI and hence you will hang.
    Just check this out.

  • Urgent help need on swing problem

    Dear friends,
    I met a problem and need urgent help from guru here, I am Swing newbie,
    I have following code and hope to draw lines between any two components at RUN-TIME, not at design time
    Please throw some skeleton code, Thanks so much!!
    code:
    package com.swing.test;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class LongguConnectLineCommponent
        public static void main(String[] args)
            JFrame f = new JFrame("Connecting Lines");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new ConnectionPanel());
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class ConnectionPanel extends JPanel
        JLabel label1, label2, label3, label4;
        JLabel[] labels;
        JLabel selectedLabel;
        int cx, cy;
        public ConnectionPanel()
            setLayout(null);
            addLabels();
            label1.setBounds( 25,  50, 125, 25);
            label2.setBounds(225,  50, 125, 25);
            label3.setBounds( 25, 175, 125, 25);
            label4.setBounds(225, 175, 125, 25);
            determineCenterOfComponents();
            ComponentMover mover = new ComponentMover();
            addMouseListener(mover);
            addMouseMotionListener(mover);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            Point[] p;
            for(int i = 0; i < labels.length; i++)
                for(int j = i + 1; j < labels.length; j++)
                    p = getEndPoints(labels, labels[j]);
    //g2.draw(new Line2D.Double(p[0], p[1]));
    private Point[] getEndPoints(Component c1, Component c2)
    Point
    p1 = new Point(),
    p2 = new Point();
    Rectangle
    r1 = c1.getBounds(),
    r2 = c2.getBounds();
    int direction = r1.outcode(r2.x, r2.y);
    switch(direction) // r2 located < direction > of r1
    case (Rectangle.OUT_LEFT): // West
    p1.x = r1.x;
    p1.y = r1.y;
    p2.x = r2.x + r2.width;
    p2.y = r2.y;
    if(r1.y > cy)
    p1.y = r1.y + r1.height;
    p2.y = r2.y + r2.height;
    break;
    case (Rectangle.OUT_TOP): // North
    p1.x = r1.x;
    p1.y = r1.y;
    p2.x = r2.x;
    p2.y = r2.y + r2.height;
    if(r1.x > cx && r2.x > cx)
    p1.x = r1.x + r1.width;
    p2.x = r2.x + r2.width;
    break;
    case (Rectangle.OUT_LEFT + Rectangle.OUT_TOP): // NW
    p1.x = r1.x;
    p1.y = r1.y;
    p2.x = r2.x + r2.width;
    p2.y = r2.y;
    if(r1.y > r2.y + r2.height)
    p2.y = r2.y + r2.height;
    break;
    case (Rectangle.OUT_RIGHT): // East
    p1.x = r1.x + r1.width;
    p1.y = r1.y;
    p2.x = r2.x;
    p2.y = r2.y;
    if(r1.y > cy)
    p1.y = r1.y + r1.height;
    p2.y = r2.y + r2.height;
    break;
    case (Rectangle.OUT_TOP + Rectangle.OUT_RIGHT): // NE
    p1.x = r1.x + r1.width;
    p1.y = r1.y;
    p2.x = r2.x;
    p2.y = r2.y;
    if(r1.y > cy)
    p1.y = r1.y + r1.height;
    p2.y = r2.y + r2.height;
    if(r1.y > r2.y + r2.height)
    p1.y = r1.y;
    else
    if(r1.y > r2.y + r2.height)
    p2.y = r2.y + r2.height;
    break;
    case (Rectangle.OUT_BOTTOM): // South
    p1.x = r1.x;
    p1.y = r1.y + r1.height;
    p2.x = r2.x;
    p2.y = r2.y;
    if(r1.x > cx && r2.x > cx)
    p1.x = r1.x + r1.width;
    p2.x = r2.x + r2.width;
    break;
    case (Rectangle.OUT_RIGHT + Rectangle.OUT_BOTTOM): // SE
    p1.x = r1.x + r1.width;
    p1.y = r1.y + r1.height;
    p2.x = r2.x;
    p2.y = r2.y;
    break;
    case (Rectangle.OUT_BOTTOM + Rectangle.OUT_LEFT): // SW
    p1.x = r1.x;
    p1.y = r1.y + r1.height;
    p2.x = r2.x;
    p2.y = r2.y;
    if(r1.x > r2.x + r2.width)
    p2.x = r2.x + r2.width;
    if(r1.x > cx && r2.x > cx)
    p1.x = r1.x + r1.width;
    p2.x = r2.x + r2.width;
    return new Point[] {p1, p2};
    private void determineCenterOfComponents()
    int
    xMin = Integer.MAX_VALUE,
    yMin = Integer.MAX_VALUE,
    xMax = 0,
    yMax = 0;
    for(int i = 0; i < labels.length; i++)
    Rectangle r = labels[i].getBounds();
    if(r.x < xMin)
    xMin = r.x;
    if(r.y < yMin)
    yMin = r.y;
    if(r.x + r.width > xMax)
    xMax = r.x + r.width;
    if(r.y + r.height > yMax)
    yMax = r.y + r.height;
    cx = xMin + (xMax - xMin)/2;
    cy = yMin + (yMax - yMin)/2;
    private class ComponentMover extends MouseInputAdapter
    Point offsetP = new Point();
    boolean dragging;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    for(int i = 0; i < labels.length; i++)
    Rectangle r = labels[i].getBounds();
    if(r.contains(p))
    selectedLabel = labels[i];
    offsetP.x = p.x - r.x;
    offsetP.y = p.y - r.y;
    dragging = true;
    break;
    public void mouseReleased(MouseEvent e)
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if(dragging)
    Rectangle r = selectedLabel.getBounds();
    r.x = e.getX() - offsetP.x;
    r.y = e.getY() - offsetP.y;
    selectedLabel.setBounds(r.x, r.y, r.width, r.height);
    determineCenterOfComponents();
    repaint();
    private void addLabels()
    label1 = new JLabel("Label 1");
    label2 = new JLabel("Label 2");
    label3 = new JLabel("Label 3");
    label4 = new JLabel("Label 4");
    labels = new JLabel[] {
    label1, label2, label3, label4
    for(int i = 0; i < labels.length; i++)
    labels[i].setHorizontalAlignment(SwingConstants.CENTER);
    labels[i].setBorder(BorderFactory.createEtchedBorder());
    add(labels[i]);

    If you need some help, be respectful of the forum rules and people will help. By using "urgent" in the title and bumping your message every 2 hours you're just asking to be ignored (which is what you ended up with).

  • Help with java swing

    Hi people!i need some help
    Im a new user for java programming language.Well im programming an application using java swing libraries. I have some problems trying to accesing variables from those swing Jpanels. Ill make it clear....
    Im using Netbeans...
    I have a class for the window (a JFrame) including 2 Jtextfields and 2 Jlabels
    import .......
    public class myclass extends javax.swing.JFrame{
    public double gp;
    public double gv;
    public G() {
    initComponents();
    gpnom=this.gpnom;
    gvnom=this.gvnom;
    private void TXFgpnom(java.awt.event.ActionEvent evt) {        //TXField                                
    gpnom= Double.parseDouble(TXFgpnom.getText());
    gvnom= Double.parseDouble(TXFgvnom.getText());
    .......//theres a lot of more code .for listeners..next...
    Now ive created a new file (a new class)in the same package ,but i cant access public variables from swing class
    //the next class was created in a new file
    public class hi () {
    JPanel prin =(JPanel) new myclass().getContentPane(); //ok
    double number=gpnom // error variable not found
    When i try to get the value of "number" ...i always get "ERROR" And the class for that textfield was public..i think...
    HOw can i use variables from that Jpanel?
    Id appreciate an answer...
    thanx for your help!
    Paco

    In future Swing related questions should be posted in the Swing forum and camickr will be more likely to answer if you have used code tags to properly format your code.
    Luckily this problem does not seem to be Swing related in the least because the public variables you have in your other class are named gp and gv and further when you access public variables (or properties) of a class you must access them by an instance of that class. Which you don't appear to be doing either.

  • Help needed in swing

    HI friends,
    I have a GUI with 4 paem nels .On one panel ..i have a menu item
    called "Create" when i click it an oval will be drawn on a canvas.
    And i have the Buttons on the other panel .
    I need to drag these buttons and drop them into the ovals.
    Can any one help me wih the drag and drop functionality using swing.
    Thanks in avance

    Did you know there is a Swing forum where you can post Swing questions?
    http://forum.java.sun.com/forum.jspa?forumID=57
    If you do repost this there, please put a link in this thread to direct interested people to the new post.
    I don't know anything about how to do drag-and-drop in Swing, so I can't help you directly with that. Good luck!

  • HELP!! SWING SHOPPING CART ADVICE!!!

    Hi everyone,
    I have just come across this site and i think its really good and helpful. Just a quick question:
    How would you make a shopping cart using java swing?
    advice would be appreciated as im stuck at the moment.
    Thanks

    SIR_KRAZIE wrote:
    I NEED TO DEVELOP SOFTWARE FOR A SANDWICH SHOP. IT IS SIMILER TO A SHOPPING CART BECAUSE YOU WILL NEED TO ADD AND REMOVE ITEMS. THIS IS WHY IM AM TRYING TO FIND OUT HOW TO MAKE A SHOPPING CART IN SWING.
    MY ADVICE TO YOU WOULD BE TO START WRITING CODE.  THAT'S HOW TO MAKE ANYTHING IN JAVA.  COME BACK AND ASK SPECIFIC QUESTIONS WHEN YOU HIT SNAGS.  BUT THIS IS NOT THE APPROPRIATE PLACE FOR "I HAVE NO IDEA WHAT TO DO", OPEN-ENDED QUESTIONS.
    And please take the caps lock off. It looks like you're shouting. It's bad enough to be ignorant, but rude, too?
    I'd recommend that you read this:
    http://catb.org/~esr/faqs/smart-questions.html
    %

  • Whyte board painting in Swing?

    Hi everyone,
    I have an application to which I'd like to attach a home made Java "whyte board". In this a user may drag his mouse to form letters, figures or whatever. I.e. I want the "whyte board JPanel" to paint out the exact movement of the mouse only when the left button of it is pressed.
    Has anyone seen this kind of application anywhere (with open source code) or do I have to develop it from scratch? If I have to, then does anyone have a good tip of where to look to find how to catch the mouses movement (when left button is pressed), cause I can't find any good sources...
    Hope you can help!
    / jez

    Thank you all for your help! And yes with the mouselistener and all, it should work, but some work must be done.
    Reply to "ashwin0007", thanx for the tip, and yes cooperation is always welcome. May E-mail is is "[email protected]" case it is not visible here. I'm getting to "work" this weekend, so we might get somewhere.
    See ya!
    / jez

  • Help needed with swings for socket Programming

    Im working on a Project for my MScIT on Distributed Computing...which involves socket programming(UDP)....im working on some algorithms like Token Ring, Message Passing interface, Byzantine, Clock Syncronisation...i hav almost finished working on these algorithms...but now i wanna give a good look to my programs..using swings but im very new to swings...so can anyone help me with some examples involving swings with socket programming...any reference...any help would be appreciated...please help im running out of time..
    thanking u in advance
    anDy

    hi im Anand(AnDY),
    i hav lost my AnDY account..plz reply to this topic keeping me in mind :p

Maybe you are looking for