Adding a button overwriting a paintComponent
Hello, I am a first newcomer here.
I want to ask you a question.
I have a button that has an icon and an ActionListener. I want to add it to a panel GridLayout(1,1), using paintComponent cause I want to add other lines, simple move animation and such, inside also.
I use paintComponent, I add lines, rectangles, oval but when I add the button it takes up all the space and overwrites all the panel. I want to be able to animate the button itself, use its listener and in general co-exists in the panel.
I pass up my code.
Code:
public class MainPanel extends JPanel {
private static final long serialVersionUID = 1L;
protected final ImageIcon redDoorIcon = new ImageIcon(getClass().getResource("/images/RedDoor.png"));
private JButton button;
public MainPanel(Controller controller) {
setLayout(new GridLayout(1, 1));
button = new JButton("press me");
// button.setVisible(false);
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("*");
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(10, 10, 30, 10);
redDoorIcon.paintIcon(this, g, 50, 50);
// add(button);
}
}
The main is irrelavant as it just creates the frame and adds the panel inside.
If I don't add the button, the panel is the way I want. But I can't add it just like the other, giving it a x,j (width,height).
How can this be done?
Thank you.
Re: Adding a button overwriting a paintComponent
Moved from New to Java.
db
Re: Adding a button overwriting a paintComponent
Re: Adding a button overwriting a paintComponent
Yes db, I made it through the links.
Although I was looking at the layout managers and overwrite paint/paintComponent, how could I figure that if I don't put a LayoutManager at all I could do exactly what I want? I'd never imagine or find it out, thanks a lot for showing that to me.
For anyone else interested, check db's link and especially
Doing Without a Layout Manager (Absolute Positioning) (The Java™ Tutorials > Creating a GUI With JFC/Swing > Laying Out Components Within a Container)