Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Graphics drawing lines

Andrew Robertson
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, i have some code, i am not sure what i am doing wrong, but i cannot get the lines to paint on the box and/or display!,

package javaapplication16;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class JavaApplication16{
    private static JFrame MainFrame;
    private static JPanel CanvasPanel;
    private static int  LayoutTextPaddedHeight = 35, LayoutTextSize = 14, LayoutFontStyle = 1;
    private static JButton DoLineButton;
    private static JLabel LabelX1,LabelY1,LabelX2,LabelY2;
    private static JTextField FieldX1,FieldY1,FieldX2,FieldY2;
    private static Box ButtonBox =  Box.createHorizontalBox();
    public static void JavaApplication16(){
        MainFrame = new JFrame("Main Frame");
        MainFrame.setPreferredSize(new Dimension(700,700));
        CanvasPanel = new JPanel();
        LabelX1 = new JLabel("X1:-", SwingConstants.RIGHT);
        FieldX1 = new JTextField(5);
        LabelY1 = new JLabel("Y1:-", SwingConstants.RIGHT);
        FieldY1 = new JTextField(5);
        LabelX2 = new JLabel("X2:-", SwingConstants.RIGHT);
        FieldX2 = new JTextField(5);
        LabelY2 = new JLabel("Y2:-", SwingConstants.RIGHT);
        FieldY2 = new JTextField(5);
        DoLineButton = new JButton("Add Curved Track");
        DoLineButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
        mypanel = new MyPanel();
    public static void main(String[] args) {
        try{ UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); } //UIManager.setLookAndFeel("");
        catch(UnsupportedLookAndFeelException | IllegalAccessException | InstantiationException | ClassNotFoundException ex){ ex.printStackTrace(); }
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        javax.swing.SwingUtilities.invokeLater(new Runnable(){ public void run(){ JavaApplication16(); } });

    private static JPanel mypanel;
    private static Graphics MyGraphics;
    public static class MyPanel extends JPanel {
        MyPanel() {
            setMinimumSize(new Dimension(500,500));
            setPreferredSize(new Dimension(500,500));
            setMaximumSize(new Dimension(500,500));
        public void paintComponent(Graphics g) {
            MyGraphics = g;
            MyGraphics = g;
            MyGraphics.drawString("BLAH", 20, 20);
            MyGraphics.drawRect(200, 200, 200, 200);
            MyGraphics.drawLine(100, 100, 200, 200);
        public static void drawLine2(int X1, int Y1, int X2, int Y2) {
            MyGraphics.drawLine(X1, Y1, X2, Y2);

thanks all
Piet Souris
Posts: 1694
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Andrew,

welcome to codeRanch!

To be honest: your program is a nightmare come true. There is very much to be commented on.

First of all: your code is not JavaFX, just plain old Java SE.

Second: use code tags! Copy your code into the reply box, select all of your code and then press the "Code" button above it.

Third: it is remarkable that your code is running at all. For instance: in your "invokeLater" you just call "JavaApplication16();" where one would normally expect "new JavaApplication16();".
It took me a moment to find out why this works. Well, "JavaApplication16()" is a normal method, and it does not call any JavaApplication16 - constructor. (try to see why this is not a constructor call).

So, let me first concentrate on getting your code to run as it should (well, more on that later!).

Here is a slightly adjusted version, that will draw your line after pressing the button. See my comments after this code:

In line 65, I changed the "private static JPanel mypanel;" to "private static MyPanel mypanel;"
in "drawLine2" I removed MyGraphics, to be replaced by a simple Graphics g. And I made it a non-static method.
I fixed a small error in your ActionListener-code, where the last "Integer.parseInt" takes X2 instead of Y2.

Well, it sort of runs now, try it. But then, try to resize your frame, by dragging one of its borders. The extra line will vanish.

So far for this time.
Andrew Robertson
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Piet,
Thanks for the reply, I did some work with java around 14 years ago, but not much since, as i have been working in other programming languages, so I am a little rusty on it, and never worked with this sort of graphics. The real code file that the code came from is 425 lines long, and that is just one file, at a guess i'd say the program has around 16 files(in two weeks), and expected to double within the next two weeks, total lines, around 20k. I slapped this together to get the question across!, as attempting to explain the problem would be a real nightmare!.
I wasn't aware of the code tags but will use from now on!, I managed to template what you've done, and make my main program work as wanted!.

Funny enough no where on the web could i find a java graphics that could do this, which is thus a question first!.

The extra line disappears as it probably needs a call to repaint or re-validate.

thanks Heaps
Piet Souris
Posts: 1694
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Andrew,

well, thank you for your reaction! For  a replier it is always a big reward to get such enthousiatic feed back.

So, if I understand you well, this is only a part of some very big application-to-be. Therefore, let me give some general advices.

1) try to follow tha Java naming conventions. Variable names and method names start with lowercase letters, class names with uppercase letters, and there is camelCasing. For instance: BufferedImage thisIsAnImage = ImageIO....

2) make all variables non static (i.e. delete all those " static" words (except from your main - routine, of course!), and make them private

3) your "public static void JavaApplication16()" then becomes: "public JavaApplication16()" and becomes a genuine constructor!

4) in your "invokeLater" method, you do then need a "new JavaApplication16()" (as I was expecting in the first place   )

5) drop the variable "MyGraphics", and replace them simply by the "g" parameter.

6) the new lines disappear as soon as you drag a frame border around. That is because in your "paintComponent(Graphics g)" (in the MyPanel class) those added lines are not drawn. To remedy this, I would suggest to add a Line2D List to your MyPanel class (so, like "List<Line2D>", and every time the "doLineButton" is pressed, create a new line and add it to the list. In your paintComponent - method, draw all these lines. Note that you need a Graphics2D object for this, but look at the API of a Graphics(2D) to see how to get one easily.

And of course: if you have this 20K line app, don't hesitate to give a demo! Looking forward to this!

Success, and send in any other question you have. There is a huge expertise at the ranch.

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!