I'm having trouble with a implementing a gridlayout. For some reason all of my MyJButtons squash up into the top left corner of my GUI. Oddly enough button clicks are still being detected in the lower right and are returning seemingly correct x and y values. I have no idea why this is happenening and any help will be much appreciated.
The reason I've extended the JButton class is so that an x and y value can be returned to assist in locating the button in a 2d array.
This is a screen shot of the afflicted GUI

This is code for the GUI
GuiDriver.java
public class GuiDriver
{
public static void main(String[] args)
{
TestGui gui = new TestGui();
}
}
MyJButton.java
import javax.swing.JButton;
public class MyJButton extends JButton {
private int x;
private int y;
public MyJButton(int x, int y) {
super(x+","+y); //set name as co-ordinates
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
TestGui.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TestGui extends JFrame
{
JPanel basePanel = new JPanel();
MyJButton[][] button = new MyJButton[9][9];
public TestGui()
{
basePanel.setLayout(new GridLayout(9, 9));
for (int x = 0; x < 9; x++)
{
for (int y = 0; y < 9; y++)
{
button[x][y] = new MyJButton(x,y);
button[x][y].addMouseListener(new MyButtonListener());
basePanel.add(button[x][y]);
}
}
add(basePanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
class MyButtonListener implements MouseListener {
public void mouseClicked(MouseEvent e)
{
Object obj = e.getSource();
if (obj instanceof MyJButton)
{
MyJButton clicked = (MyJButton) obj;
if (e.getButton() == 1)
{
System.out.println(clicked.getX()+","+clicked.getY()+":left");
}
else if (e.getButton() == 3)
{
System.out.println(clicked.getX()+","+clicked.getY()+":right");
}
}
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
}
}
This post has been edited by kezkankrayon: 16 September 2009 - 02:42 PM

New Topic/Question
Reply




MultiQuote




|