I have got a strange problem with displaying components in JFrame.
I have to write my own GUI engine (buttons, textboxes, etc...) without using Swing. Only JFrame/JPanel is allowed to be used.
Let's say I want to place 3 buttons.
My button class:
public class Button extends JPanel implements MouseListener {
Rectangle r = new Rectangle();
String text;
int X,Y,W,H;
public Button(int x, int y, int w, int h, String t)
{
X=x;
Y=y;
W=w;
H=h;
this.setBackground(Color.CYAN);
addMouseListener(this);
r.setSize(w, h);
r.setLocation(x, y);
this.text = t;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.draw(r);
g2d.drawString(text, X+W/2, Y+H/2);
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
if((arg0.getButton()==1) && r.contains(arg0.getPoint()))
System.out.println(arg0.getPoint().toString());
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
And in main class I create a JFrame and JPanel. I add to JPanel 3 buttons, and finally JPanel to JFrame, but only the last declared button shows up.
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame f = new JFrame("Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.cyan);
JPanel j = new JPanel(new BorderLayout());
j.add(new Button(10,10,100,50,"text"));
j.add(new Button(10,100,100,50,"text2"));
j.add(new Button(300,10,100,50,"text3"));
f.add(j);
f.pack();
f.setSize(640, 400);;
f.setVisible(true);
}
What am I doing wrong?