How do I use two drawing methods in java? Or outside the main paint method

How can I create two drawing methods? When I try to use two drawing methods, they never work. If this is not possible, I want to draw outside of the main drawing method and I have no idea how to do it. For example:

public class test extends JFrame {

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                test frame = new test();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public void paint(Graphics g) {
    g.fillRect(100, 100, 100, 100);
}

public void pp(Graphics g) {
    g.fillRect(250, 100, 100, 100);
}

/**
 * Create the frame.
 */
public test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);
}

}

      

+3


source to share


2 answers


I found a way.

public void paint(Graphics g) { super.paint(g); draw(g); draw2(g); }



public void draw(Graphics g){
    g.fillRect(100, 100, 100, 100);
}

public void draw2(Graphics g){
    g.setColor(Color.blue);
    g.fillRect(200, 100, 100, 100);
}

      

+1


source


When I try to use two drawing methods, they never work.

paintComponent(...)

is not a JFrame method. Whenever you try to override a method, you must use annotation @Override

and the compiler will tell you when you try to override a method that doesn't exist.



In general, for other Swing components, a method paint(...)

is responsible for calling a method paintComponent(...)

, so you shouldn't override a method paint()

. See a more detailed look at the paint engine for more information.

You should NOT override paint () on JFrame anyway. Read the entire section on Performing Custom Painting

from the tutorial link for a working example of how regular painting should be done.

+5


source







All Articles