Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to draw grid using swing class Java and detect mouse position when click and drag
    primarykey
    data
    text
    <p>I am trying to create a grid UI (5*5) using Swing classes. I tried a nested loop and adding a jPanel dynamically to the jFrame. And I also tried to change the background colour of each jPanel when user clicks and drops over it. But with my code there are huge gaps between each cell and I can't get the drag event to work.</p> <pre><code>public class clsCanvasPanel extends JPanel { private static final int intRows = 5; private static final int intCols = 5; private List&lt;JPanel&gt; jpllist = new ArrayList&lt;JPanel&gt;(); public clsCanvasPanel() { /* * * Add eventListener to individual JPanel within CanvasPanel * * * TODO : * 1) mousePressed --&gt; update Temperature and HeatConstant of clsElement Class * 2) start a new thread and * 3) call clsElement.run() method * * * Right Now : it updates the colours of the JPanel * */ MouseListener mouseListener = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { JPanel panel = (JPanel) e.getSource(); Component[] components = panel.getComponents(); for (Component component : components) { component.setVisible(!component.isVisible()); component.setBackground(new Color(255,255,0)); } panel.revalidate(); panel.repaint(); } }; //TODO : refactoring GridLayout gdlyPlates = new GridLayout(); gdlyPlates.setColumns(intCols); gdlyPlates.setRows(intRows); gdlyPlates.setHgap(0); gdlyPlates.setVgap(0); setLayout(gdlyPlates); //TODO : refactoring for (int row = 0; row &lt; intRows; row++) { for (int col = 0; col &lt; intCols; col++) { JPanel panel = new JPanel(new GridBagLayout()); panel.setOpaque(false); JPanel jl = new JPanel(); jl.setVisible(true); panel.add(jl); panel.addMouseListener(mouseListener); jpllist.add(panel); add(panel); } } } } </code></pre> <p>So now I am trying to create one panel and draw grids on it, then detects the mouse position on the grid, further change the colour of each cell.</p> <p>Could someone give me some advices on how to implement this grid on JPanel, and change the colour of a chosen cell.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload