How to do different drawings in different methods using paintComponent?

I have 2 classes, one which extends a panel and other which extends a frame.

First class, the panel(used for drawings):

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class GraficPne extends JPanel{


public int dim1 = 0, dim2 = 0;
public JLabel lblSem1GraficPne, lblSem2GraficPne;

public GraficPne(){
    super();
    this.setLayout(null);
    this.setupComponents();

}


public void setupComponents(){

    lblSem1GraficPne = new JLabel("Sem I");
    lblSem2GraficPne = new JLabel("Sem II");

    lblSem1GraficPne.setFont(new Font("Serif", Font.PLAIN, 12));
    lblSem2GraficPne.setFont(new Font("Serif", Font.PLAIN, 12));

    this.add(lblSem1GraficPne);
    this.add(lblSem2GraficPne);
}

public void layComponents(int firstConv, int secondConv){

    lblSem1GraficPne.setBounds(20, getHeight() - firstConv - 20, 100, 20);
    lblSem2GraficPne.setBounds(100, getHeight() - secondConv - 20, 100, 20);

}



public void paint(Graphics g){

    super.paint(g);

    g.setColor(Color.BLACK);
    g.drawRect(0, 0, getWidth()-1, getHeight()-1);

    this.setBackground(Color.GREEN);

    g.setColor(Color.RED);
    g.fillRect(20, getHeight()-dim1, 40, dim1);

    g.setColor(Color.BLUE);
    g.fillRect(100, getHeight()-dim2, 40, dim2);

    }



public void setData(int dim1, int dim2){

    this.dim1 = dim1;
    this.dim2 = dim2;

}

}

Second class, the frame, used to add the panel on it:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;


public class GraficFrm extends JFrame implements ActionListener{

private JButton btnApply;
private JLabel lblSem1, lblSem2;
private JTextField txtSem1, txtSem2;
private GraficPne ob; //the object from first class
private int firstConv = 0, secondConv = 0; 


public GraficFrm() {

    super("Grafic soft");
    initSettings();
    setupComponents();
}



private void initSettings() {

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(null);
    this.setSize(400, 450);
    this.setLocation(100, 100);
    this.setResizable(false);

}


private void setupComponents() {


    ob = new GraficPne();
    lblSem1 = new JLabel("Sem I");
    txtSem1 = new JTextField();
    lblSem2 = new JLabel("Sem II");
    txtSem2 = new JTextField();
    btnApply = new JButton("Apply");

    ob.setBounds(30, 50, 340, 200);
    lblSem1.setBounds(30, 280, 100, 20);
    txtSem1.setBounds(150, 280, 220, 20);
    lblSem2.setBounds(30, 330, 100, 20);
    txtSem2.setBounds(150, 330, 220, 20);
    btnApply.setBounds(170, 380, 80, 30);

    this.add(lblSem1);
    this.add(ob);
    this.add(txtSem1);
    this.add(lblSem2);
    this.add(txtSem2);
    this.add(btnApply);

    btnApply.addActionListener(this);

}


public void getConvertedValues(){

    String txtField1 = txtSem1.getText();
    firstConv = Integer.parseInt(txtField1);
    String txtField2 = txtSem2.getText();
    secondConv = Integer.parseInt(txtField2);

}


public void getHighValues(){

    if((firstConv > 100) || (secondConv > 100)) {

        JOptionPane.showMessageDialog(this, "Only values < 100 are allowed");

        firstConv = 0;
        secondConv = 0;
        txtSem1.setText("");
        txtSem2.setText("");
        ob.removeAll();
        ob.repaint();
    }

}



public void actionPerformed(ActionEvent e) {


    if(e.getSource().equals(btnApply)){

        try{

        new GraficFrm();
        getConvertedValues();
        getHighValues();
        ob.setData(firstConv, secondConv);
        ob.layComponents(firstConv,secondConv);
        ob.repaint();

        }catch(NumberFormatException ex1){
            JOptionPane.showMessageDialog(this, "Only natural numbers are allowed");
        }

    }

}

public static void main(String[] args) {

    GraficFrm frm = new GraficFrm();
    frm.setVisible(true);
}

}

All I want to do is to create a new method called getNegativeValues(), which would be called by pressing the Apply button, and this method to be executed when firstConv or secondConv would be < than 0. The block of my method, getNegativeValues(), i want to keep only the green background of the panel, as it is in paint(Graphics g), but to draw a center horizontal line(g.drawLine(0, getHeight()/2, getWidth(), getHeight()/2);). Then, when i execute the program and i type, let's say the value 55 for the first textfield and -40 for the second one, to draw 55 over my center horizontal line and -40 under my center horizontal line, and the 0 point would be on this center horizontal line.

LE: @nIcE cOw i'll make a short recap: So, first, when i execute my app, i just want to appear my green panel and those 2 labels which have 2 textfields, as in my example(try to follow my example, please)(all good, i already did this, so this part is done). After, when i complete those 2 textfields let's say with 2 positive values, and then when i press the Apply button to happen exactly like in my example(without any center vertical line)(so already did this, also). All good, but my problem is: If complete one of those 2 textfields with a negative value and other with a positive one, and after i press the Apply button, i want that my application to recognize that there is a negative value typped in one of my textfields, thus to draw me on my green panel a center horizontal line(after i press the Apply button) and to draw those 2 rectangles exactly as you did in your first picture uploaded. Please help me, as i said i'll help you to understand what i want to do, and also i want to say i really appreciate your effort and i'm sorry (again) if i was confused(again).

Answers


I guess, what you looking for is a method as presented below, that might can calculate, the starting point of Rectangles that you are trying to draw on the JPanel. Here pos is Positive Value and neg is Negative Value :

public void setValues(int above, int below)
{
    midPoint = getHeight() / 2;
    heightAbove = Math.abs(above);
    heightBelow = Math.abs(below);
    /*
     * If both are negative values, 
     * we need a Mid-Point in this case.
     */
    if (above < 0 && below < 0)
    {
        rectAbove = midPoint;
        diff = 120;
        rectBelow = midPoint;
        flag = true;
    }
    else if (above >= 0 && below >= 0)
    {
        rectAbove = getHeight() - heightAbove;
        diff = 120;
        rectBelow = getHeight() - heightBelow;
        flag = false;
    }
    else if (above < 0 && below >= 0)
    {
        rectAbove = midPoint;
        diff = 40;
        rectBelow = midPoint - heightBelow;
        flag = true;
    }
    else if (above >= 0 && below < 0)
    {
        rectAbove = midPoint - heightAbove;
        diff = 40;
        rectBelow = midPoint;
        flag = true;
    }       

    repaint();
}

Here is the code :

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

public class PaintingRectangles
{
    private JTextField aboveField;
    private JTextField belowField;
    private JButton applyButton;
    private MyCanvas canvas;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Painting Rectangles Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(5, 5));

        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new GridLayout(3, 1, 5, 5));
        aboveField = new JTextField(10);
        belowField = new JTextField(10);
        applyButton = new JButton("Apply");
        applyButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                int above = 0;              
                int below = 0;
                try
                {
                    above = Integer.parseInt(aboveField.getText());
                    below = Integer.parseInt(belowField.getText());
                }
                catch(NumberFormatException nfe)
                {
                    aboveField.setText("0");
                    belowField.setText("0");
                    above = 0;
                    below = 0;
                    nfe.printStackTrace();
                }

                canvas.setValues(above, below);
            }
        });

        rightPanel.add(aboveField);
        rightPanel.add(belowField);
        rightPanel.add(applyButton);

        canvas = new MyCanvas();
        contentPane.add(canvas, BorderLayout.CENTER);
        contentPane.add(rightPanel, BorderLayout.LINE_END);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new PaintingRectangles().displayGUI();
            }
        });
    }
}

class MyCanvas extends JPanel
{   
    private int midPoint = getHeight() / 2;
    private int rectAbove = getHeight() / 2;
    private int rectBelow = getHeight() / 2;    
    private int width = 40;
    private int heightAbove = 0;
    private int heightBelow = 0;
    private int diff = 0;
    private boolean flag = false;

    public MyCanvas()
    {
        setBackground(Color.GREEN);
    }

    public void setValues(int above, int below)
    {
        midPoint = getHeight() / 2;
        heightAbove = Math.abs(above);
        heightBelow = Math.abs(below);
        /*
         * If both are negative values, 
         * we need a Mid-Point in this case.
         */
        if (above < 0 && below < 0)
        {
            rectAbove = midPoint;
            diff = 120;
            rectBelow = midPoint;
            flag = true;
        }
        else if (above >= 0 && below >= 0)
        {
            rectAbove = getHeight() - heightAbove;
            diff = 120;
            rectBelow = getHeight() - heightBelow;
            flag = false;
        }
        else if (above < 0 && below >= 0)
        {
            rectAbove = midPoint;
            diff = 40;
            rectBelow = midPoint - heightBelow;
            flag = true;
        }
        else if (above >= 0 && below < 0)
        {
            rectAbove = midPoint - heightAbove;
            diff = 40;
            rectBelow = midPoint;
            flag = true;
        }       

        repaint();
    }

    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(400, 400));
    }

    @Override
    protected void paintComponent(Graphics g)
    {       
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, getWidth(), getHeight());
        if (flag)
            g.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
        makeRectangles(g);
    }

    private void makeRectangles(Graphics g)
    {
        g.setColor(Color.RED);
        g.fillRect(40, rectAbove, width, heightAbove);

        g.setColor(Color.BLUE);
        g.fillRect(diff, rectBelow, width, heightBelow);

        g.dispose();
    }
}

Here is the output :

Though if you intend to do something else, please do clarify a bit more :-)


Need Your Help

On-demand audio streaming

web-services rest audio-streaming playlist liquidsoap

Has anyone come across a software that can dynamically stream an arbitrary source identified by an HTTP URL.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.