Ahmed Ahmed - 1 month ago 23
Java Question

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.

Answer

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).