2

i'm trying to draw a line in a java program but the line has not drawn

i have try every function but still no line on JLable

i don't know why the graphics of JLable does not updated after i draw my line and it's still empty.

help me please

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class t
{
private static JFrame frame;
private static JLabel field;

public static void main(String[] args)
{
    frame = new JFrame("Simple Server");
    frame.setLayout(new FlowLayout());

    frame.setPreferredSize(new Dimension(1200, 700));
    frame.setSize(new Dimension(1200, 700));
    frame.setMinimumSize(new Dimension(1200, 700));

    frame.addWindowListener(new WindowAdapter()
    {
        @Override
        public void windowClosing(WindowEvent we)
        {
            System.gc();
            System.exit(0);
        }
    });

    int maxW = 1000, maxH = 600;
    field = new JLabel();
    field.setSize(maxW, maxH);
    field.setPreferredSize(new Dimension(maxW, maxH));
    field.setMaximumSize(new Dimension(maxW, maxH));
    field.setMinimumSize(new Dimension(maxW, maxH));

    field.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
    field.setBackground(Color.GREEN);
    field.setOpaque(true);

    frame.add(field, BorderLayout.CENTER);

    frame.pack();
    frame.setVisible(true);

    Graphics g = field.getGraphics();
    g.drawLine(0, 0, 100, 100);

    field.paintComponents(g);
    field.paint(g);
    field.paintAll(g);
    field.update(g);
    field.repaint();

    frame.paint(g);
    frame.paintAll(g);
    frame.paintComponents(g);
    frame.update(g);
    frame.repaint();
    frame.setVisible(true);
}
kiheru
  • 6,588
  • 25
  • 31
strings95
  • 661
  • 11
  • 26
  • Why impose the arbitrary "no-inheritance" restriction on yourself, out of curiosity? Because drawing with Swing is easily done by extending JLabel and overriding the `paintComponent(Graphics g)` method – Kon Jul 21 '13 at 07:05
  • actually is a part of my project. i search in internet and i saw every program override the paintComponent but i should try to use this way – strings95 Jul 21 '13 at 07:08
  • Wrap your swing code with `SwingUtilities.invokeLater()`. Swing is not thread safe and modifying the components outside the event dispatch thread can lead to hard to debug problems. As for the problem, everybody overrides `paintComponent()` because it is the correct way. – kiheru Jul 21 '13 at 07:10
  • well in this way how can i move for example a circle on screen? because this program is going to be such an animation :) – strings95 Jul 21 '13 at 07:14
  • Also, take a look at [JFrame#setDefaultCloseOperation](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation(int)) and [Initial Threads](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html). While I would agree that success is often found in the opposite direction of the normal, there are reasons things are done a certain way – MadProgrammer Jul 21 '13 at 07:16
  • For drawing on top of all components, use a glass pane. http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html – kiheru Jul 21 '13 at 07:16
  • @user2603656 : Please have a look at the last link, on the [info](http://stackoverflow.com/tags/swing/info) page of `Swing` tag :-) – nIcE cOw Jul 21 '13 at 07:57
  • Here is an [SSCCE of dynamically changing an image](http://stackoverflow.com/a/10055306/418556), & [another one](http://stackoverflow.com/a/10628553/418556) & [another one](http://stackoverflow.com/a/11330719/418556).. – Andrew Thompson Jul 21 '13 at 08:26
  • @user2603656 : One very simple [example](http://stackoverflow.com/a/17573406/1057230) – nIcE cOw Jul 21 '13 at 08:35

3 Answers3

2

getGraphics can return null and is, at best, a snapshot of what was painted on the last paint cycle.

While you can use this technique, the next time the component needs to be painted, anything you've painted to it will be erased.

Take a look at Perofrming Custom Painting and Painting in AWT and Swing for more details about how painting works

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

To be swing graphics conformant, do this:

public class CrossedLabel extends JLabel {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawLine(0, 0, 100, 100);
    }
}
tbodt
  • 16,609
  • 6
  • 58
  • 83
  • but how can i make it dynamic?? i means how can i define a function that every time i call it, it draw a line for example?? – strings95 Jul 21 '13 at 07:42
  • That isn't possible if you want to stay within the bounds of the reasonable. If you want to draw the line differently each time, alter some flags by calling methods. – tbodt Jul 21 '13 at 07:43
  • Not with the new swing graphics manipulation. You should never reasonably call `getGraphics on a swing component unless you have a good reason/ – tbodt Jul 21 '13 at 07:48
  • so how can i program an animation? for example a moving circle – strings95 Jul 21 '13 at 07:49
  • That is something totally different and is best left to a separate question. I'll answer it if you give me the link. – tbodt Jul 21 '13 at 07:50
  • http://stackoverflow.com/questions/17770249/dynamic-graphic-programming-in-java-animation – strings95 Jul 21 '13 at 07:57
  • @tbodt : Just a side note, while overriding the method of the super class, try to keep the access specifier, the same as much as possible. Here it is `protected` for `paintComponent(...)` and not `public` +1 for the rest :-) – nIcE cOw Jul 21 '13 at 08:00
0

Use an infinite while loop and within add the line "g.drawLine(0,0,100,100);" alone and then end the main function. Then a line is visible on screen. Similarly you can use a loop to play an animation until a condition is completed to make it work.

The code should be like this below one :-

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class t implements Runnable
{
private static JFrame frame;
private static JLabel field;
private java.lang.Thread tdr;
t()
{
 tdr = new java.lang.Thread(this);
}

public static void main(String[] args)
{
    t tsk= new t();
    frame = new JFrame("Simple Server");
    frame.setLayout(new FlowLayout());

    frame.setPreferredSize(new Dimension(1200, 700));
    frame.setSize(new Dimension(1200, 700));
    frame.setMinimumSize(new Dimension(1200, 700));

    frame.addWindowListener(new WindowAdapter()
    {
        @Override
        public void windowClosing(WindowEvent we)
        {
            System.gc();
            System.exit(0);
        }
    });

    int maxW = 1000, maxH = 600;
    field = new JLabel();
    field.setSize(maxW, maxH);
    field.setPreferredSize(new Dimension(maxW, maxH));
    field.setMaximumSize(new Dimension(maxW, maxH));
    field.setMinimumSize(new Dimension(maxW, maxH));

    field.setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
    field.setBackground(Color.GREEN);
    field.setOpaque(true);

    frame.add(field, BorderLayout.CENTER);

    frame.pack();
    frame.setVisible(true);
    Graphics g = field.getGraphics();
 while(true)
 {
    g.drawLine(0, 0, 100, 100);
 try{

    tsk.tdr.sleep(1000);
 }
 catch ( Exception e)
 {
     System.out.println(e.getMessage());
 }
  System.out.println("Thread started");
}
}

    @Override
    public void run() {
       tdr.start();
    }
}

Similarly use some other condition in the while loop instead of true, which would meet until the animation like moving a circle form point a to b is finished.

  • 2
    Many a things are wrong/old style in this code snippet. Setting sizes manually is discouraged, since Layout concern can calculate that. This code basically resembles an AWT design. Do not add WindowListener to the JFrame, when he same can be achieved by using `frameReference.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)` – nIcE cOw Jul 21 '13 at 08:39
  • Please run through this [thread](http://stackoverflow.com/q/10338163/1057230), before suggesting this approach. – nIcE cOw Jul 21 '13 at 08:45
  • 1
    This could potentially block the event dispatching, causing the program to hang. This not how painting is done in Swing – MadProgrammer Jul 21 '13 at 09:05