As the title says, I'm having a hard time trying to draw some rectangles (filled) in JApplet.
The exact goal is to have a 50x50 table and when you click on a targeted cell, to make it filled (possibly done by drawing a filled rectangle). I have done the maths about the coordinates of the starting point, but for some reason I can't draw the new rectangle in the MouseClicked method. Any suggestions?
public class Main extends JApplet {
public static final int DIMX = 800;
public static final int DIMY = 800;
public static final int ratio = 16;
Graphics g;
boolean drawing;
public int cX;
public int cY;
public Main() {
JPanel MainFrame = new JPanel();
MainFrame.setPreferredSize(new Dimension(400, 800));
MainFrame.setBackground(Color.LIGHT_GRAY);
JPanel Table = new JPanel();
Table.setPreferredSize(new Dimension(800, 800));
Table.setBackground(Color.LIGHT_GRAY);
add(MainFrame, BorderLayout.EAST);
add(Table, BorderLayout.WEST);
addMouseListener(new clicked());
}
public void paint(Graphics g) {
super.paintComponents(g);
g.setColor(Color.black);
for (int i = 0; i <= 800; i += 16) {
g.drawLine(0, i, 800, i);
g.drawLine(i, 0, i, 800);
// g.fillRect(cX, cY, 16, 16);
}
}
public static void main(String[] args) {
JFrame win = new JFrame("Retarded Bullshit");
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setPreferredSize(new Dimension(1216, 840));
win.setContentPane(new Main());
win.pack();
win.setVisible(true);
}
public class clicked extends JApplet implements MouseListener {
public int cX;
public int cY;
Graphics g;
#Override
public void mouseClicked(MouseEvent e) {
// Point a = e.getLocationOnScreen();
int cellX = e.getX();
int cellY = e.getY();
if (cellX < 800 && cellX > 0 && cellY < 800 && cellY > 0) {
cX = cellX / 16 + 1;
cY = cellY / 16 + 1;
JOptionPane.showMessageDialog(null, "" + cX + " " + cY);
}
This is a relatively simple concept (no offense).
To start with, don't mix your code with JApplet and JFrame. If you want to use your application in these two mediums, separate the logic into a separate component (like JPanel) which you can easily add to either. You really shouldn't add a top level container to another top level container (adding an applet to a frame) - it's messy.
Avoid overriding the paint methods of top level containers (like JApplet), instead, use a custom component (like JPanel) instead and override it's paintComponent method.
In your example, you should be calling super.paint rather then super.paintComponents. paint does important work, you don't want to skip it - but you should be using JComponent#paintComponent
MouseListeners should added to the components that you are interested in managing mouse events. Because clicked is never added to any containers, it will never recieve mouse events.
Take a look at
How to write mouse listeners
Performing Custom Painting
2D Graphics
Painting in AWT and Swing (because every Swing developer should have an understanding of this)
public class SimplePaint03 {
public static void main(String[] args) {
new SimplePaint03();
}
public SimplePaint03() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintPane extends JPanel {
private List<Shape> grid;
private List<Shape> fill;
public PaintPane() {
grid = new ArrayList<>(5);
fill = new ArrayList<>(5);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
for (Shape shape : grid) {
if (shape.contains(e.getPoint())) {
if (fill.contains(shape)) {
fill.remove(shape);
} else {
fill.add(shape);
}
}
}
repaint();
}
});
int colWidth = 200 / 50;
int rowHeight = 200 / 50;
for (int row = 0; row < 50; row++) {
for (int col = 0; col < 50; col++) {
grid.add(new Rectangle(colWidth * col, rowHeight * row, colWidth, rowHeight));
}
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
for (Shape cell : fill) {
g2d.fill(cell);
}
g2d.setColor(Color.BLACK);
for (Shape cell : grid) {
g2d.draw(cell);
}
}
}
}
Additional
Information from one paint cycle to another is not maintained. You are required to repaint the component exactly the way you want it to appear. This means you will need to maintain a list of click points that can be repainted at any time.
Start by reading the Swing tutorial on Custom Painting.
Custom painting is done by overriding the paintComponent() method of a JPanel or JComponent(). Then you add the panel to the JApplet.
If you only want to paint certain squares then you are going to need a List to keep track of which cells to paint. Then every time you repaint the component you will need to loop through the List and paint the cells.
Your MouseListener would not extend JApplet. When you click on a cell you would update the List from above to indicate that the cell needs to be painted. Then you would invoke repaint() on the panel so that your painting code will be invoked.
You may also want to look at Custom Painting Approaches which gives two different ways to do this type of painting depending on your exact requirement.
Related
I'm making a gravity simulator and I need it animate live so the user can watch it. I've been able to make it trace out the path the object would take.
But as you can see it just traces it out and then displays the window. I think my problem is because all of this in the section of code that builds the JPanel but I don't know how to change it properly.
Here's what I'm doing for my window:
import java.awt.*;
import javax.swing.*;
import java.lang.Math;
public class Universe {
public static void main(String[] args) throws InterruptedException {
new Universe();
}
public Universe() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Gravity Simulator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
int paneWidth = 500;
int paneHeight = 500;
#Override
public Dimension getPreferredSize() {
return new Dimension(paneWidth, paneHeight);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int size = Math.min(getWidth()-4, getHeight()-4) / 10;
int width = getWidth() - (size * 2);
int height = getHeight() - (size * 2);
int x0=paneWidth/2; int y0=paneHeight/2; int radius0=20;
int y = (getHeight() - (size * 10)) / 2;
for (int horz = 0; horz < 2; horz++) {
int x = (getWidth() - (size * 10)) / 2;
for (int vert = 0; vert < 10; vert++) {
g.drawRect(x, y, size, size);
drawCircle(g, x+25, y+25, 5);//A massive object would go here this just proof of concept
x += size;
}
y += size;
}
double[] velocity={5,-2};
MassiveObject planet = new MassiveObject(g, 20, 50, velocity, 250, 150);
planet.draw(g);
MassiveObject rock = new MassiveObject(g, 2, 25, velocity, 275, 300);
rock.draw(g);
double sGravity = fGrav(planet, rock);
//double dis = massDis(planet, rock);
System.out.println("Distance: "+massDis(planet, rock));
System.out.println("Gravity: "+sGravity+" Newtons of force(gravity is multiplied by "+1000000+")");
double[] traj = objectTrajetory(planet, rock, rock.getMass());
int t = 0;
try {
while(true) {
//double k = sGravity/dis;
//x and y components of motion
double xm = traj[0];
double ym = traj[1];
double[] nVelocity= {xm,ym};
//////////////////////////////
//set new position of object
rock.setX(rock.getX()+(xm));
rock.setY(rock.getY()+(ym));
rock.setVelocity(nVelocity);
rock.draw(g);
t++;
System.out.println("position changed: "+rock.getCoords());
traj = objectTrajetory(planet, rock, 1);
Thread.sleep(100);
if (t> 15){break;}
}
}
catch(Exception e) {
}
//System.out.println("Distance: "+massDis(planet, rock));
//System.out.println("Gravity: "+fGrav(planet, rock)+" Newtons of force(gravity is multiplied by "+1000000+")");
g2d.dispose();
}
And here is the code for the draw function of my MassiveObject:
public void draw(Graphics g){
Graphics2D g2d = (Graphics2D) g;
Ellipse2D.Double circle = new Ellipse2D.Double(this.x0-(this.radius/2), this.y0-(this.radius/2), this.radius, this.radius);
g2d.setColor(Color.GRAY);
g2d.fill(circle);
}
So basically what I'm asking is how can I make it run that algorithm to paste the MassiveObject at its new location after the window is already pulled up so the user can watch it happening instead of it just building the window with it already on it?
The logic of your animation shouldn't be in the paintComponent() method. The paintComponent() method should just paint the current frame of animation. The code inside paintComponent() is run inside a special thread dedicated to handling all UI paints, responding to clicks etc. So for as long as paintComponent() is running, nothing else can happen in the UI, hence your application "grinds to a halt".
The logic to periodically update the state and then order a repaint should be in a separate thread (or the main thread). When it has updated the state and needs the next frame to be drawn, it then calls the panel's repaint() method. Because you're doing this in another thread, you would surround it in SwingUtilities.invokeLater(). This orders Swing to to call back into the paintComponent():
while (true) {
// Update state used by the paintComponent() method
updateObjectPositions();
// Now draw the new animation frame
SwingUtilities.invokeLater(() -> {
universePanel.repaint(0, 0, universeWidth, universeHeight);
});
Thread.sleep(...);
}
Because the drawing and updating are happening in different threads, you need to make sure that the data is shared between the threads in a thread-safe way. If you're just starting out and the calculations are very quick, then you could put the updateObjectPositions() method inside the invokeLater() so that the update to the data and the redraw happen in the UI thread. But remember that the code inside the invokeLater() will be blocking the UI for as long as it runs, so it should be as brief as possible and just handle a single frame. Crucially, your while loop and sleep should not go inside the invokeLater() or inside any UI code such as paintComponent().
Thanks a lot for the help, I was able to get the program animating the way I wanted it to and it was exactly as you all suggested. I removed my logic from the paintComponent() and put it inside the JPanel pane, ran a timer to continuously update the position, and then ran the repaint() function at the end of each loop in timer.
public class TestPane extends JPanel {
int paneWidth = 1200;
int paneHeight = 1200;
double[] velocity={4,4};
MassiveObject planet = new MassiveObject( 50, 50, velocity, paneWidth/2,paneHeight/2);
MassiveObject rock = new MassiveObject( 2, 25, velocity, 150, 200);
double[] traj = objectTrajetory(planet, rock, rock.getMass());
double xm=0.00;
double ym=0.00;
public TestPane() {
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
xm = traj[0];
ym = traj[1];
double[] nVelocity= {xm,ym};
//////////////////////////////
//set new position of object
rock.setX(rock.getX()+(xm));
rock.setY(rock.getY()+(ym));
rock.setVelocity(nVelocity);
System.out.println("position changed: "+rock.getCoords());
repaint();
traj = objectTrajetory(planet, rock, 1);
rock.setX(rock.getX()+(xm));
rock.setY(rock.getY()+(ym));
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(paneWidth, paneHeight);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int size = Math.min(getWidth()-4, getHeight()-4) / 10;
int width = getWidth() - (size * 2);
int height = getHeight() - (size * 2);
int x0=paneWidth/2; int y0=paneHeight/2; int radius0=20;
rock.draw(g);
planet.draw(g);
g2d.dispose();
}
The program now animates pretty smoothly instead of just spitting out a plot of the path it would take.
Snap of Animated Orbit
I am trying to recreate the Game of Life in Java using JFrame. I have already completed most of the program but this one thing is bugging me. How do I make a bunch of fields(panels) which are clickable, so that the user can input their own pattern, instead of the computer randomly generating the pattern each time?
You could use a GridLayout layout manager to put all the JPanels in a grid, and for each JPanel, add an instance of the MouseAdapter class with addMouseListener() to listen for mouse clicks to flip their state. The instance of MouseAdapter would override mouseClicked() and within that function, flip the state of the JPanel.
This is just to make a complete example, but here would be the creation of the frame and setting its layout manager:
public static void main(String[] args) {
JFrame frame = new JFrame();
int width = 200, height = 200;
frame.setSize(width, height);
int rows = width/10, cols = height/10;
frame.setLayout(new GridLayout(rows, cols));
// add all the cells
for(int j = 0; j < cols; j++) {
for(int i = 0; i < rows; i++) {
frame.add(new Cell(i, j));
}
}
frame.setVisible(true);
}
Then for each cell, we have instances of this class:
class Cell extends JPanel {
int row, col;
public static final int STATE_DEAD = 0;
public static final int STATE_ALIVE = 1;
int state = STATE_DEAD;
public Cell(int row, int col) {
this.row = row;
this.col = col;
// MouseAdapter tells a component how it should react to mouse events
MouseAdapter mouseAdapter = new MouseAdapter() {
// using mouseReleased because moving the mouse slightly
// while clicking will register as a drag instead of a click
#Override
public void mouseReleased(MouseEvent e) {
flip();
repaint(); // redraw the JPanel to reflect new state
}
};
// assign that behavior to this JPanel for mouse button events
addMouseListener(mouseAdapter);
}
// Override this method to change drawing behavior to reflect state
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// fill the cell with black if it is dead
if(state == STATE_DEAD) {
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public void flip() {
if(state == STATE_DEAD) {
state = STATE_ALIVE;
} else {
state = STATE_DEAD;
}
}
}
Alternatively, you could override the paintComponent() method of one JPanel, and do the above but use addMouseMotionListener() as well, that way your one panel can track which drawn grid cell the mouse is in, and you can control how they are drawn.
I don't understand why i have to set Component.setPreferredSize() to draw and why my ovals are not placed in one place. Also i got some other questions, which are described below.
public class PaintPanel extends JPanel implements ActionListener
{
private void initStructure()
{
for (int i : new Range(MAX_AGENTS)) {
Agent agent = new Agent();
agents.add(agent);
add(agent);
}
}
//i want to override parent class 'add', to easy call 'actionPerformed' on children elements.
public Component add(Element comp)
{
elements.add(comp);
return super.add(comp);
}
#Override
public void actionPerformed(ActionEvent e)
{
for(Element element: elements){
element.actionPerformed(e);
}
repaint();
}
//ELEMENT is abstract class: 'public class Element extends JComponent implements ActionListener'
public class Agent extends Element
{
public Agent()
{
super();
// setPreferredSize(new Dimension(120,120)); !!!! a-a, i don't know the future size of the oval or triangle, i don't want and i can't set this :(
setVisible(true);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
System.out.println("draw"); //called
Point p1 = new Point(1, 1);
Point p2 = new Point(101, 101);
Point p3 = new Point(10, 10);
int[] xs = { p1.x, p2.x, p3.x };
int[] ys = { p1.y, p2.y, p3.y };
Polygon triangle = new Polygon(xs, ys, xs.length);
g.setColor(new Color(255,255,255)); // !! never painted
g.fillPolygon(triangle); //!! never painted
g.drawOval(10,10,10,10); // !!!! painted only when i set preferredSize
}
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("i am alive"); //working
}
}
In case, if i set preferred size i got the picture below.
So.
Question
1) Is there any patterns to not set preferred size and draw component inside Component calling paint() on contentPanel?
2) Why g.fillPolygon not working?
3) Why my ovals are not placed in one point?
Why my ovals are not placed in one point?
I would guess you are adding your Agent components to a JPanel. By default a JPanel uses a FlowLayout. So each component is placed 120 pixels apart and flow to a new line when the row is filled.
i don't know the future size of the oval or triangle, i don't want and i can't set this
Don't use the drawOval(...) method. Instead use a Shape object that represents an oval. Then you can get the size of the Shape and use this value in the getPreferredSize() method mentioned by #hovercraft.
Check out Playing With Shapes for more info on this concept. Of course if you use this concept you would need to define the Shapes as instance variable so the Shape can be referenced by both the paintComponent() and getpreferredSize() methods.
The issue is if the JPanel doesn't have a preferred size, and if it is being added to a container that uses a layout manager that doesn't fill the container (such as FlowLayout), then how will the GUI know what size the drawing JPanel should be? I've heard that better than calling setPreferredSize(...) on your JPanel is to override its Dimension getPreferredSize() method (ask kleopatra, a Swing expert on this site).
Regarding:
Why g.fillShape not working?
Check the API -- does Graphics have a fillShape method? Nope. But Graphics2D has a fill(Shape s) method, and that's what you want.
Why my ovals are not placed in one point?
Please clarify this and provide details. What do you mean by "placed in one point"? What behavior exactly are you expecting and why?
Edit: your triangle is not being drawn because all the points are co-linear!
For example:
import java.awt.*;
import javax.swing.*;
public class MyDrawingPanel extends JPanel {
private static final int PREF_W = 100;
private static final int PREF_H = PREF_W;
// private Point p1 = new Point(1, 1);
private Point p1 = new Point(30, 1);
private Point p2 = new Point(100, 101);
// private Point p3 = new Point(10, 10);
private Point p3 = new Point(50, 10);
private int[] xs = { p1.x, p2.x, p3.x };
private int[] ys = { p1.y, p2.y, p3.y };
private Polygon triangle = new Polygon(xs, ys, xs.length);
public MyDrawingPanel() {
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(255, 255, 255)); // !! never painted
g.fillPolygon(triangle); // !! never painted
g.drawOval(10, 10, 10, 10); // !!!! painted only when i set preferredSize
}
private static void createAndShowGui() {
int rows = 4;
int cols = 4;
JPanel gridPanel = new JPanel(new GridLayout(rows, cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
gridPanel.add(new MyDrawingPanel());
}
}
JFrame frame = new JFrame("PaintPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(gridPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I've been searching for a way to draw a black-and-white array on screen. It's a simple array, just 20x20. What I plan to do is to draw on an array with the mouse so that each pixel "toggles" from black to white and back when clicked, then pass the array as a set of booleans (or integers) to another function. Currently I'm using Swing. I do remember to have used Swing for drawing on a canvas, but I still can't find the actual usage. Should I use a canvas, or instead rely on JToggleButtons?
You can simply use a JFrame (or other Swing component) and override the paint(Graphics) method to draw a representation of the boolean matrix (note that in the case of a lightweight component such as JPanel you should override paintComponent(Graphics). This will give you the click-and-drag capability you require (which is very difficult to achieve using a grid of individual Swing components).
As other people have commented, AWT Canvas doesn't give you anything not provided by Swing components and you'll see in the example below that I've used the createBufferStrategy method also present on JFrame to ensure a non-flicker display.
Note that my example is fairly simple in that it toggles every pixel you drag across rather than the click operation establishing whether you're in "paint" mode or "erase" mode and then exclusively applying black or white pixels for the duration of the drag.
public class Grid extends JFrame {
private static final int SCALE = 10; // 1 boolean value == 10 x 10 pixels.
private static final int SIZE = 20;
private boolean[][] matrix = new boolean[SIZE][SIZE];
private boolean painting;
private int lastX = -1;
private int lastY = -1;
public Grid() throws HeadlessException {
setPreferredSize(new Dimension(SIZE * SCALE, SIZE * SCALE));
setResizable(false);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
painting = true;
tryAdjustValue(e.getPoint());
}
public void mouseReleased(MouseEvent e) {
painting = false;
lastX = -1;
lastY = -1;
}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
tryAdjustValue(e.getPoint());
}
public void mouseMoved(MouseEvent e) {
tryAdjustValue(e.getPoint());
}
});
}
private void tryAdjustValue(Point pt) {
int newX = pt.x / SCALE;
int newY = pt.y / SCALE;
if (painting && isInRange(newX) && isInRange(newY) && (newX != lastX || newY != lastY)) {
// Only invert "pixel" if we're currently in painting mode, both array indices are valid
// and we're not attempting to adjust the same "pixel" as before (important for drag operations).
matrix[newX][newY] = !matrix[newX][newY];
lastX = newX;
lastY = newY;
repaint();
}
}
private boolean isInRange(int val) {
return val >= 0 && val < SIZE;
}
public void paint(Graphics g) {
super.paint(g);
for (int x=0; x<SIZE; ++x) {
for (int y=0; y<SIZE; ++y) {
if (matrix[x][y]) {
g.fillRect(x * SCALE, y * SCALE, SCALE, SCALE);
}
}
}
}
public static void main(String[] args) {
Grid grid = new Grid();
grid.pack();
grid.setLocationRelativeTo(null);
grid.createBufferStrategy(2);
grid.setVisible(true);
}
}
Why not a simple 20 x 20 grid of JPanel held in a GridLayout(20, 20), and flip the panel's background color if clicked via a MouseListener's mousePressed method. You could hold the panels in a 2D array and query their background color whenever the need arises.
You could also use JLabels for this, but you'd have to remember to turn their opaque properties to true. A JButton would work as well or a JToggleButton, ... the options are almost limitless. I do not recommend though that you use AWT (Canvas) as their's no need to step backwards in functionality since Swing handles this so well.
If you get stuck on this, why not come back and show us your code and we'll better be able to give you more specific help.
Another way to solve this is to use a single JPanel and override its paintComponent method. You could give it an int[][] array to serve as its model, and then in the paintComponent method draw rectangles of whatever color desired based on the state of the model. Then give it a MouseListener that changes the state of the model and calls repaint.
e.g.,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class BlackWhiteGridPanel extends JPanel {
// can have multiple colors if desired
// public static final Color[] COLORS = {Color.black, Color.red, Color.blue, Color.white};
public static final Color[] COLORS = {Color.black, Color.white};
public static final int SIDE = 20;
private static final int BWG_WIDTH = 400;
private static final int BWG_HEIGHT = BWG_WIDTH;
private int[][] model = new int[SIDE][SIDE]; // filled with 0's.
public BlackWhiteGridPanel() {
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
myMousePressed(e);
}
});
}
private void myMousePressed(MouseEvent e) {
// find relative position of mouse press on grid.
int i = (e.getX() * SIDE) / getWidth();
int j = (e.getY() * SIDE) / getHeight();
int value = model[i][j];
// the model can only hold states allowed by the COLORS array.
// So if only two colors, then value can only be 0 or 1.
value = (value + 1) % COLORS.length;
model[i][j] = value;
repaint();
}
public int[][] getModel() {
// return a copy of model so as not to risk corruption from outside classes
int[][] copy = new int[model.length][model[0].length];
for (int i = 0; i < copy.length; i++) {
System.arraycopy(model[i], 0, copy[i], 0, model[i].length);
}
return copy;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int ht = getHeight();
for (int i = 0; i < model.length; i++) {
for (int j = 0; j < model[i].length; j++) {
Color c = COLORS[model[i][j]];
g.setColor(c);
int x = (i * width) / SIDE;
int y = (j * ht) / SIDE;
int w = ((i + 1) * width) / SIDE - x;
int h = ((j + 1) * ht) / SIDE - y;
g.fillRect(x, y, w, h);
}
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(BWG_WIDTH, BWG_HEIGHT);
}
private static void createAndShowGui() {
BlackWhiteGridPanel mainPanel = new BlackWhiteGridPanel();
JFrame frame = new JFrame("BlackWhiteGrid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I have a JTextArea and it's riding on top of a JScrollPane. Anyways, I know I can use the getViewPort() method to set the opaque property of the viewport, but I cannot seem to find any sign of how to do that anywhere.
Here is what I have so far:
if (e.getKeyCode() == KeyEvent.VK_F)
{
if (sp.isVisible())
{
sp.setVisible(false);
}
else
{
sp.setVisible(true);
}
}
You need to use setOpaque(false) to make it transparent. Call that both on the JScrollPane, and on it's ViewPort.
sp.setOpaque(false);
sp.getViewport().setOpaque(false);
You'll also have to call setOpaque(false) on the JTextArea, if you want that transparent as well.
Your colloquy with #Serplat suggests that you may be confounding opacity and transparency.
Opacity is a boolean property of Swing components used to optimize drawing:
true: The component agrees to paint all of the bits contained within its rectangular bounds.
false: The component makes no guarantees about painting all the bits within its rectangular bounds.
Transparency is a means of compositing digital images, as seen in this example.
Considering the distinction may help to clarify your question or focus your search for more information.
Addendum: Based on #camickr's example, the example below shows a blue square that "sticks" to the viewport, while the gray checkerboard may be scrolled over it.
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/questions/2846497 */
public class ScrollPanePaint extends JFrame {
private static final int TILE = 64;
public ScrollPanePaint() {
JViewport viewport = new MyViewport();
viewport.setView(new MyPanel());
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewport(viewport);
this.add(scrollPane);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
private static class MyViewport extends JViewport {
public MyViewport() {
this.setOpaque(false);
this.setPreferredSize(new Dimension(6 * TILE, 6 * TILE));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.fillRect(TILE, TILE, 3 * TILE, 3 * TILE);
}
}
private static class MyPanel extends JPanel {
public MyPanel() {
this.setOpaque(false);
this.setPreferredSize(new Dimension(9 * TILE, 9 * TILE));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.lightGray);
int w = this.getWidth() / TILE + 1;
int h = this.getHeight() / TILE + 1;
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
if ((row + col) % 2 == 0) {
g.fillRect(col * TILE, row * TILE, TILE, TILE);
}
}
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ScrollPanePaint();
}
});
}
}
Code for JScrollpane Transparent Background.
JScrollPane scrollPane = new JScrollPane();
JViewport viewport = new JViewport();
//Component that need to be added in Scroll pane//
viewport.setView(new JPanel());
viewport.setOpaque(false);
scrollPane.setViewport(viewport);
scrollPane.getViewport().setOpaque(false);
scrollPane.setOpaque(false);
// Add Scrollpane to Jframe or JPanel//
add( scrollPane,BorderLayout.CENTER);