1

I need help with this code. My g.drawLine(0,0,300,300) is not working. It was working until monday, I don't know what is going wrong. I use the g.drawLine(0,0,300,300) in order to test before using the plota_pixel() method. g.drawLine(0,0,300,300) shoud print a line from (0,0) to (300,300) on the Jpanel panel

MainView Class:

package alexandre.VIEW;

import java.awt.Color;

import java.awt.Graphics;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class MainView {

private JFrame janela;
public JPanel panel;


public MainView()
{
    janela = new JFrame("Exercicio 15/09");
    janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel = new JPanel();
    this.ShowView();
}

public void ShowView()
{
    janela.pack();
    janela.setSize(750,600);
    janela.setLayout(null);
    janela.add(panel);
    panel.setBounds(0,0,710,600);


    janela.setVisible(true);
    System.out.println("OIdsazxc");
    Graphics g = panel.getGraphics();
    g.setColor(Color.BLACK);    
    g.drawLine(0,0,300,300);

}

public void plota_pixel(int x, int y)
{
    Graphics g = panel.getGraphics();
    g.drawLine(x, y, x, y);

}

}

Starter Class:

package alexandre.CONTROL;

import alexandre.VIEW.MainView;


public class Starter {

public static void main(String[] args) {

    MainView view = new MainView();     
    view.ShowView();

}

}

2 Answers2

2

Using and drawing with the Graphics object from panel.getGraphics() does not work (see below links for the "why"). You will have to override the method "paintComponent" for the the JPanel, where the input parameter is the Graphics object

(Also quick note - standard method naming has the first letter lowercase so ShowView() should be showView())

public MainView()
{
    janela = new JFrame("Exercicio 15/09");
    janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel = new JPanel() {
       @Override
       public void paintComponent(Graphics g) {
          super.paintComponent(g);
           g.setColor(Color.BLACK);                   
           g.drawLine(0,0,300,300);
       }
    };
    this.showView();
}


public void showView() {
    janela.pack();
    janela.setSize(750, 600);
    janela.setLayout(null);
    janela.add(panel);
    panel.setBounds(0, 0, 710, 600);
    panel.setVisible(true);

    janela.repaint();
}

Check out the following stack overflow question

Drawing an object using getGraphics() without extending JFrame

And this resource (it's also in the linked question)

http://docs.oracle.com/javase/tutorial/uiswing/painting/

Community
  • 1
  • 1
FriedSaucePots
  • 1,342
  • 10
  • 16
0

You should set the panel visible as the last thing in the ShowViewmethod.

public void ShowView()
{
    //your code
    janela.setVisible(true);
}
Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45