Super paint component not showing up (I have tried everything) - java

Hello guys I am currently having problems with making anything show with my paint component. I have tried numerous things that I have seen online and tried a lot of different things myself but i Just can't get it to show anything. I am trying to get my paint component to show a series of bars that move as an array being sorted using swing but i can't even get it ti show anything. Any help would be appreciated.
package proj2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
public class project2 extends JFrame
{
private JButton button1 = new JButton("Insertion");
private UpdateTextFieldThread currentThread;
private int[] array = new int[15];
private Display display;
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
if (src == button1){
insertionSort(array);
(new UpdateTextFieldThread()).execute();
}
}
}
public project2()
{
setTitle("Sorting Charts");
setSize(400,250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
for(int i=0; i<array.length;i++)
array[i]=(int) (Math.random()*100);
display=new Display();
ButtonHandler bh = new ButtonHandler();
button1.addActionListener(bh);
JPanel container = new JPanel();
container.setLayout(new GridLayout(2, 2));
container.add(button1);
JPanel masterPanel=new JPanel();
masterPanel.setLayout(new BorderLayout());
masterPanel.add(display, BorderLayout.SOUTH);
masterPanel.add(container, BorderLayout.NORTH);
setContentPane(container);
setVisible(true);
display.repaint();
}
private class Display extends JPanel {
private Color color = Color.RED;
//#Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.setColor(Color.RED);
Dimension d = getSize();
int clientWidth = d.width;
int clientHeight = d.height;
int barWidth = clientWidth / array.length;
for(int i=0;i<array.length;i++){
int x=0;
int y=15;
int linethickness=5;
int linelength=10;
g.setColor(Color.red);
g.fillRect(x, clientHeight, linelength*array[i] , linethickness);
g.setColor(Color.black);
g.drawRect(x,clientHeight, linelength*array[i], linethickness);
x+=15;
}
}
}
private class UpdateTextFieldThread extends SwingWorker<Void, Integer>
{
protected Void doInBackground()
{
display.repaint();
return null;
//should have repaint method in here somewhere
/*for (int i = 0; i < 50; i++) {
publish(i);
try {
Thread.sleep(THREAD_DELAY);
} catch (InterruptedException e) { }
}
return null;*/
}
// The parameter here is a list of all published data
// since the last call to process. We are interested
// in displaying only the latest one on the GUI.
protected void process(java.util.List<Integer> list)
{
// textfield.setText("" + list.get(list.size() - 1));
}
}
public static <T extends Comparable<T>> void insertionSort(int[] hue2)
{
for (int i = 1; i < hue2.length; i++) {
int thingToInsert = hue2[i];
int j = i - 1;
while (j >= 0 && thingToInsert<hue2[j]) {
hue2[j+1] = hue2[j];
j--;
}
hue2[j+1] = thingToInsert;
}
}
public static void main(String[]args) {
new project2();
}
}

masterPanel.add(display, BorderLayout.SOUTH);
You are adding your Display panel to the SOUTH of a BorderLayout. The SOUTH constraint will respsect the preferred height of the component. Your component has a height of 0, to there is nothing to display.
Whenever you do custom painting you also need to override the getPreferredSize() method of the component to provide the appropriate size of the component so the layout managers can do there job.

Related

Why is the MouseListner not working in my Java-JFrame project?

So I am trying to make a TicTacToe game in Java with JFrame and trying to implement a MouseListener so the player can click on the squares. I found one method on the internet but cant figure out why its not working for me. What I already did is I created a frame and draw the grid and background color. Maybe I missed something? Thanks for your time.
import java.awt.*;
import javax.swing.JFrame;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Main extends JFrame
{
public static JFrame root = new JFrame("TicTacToe");
public static void main(String[] args)
{
int[] board = {
0, 0, 0,
0, 0, 0,
0, 0, 0
};
root.getContentPane().setBackground(new Color(232,209,197));
TicTacToeCanvas Canvas = new TicTacToeCanvas(board);
root.add(Canvas);
root.setSize(915,939);
root.setVisible(true);
root.setResizable(false);
root.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
root.pack();
MouseEventClass mouseEvents = new MouseEventClass(root);
}
}
class MouseEventClass implements MouseListener{
public MouseEventClass(JFrame frame){
frame.addMouseListener(this);
}
#Override
public void mouseExited(MouseEvent e){
}
#Override
public void mouseEntered(MouseEvent e){
}
#Override
public void mousePressed(MouseEvent e){
}
#Override
public void mouseReleased(MouseEvent e){
}
#Override
public void mouseClicked(MouseEvent e){
System.out.println("Click");
}
}
}
I would advise that you add the listener to the components held by the main JPanel so you can get individual clicked components more easily. For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class TicTacToePanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final String ROW = "row";
private static final String COL = "col";
private static final Color BKGRD1 = new Color(230, 230, 230);
private static final Color BKGRD2 = new Color(180, 180, 180);
private static final Dimension CELL_SIZE = new Dimension(80, 80);
private JPanel[][] panelGrid = new JPanel[3][3];
public TicTacToePanel() {
setLayout(new GridLayout(3, 3, 1, 1));
setBackground(Color.BLACK);
setBorder(BorderFactory.createLineBorder(Color.BLACK));
MyMouse myMouse = new MyMouse();
for (int i = 0; i < panelGrid.length; i++) {
for (int j = 0; j < panelGrid[i].length; j++) {
JPanel cellPanel = new JPanel();
cellPanel.putClientProperty(ROW, i);
cellPanel.putClientProperty(COL, j);
cellPanel.setPreferredSize(CELL_SIZE);
cellPanel.setBackground(BKGRD1);
cellPanel.addMouseListener(myMouse);
add(cellPanel);
panelGrid[i][j] = cellPanel;
}
}
}
class MyMouse extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
JPanel cell = (JPanel) e.getComponent();
if (cell == null) {
return;
}
Color background = cell.getBackground().equals(BKGRD1) ? BKGRD2 : BKGRD1;
cell.setBackground(background);
int row = (int) cell.getClientProperty(ROW);
int col = (int) cell.getClientProperty(COL);
System.out.printf("cell row & column: [%d, %d]%n", row, col);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TicTacToePanel mainPanel = new TicTacToePanel();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Here, I create a 2D array of JPanels:
private JPanel[][] panelGrid = new JPanel[3][3];
and then in the main JPanel's constructor,
create individual "cell" JPanels in a nested for loop, adding them to the main JPanel
Adding my mouse listener to each individual cell.
This way, I can get each individual clicked cell cleanly and easily
public TicTacToePanel() {
// ....
// my mouse listener
MyMouse myMouse = new MyMouse();
// create cells and fill my grid with cells
for (int i = 0; i < panelGrid.length; i++) {
for (int j = 0; j < panelGrid[i].length; j++) {
JPanel cellPanel = new JPanel();
// gives each cell identifying information
cellPanel.putClientProperty(ROW, i);
cellPanel.putClientProperty(COL, j);
cellPanel.setPreferredSize(CELL_SIZE);
cellPanel.setBackground(BKGRD1);
// add the same mouse listener to all cells
cellPanel.addMouseListener(myMouse);
add(cellPanel); // add it to the main JPanel
panelGrid[i][j] = cellPanel; // and to a holding array
}
}
}
The mouse listener is simple:
class MyMouse extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
// get the cell clicked
JPanel cell = (JPanel) e.getComponent();
// make sure it's not null
if (cell == null) {
return;
}
// then do stuff to it
Color background = cell.getBackground().equals(BKGRD1) ? BKGRD2 : BKGRD1;
cell.setBackground(background);
int row = (int) cell.getClientProperty(ROW);
int col = (int) cell.getClientProperty(COL);
System.out.printf("cell row & column: [%d, %d]%n", row, col);
}
}

I cannot pull values from an array in a different class

The printout of the array lifegrid2 just gives all zeros. I tested the lifegrid array in MyPanel and that is populating, but the values are pulling through as zeros. I checked by putting some values in lifegrid2 and they are being wiped, so it is pulling through from MyPanel, but only zeros. There are no errors being reported.
I have made a small test program with a 2d array which does pull values through.
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import java.awt.*;
import java.awt.event.*;
public class SwingPaintDemo3 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Swing Paint Demo");
f.setPreferredSize(new Dimension(1280,800));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
JPanel subPanel = new JPanel();
JButton start = new JButton("START");
subPanel.add(start);
start.setPreferredSize(new Dimension(100,50));
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae1) {
System.out.println("START");
int [][][] lifegrid2 = new int [12][12][2];
int temp;
for (int i=0; i<12; i++) {
for (int j=0; j<12; j++) {
**MyPanel obj = new MyPanel();
temp = obj.lifegrid [i][j][0];
lifegrid2 [i][j][0] = temp;**
if (j<11)
{System.out.print(lifegrid2 [j] [i] [0]);}
else
{System.out.println(lifegrid2 [j] [i] [0]);}}}
}
});
f.add(subPanel, BorderLayout.EAST);
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
class MyPanel extends JPanel {
public int [][][] lifegrid = new int [12][12][2];
private int squareX = 1280;
private int squareY = 800;
private int gridX, gridY ;
public MyPanel() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
squareX = e.getX();
squareY = e.getY();
if ((squareX>50 & squareX <550) & (squareY>50 & squareY <550) ){
gridX =(squareX-50)/50+1;
gridY =(squareY-50)/50+1;
squareX = (squareX -50)/50 * 50 + 50;
squareY = (squareY -50)/50 * 50 + 50;
System.out.println(gridX + " " + gridY);
lifegrid [gridX] [gridY] [0] = 1;
repaint(squareX,squareY,50,50);}
else {
}
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("This is my custom Panel!",10,20);
g.setColor(Color.RED);
g.fillRect(squareX,squareY,48,48);
g.setColor(Color.BLACK);
g.drawRect(squareX,squareY,48,48);
}
}
I have made a small test program with a 2d array
int [][][] lifegrid2 = new int [12][12][2];
That is a 3D array.
A 2D array is defined as:
int [][] lifegrid2 = new int [12][12];
The logic to initialize the array belongs in the constructor of your class:
MyPanel()
{
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
lifegrid [i][j] = 0)
}
}
}
Then your paintComponent() method needs to iterate through the 2D grid and only paint the grids that have a value of 1.
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
if (lifegrid[i][j] = 1)
// paint the grid
}
}
}
}
Edit:
As best as I can tell you are trying to create a grid based game. When you click on a cell in the grid the cell turns red. The are two common ways to approach this:
Use components. In this approach you have a parent panel using a GridLayout and you add a child panel to each cell in the grid. You would also add your MouseListener to each child panel. When you click on the child panel you change the background of the panel to red.
Do custom painting. In this approach you have a single JPanel. This class keep a 2D Array for the "state" of each cell in the grid. You add a single MouseListener to the panel. When you click on the panel you determine which cell was clicked and then you update the state of that cell. In the paintComponent() method you iterate through the 2D Array and paint each cell where that state has changed.
Your approach seems to be some kind of hybrid between the two and is not working.

Java - JPanel contains point method error

I have a 2d array of Grids (JPanels) that are added to another JPanel using the GridLayout. That JPanel is added to the JFrame. Whenever a click happens on the JFrame I'm attempting to take the Point of the click and determine if any of those Grids in the 2d array contain that Point.
I'm attempting to do this inside frame.addMouseListener...
I know the frame is registering the mouse clicks. For some reason the Grids don't register that they should be containing that Point. Can anyone explain this? if(theView[i][j].contains(me.getPoint())){ This is the line of code that seems to be failing me.
I originally attempted to have the Grids know when they were clicked on so I wouldn't have to coordinate between the frame and grids, but I couldn't get that to work.
Here's the level designer.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import javax.swing.*;
public class LevelDesigner extends JPanel implements ButtonListener{
private final int SIZE = 12;
private int [][] thePit;
private Grid [][] theView;
private ButtonPanel bp;
public static int val;
private int rows, cols;
private JPanel gridPanel;
private JFrame frame;
public LevelDesigner(int r, int c){
frame = new JFrame();
int h = 10, w = 10;
setVisible(true);
setLayout(new BorderLayout());
setBackground(Color.BLUE);
rows = r;
cols = c;
thePit = new int[r][c];
theView = new Grid[r][c];
gridPanel = new JPanel();
gridPanel.setVisible(true);
gridPanel.setBackground(Color.BLACK);
gridPanel.setPreferredSize(getMaximumSize());
GridLayout gridLayout = new GridLayout();
gridLayout.setColumns(cols);
gridLayout.setRows(rows);
gridPanel.setLayout(gridLayout);
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
theView[i][j] = new Grid(i, j, SIZE, this);
gridPanel.add(theView[i][j]);
}
}
String test [] = {"0", "1","2","3","4","save"};
bp = new ButtonPanel(test, this);
this.add(bp, BorderLayout.SOUTH);
this.add(gridPanel, BorderLayout.CENTER);
frame.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me) {
for(int i = 0; i < rows; ++i){
for(int j = 0; j < cols; ++j){
if(theView[i][j].contains(me.getPoint())){
theView[i][j].actionPerformed(null);
return;
}
}
}
}
});
frame.setVisible(true);
frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
frame.setTitle("Epic Crawl - Main Menu");
frame.pack();
frame.setLocationRelativeTo(null);
frame.repaint();
frame.add(this);
}
public String toString(){
int noRows = thePit.length;
int noColumns = thePit[0].length;
String s="";
for (int r=0;r<noRows;r++){
for (int c=0;c<noColumns;c++){
s=s + thePit[r][c] + " ";
}
s=s+"\n";
}
return(s);
}
public void notify( int i, int j){
thePit[i][j] = val;
}
public void print(){
final JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File("."));
int returnVal = fc.showSaveDialog( null);
if( returnVal == JFileChooser.APPROVE_OPTION ){
try{
PrintWriter p = new PrintWriter(
new File( fc.getSelectedFile().getName() ) );
System.out.println(" printing");
p.println( this );
p.close();
}
catch( Exception e){
System.out.println("ERROR: file not saved");
}
}
}
public void buttonPressed(String buttonLabel, int id){
if(id == 5)
print();
else
val = id;
}
public void buttonReleased( String buttonLabel, int buttonId ){}
public void buttonClicked( String buttonLabel, int buttonId ){}
public static void main(String arg[]){
LevelDesigner levelDesigner = new LevelDesigner(4, 4);
}
}
And here is the Grid.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Grid extends JPanel implements ActionListener{
LevelDesigner grid;
int myI, myJ;
private String[] imageNames = {"dirt.png", "grass.png", "Door.png", "woodfloor.png", "32x32WoodFloor.png"};
BufferedImage gridImage;
private String imagePath;
public Grid(int i, int j, int size, LevelDesigner m){
imagePath = "";
grid = m;
myI = i;
myJ = j;
setBackground(Color.RED);
this.setBorder(BorderFactory.createLineBorder(Color.black));
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae){
grid.notify(myI, myJ);
imagePath = "Images/" + imageNames[LevelDesigner.val];
gridImage = null;
InputStream input = this.getClass().getClassLoader().getResourceAsStream(imagePath);
try{
gridImage = ImageIO.read(input);
}catch(Exception e){System.err.println("Failed to load image");}
}
public void paintComponent(Graphics g){
super.paintComponent(g); // Important to call super class method
g.clearRect(0, 0, getWidth(), getHeight()); // Clear the board
g.drawImage(gridImage, 0, 0, getWidth(), getHeight(), null);
}
}
The contains method checks if the Point is within the boundaries of the JPanel but using a coordinate system relative to the JPanel. Instead consider using findComponentAt(Point p).
For example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
public class TestMouseListener {
private static final int SIDE_COUNT = 4;
private JPanel mainPanel = new JPanel();
private MyGridCell[][] grid = new MyGridCell[SIDE_COUNT][SIDE_COUNT];
public TestMouseListener() {
mainPanel.setLayout(new GridLayout(SIDE_COUNT, SIDE_COUNT));
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = new MyGridCell();
mainPanel.add(grid[i][j].getMainComponent());
}
}
mainPanel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
Component c = mainPanel.findComponentAt(p);
for (MyGridCell[] gridRow : grid) {
for (MyGridCell myGridCell : gridRow) {
if (c == myGridCell.getMainComponent()) {
myGridCell.setLabelText("Pressed!");
} else {
myGridCell.setLabelText("");
}
}
}
}
});
}
public Component getMainComponent() {
return mainPanel;
}
private static void createAndShowGui() {
TestMouseListener mainPanel = new TestMouseListener();
JFrame frame = new JFrame("TestMouseListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel.getMainComponent());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyGridCell {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
#SuppressWarnings("serial")
private JPanel mainPanel = new JPanel() {
public Dimension getPreferredSize() {
return MyGridCell.this.getPreferredSize();
};
};
private JLabel label = new JLabel();
public MyGridCell() {
mainPanel.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.setLayout(new GridBagLayout());
mainPanel.add(label);
}
public Component getMainComponent() {
return mainPanel;
}
public void setLabelText(String text) {
label.setText(text);
}
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
}
Component#contains "Checks whether this component "contains" the specified point, where the point's x and y coordinates are defined to be relative to the coordinate system of this component"
This means that the contains will only return true if the Point is within the bounds of 0 x 0 x width x height.
So if the component is position at 400x200 and is sized at 200x200 (for example). When you click within in, the mouse point will be between 400x200 and 600x400, which is actually out side of the relative position of the component (200x200) - confused yet...
Basically, you either need to convert the click point to a relative coordinate within the context of the component you are checking...
Point p = SwingUtilities.convertPoint(frame, me.getPoint(), theView[i][j])
if (theView[i][j].contains(p)) {...
Or use the components Rectangle bounds...
if (theView[i][j].getBounds().contains(me.getPoint())) {...
So, remember, mouse events are relative to the component that they were generated for

Java: Graphics Disappear upon clicking JButton

For my algorithms class we have to sort an array using mergesort and at each step draw the array as a histogram to graphically see what is going on. I am running into a problem with the paintComponent method updating the array. When I run the program for the first time, it shows the jumbled array (as it should) and then when I click the mergesort button, I am expecting to see the sorted array but instead, I get nothing. Any help would be appreciated, thanks.
Note: I know I'm not using mergesort now, I am just trying to get the graphics working first.
package a2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class GraphicalSort extends JFrame implements ActionListener {
static int[] data = new int[200];
JPanel panel = new JPanel(); //Panel to hold graphical display of array
JPanel buttonsPanel = new JPanel();
JButton mButton = new JButton("Mergesort");
int xPos = 0;
static int barWidth = 8;
static int barHeight = 1;
public GraphicalSort() {
setLayout(new BorderLayout());
mButton.addActionListener(this);
buttonsPanel.add(mButton);
for (int i = 0; i < data.length; i++) {
data[i] = (int) (500 * Math.random() + 1);
}
setSize(barWidth * data.length, barHeight * 500 + buttonsPanel.getHeight());
panel = new ArrayPanel();
add(buttonsPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
repaint();
validate();
}
public static void main(String[] args) {
GraphicalSort gs = new GraphicalSort();
gs.setTitle("Graphical Sort");
gs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gs.setLocationRelativeTo(null);
gs.setResizable(false);
gs.setVisible(true);
}
#SuppressWarnings("serial")
class ArrayPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
for (int i = 0; i < data.length; i++) {
g.fillRect(xPos, (barHeight * 500) - (barHeight * data[i]), barWidth, barHeight * data[i]);
xPos += barWidth;
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
remove(panel);
if (e.getSource() == mButton) {
Arrays.sort(data);
panel = new ArrayPanel();
}
add(panel, BorderLayout.CENTER);
repaint();
validate();
}
}
You aren't reseting the xPos instance variable which really should not be an instance variable because you only need it in the paintComponent. So get rid of it and move it to the paintComponent() method.
You also don't need to remove and re-add the panel. So here is what I did (note the removal of the statics! Those should be instance variables):
int[] data = new int[200];
JPanel panel;
JPanel buttonsPanel = new JPanel();
JButton mButton = new JButton("Mergesort");
int barWidth = 8;
int barHeight = 1;
class ArrayPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
int xPos = 0;
for (int i = 0; i < data.length; i++) {
System.out.println("Drawing " + i);
g.fillRect(xPos, (barHeight * 500) - (barHeight * data[i]), barWidth, barHeight * data[i]);
xPos += barWidth;
}
}
}
public void actionPerformed(ActionEvent e) {
Arrays.sort(data);
panel.repaint();
}
You need to reset your xPos variable, otherwise the x co-ordinate will appear off-screen:
int xPos = 0;
Aside: creating a new ArrayPanel is unnecessary — just resetting the variables and calling repaint will work by making xPos a class member variable of ArrayPanel.

Java, Grid of Objects

I need help with drawing the grids to the GUI as well as the program later letting me change the colour of the boxes drawn. I know i will have to use paintComponent(Graphics g), but i have no idea how or where.
So here is a copy of the code i have got so far ( even though i have been told it can be quite daunting just being given code i think it is the best way for people to help and not just do it for me). From the top it sets values, creates the GUI, calls the GUI, fills a 2d array with boxes( i think). Then in the Boxes class setting values the boxes class will need, then the start of how to draw them (didn't know how to work it out), then some seta methods for the x and y coordinates.
what i would like you to do is show how to have the boxes be drawn to the Jpanel, to make a grid and then to show me how to change the colour to different shades of blue, depending on a external value.
import java.awt.*;
import java.awt.Graphics;
import java.util.*;
import javax.swing.*;
public class NewGrid {
Boxes[][] Boxs;
int BoxesX;
int BoxesY;
NewGrid() {
buildtheGUI();
}
JFrame frame = new JFrame();
JPanel panel = new JPanel();
public void buildtheGUI() {
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new NewGrid();
}
public void addboxes() {
Boxs = new Boxes[panel.getWidth() / 10][panel.getHeight() / 10];
for (int i = 0; i < panel.getWidth() / 10; i++) {
for (int j = 0; j < panel.getHeight() / 10; j++) {
Boxs[i][j] = new Boxes();
Boxs[i][j].setx(i * (panel.getWidth() / 10));
Boxs[i][j].sety(j * (panel.getHeight() / 10));
Boxs[i][j].draw(null);
}
}
}
}
public class Boxes extends JPanel {
int x;
int y;
int width = 10;
int hieight = 10;
Color colour = Color.BLACK;
public void draw(Graphics g) {
g.setColor(colour);
g.fillRect(x, y, width, hieight);
}
public void setx(int i ){
x = i;
}
public void sety(int i ){
y = i;
}
}
I can't comment something, to try to make things easier,
I code there box.putClientProperty(unique_identifier, value_for_identifier), you can to multiple this method as you want
from every Swing Listener you can to get this and proper coordinated defined in putClientProperty
.
JComponent comp = event.getComponent();
String strRow = (String) comp.getClientProperty("row");
String strColumn = (String) comp.getClientProperty("column");
simple code
import java.awt.*;
import java.awt.Graphics;
import java.util.*;
import javax.swing.*;
public class NewGrid {
private int row = 10;
private int column = 10;
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private NewGrid() {
addboxes();
panel.setLayout(new GridLayout(row, column));
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void addboxes() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
Boxes box = new Boxes();
box.putClientProperty("row", row);
box.putClientProperty("column", column);
panel.add(box);
}
}
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
#Override
public void run() {
new NewGrid();
}
};
SwingUtilities.invokeLater(doRun);
}
}
class Boxes extends JPanel {
private static final long serialVersionUID = 1L;
#Override
public Dimension getMinimumSize() {
return new Dimension(20, 20);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(20, 20);
}
#Override
public void paintComponent(Graphics g) {
int margin = 2;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2,
dim.height - margin * 2);
}
}

Categories

Resources