Ahmed
Ahmed

Reputation: 49

Java Graphics(Drawing a line)

I'm not familiar with the java Graphics, and I want to draw a line over 3 buttons. I found some ways to draw a line, but none of them draws it on top of the buttons.

Here's my GUI class

public class GUI extends JFrame{
JButton[] buttons;

GUI()
{
    setSize(255, 390);
    setLocation(0, 0);      
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(null);
    setVisible(true);       
}
public void paint(Graphics g) {
    super.paint(g);
    //TODO add the line    
}
void drawButtons()
{
    buttons=new JButton[9];
    int x=5,y=80;
    for(int i=0;i<buttons.length;i++)
    {
        buttons[i]=new JButton("");
        buttons[i].setSize(70,70);
        buttons[i].setLocation(x,y);
        buttons[i].setFont(new Font("Arial", Font.PLAIN, 45));
        buttons[i].setBorder(BorderFactory.createBevelBorder(1,Color.black,Color.black));
        y+=(i%3==2)?75:0;
        x=(i%3==2)?5:x+75;          
        add(buttons[i]);
    }
}

}

So simply, I want to create a function that creates a line, and gets the location of the line as a parameter. And I want the line to be on top of the buttons. How can I do that? Thanks in advance.

Upvotes: 0

Views: 300

Answers (2)

copeg
copeg

Reputation: 8348

And I want the line to be on top of the buttons.

Consider using the Glass pane to do the custom drawing, overriding its paintComponent method to do the draw on top of the JFrame. For example:

public class CustomGlassPane extends JPanel{

    public CustomGlassPane(){
        setOpaque(false);
    }

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.drawLine(10, 100, 2000, 100);
    }
}

You would then set the Glass pane of the JFrame

setGlassPane(new CustomGlassPane());
getGlassPane().setVisible(true);

As an aside, I would also recommend against using null layouts - select the LayoutManager that best suits your layout (and note that you can nest layouts). I would also recommend overriding paintComponent rather than paint (as your posted code attempts to do).

Upvotes: 2

camickr
camickr

Reputation: 324197

Take a look at the section from the Swing tutorial on A Closer Look at the Painting Mechanism.

As you can see a JPanel will invoke a paintChildren(...) method. So you could override this method to paint your line on top of the children of the panel:

@Override
protected void paintChildren(Graphics g)
{
    super.paintChildren(g);

    // paint the line here
}

Proably the better option is to use a JLayer which is designed specifically for this. Read the section from the Swing tutorial on Decorating Components With JLayer for more information and examples.

Upvotes: 2

Related Questions