moving glass pane between frames - java

I'm dragging component from one frame in main monitor to another frame in secondary monitor ,and while I'm dragging it the component painted in glasspane, I can see the glasspane over the main mointor ,but after the mouse reach the secondary monitor, the glasspane disappears? Can any one help me in this? How I can paint the glasspane over the secondary monitor?
Here is some pieces of my code:
public class Main_Frame extends JFrame
{
public Main_Frame (){
//adding the content of main JFrame
setGlassPane(new ImageGlassPane());
//detect other screens and making object of Second_Frame for each
}
}
public class Second_Frame extends JDialog{
public Second_Frame(){
super(new Frame(MultiMonitor.getInstance().getNextDevice().getDefaultConfiguration()),
Title, false);
setGlassPane(new ImageGlassPane());
}
}
public class ImageGlassPane() extends JPanel{
public ImageGlassPane() {
setOpaque(false);
}
protected void paintComponent(Graphics g) {
if ( !isVisible()) {
return;
}
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int x = (int) (location.getX() - (width * zoom / 2));
int y = (int) (location.getY() - (height * zoom / 2));
if (visibleRect != null) {
g2.setClip(visibleRect);
}
if (visibleRect != null) {
Area clip = new Area(visibleRect);
g2.setClip(clip);
}
g2.drawImage(image, x, y, (int) (width * zoom), (int) (height * zoom), null);
}
}

However you are painting the component in the glass pane on the first frame, you will need to do for the second frame as well. This sounds like it is not a two monitor issue, but a two frame issue instead.

Related

Java Swing: background of the whole ScrollBar (doesn't show up)

I am working on a swing app (let us omit why).
I need to make a custom design of a scrollbar. So far so good, I implemented my descendant of ScrollBarUI - i have custom buttons, custom thumb, custom track... except of the area around my buttons - I added some padding there and I want to wrap all my scrollbar into a rectangle with rounded corners.
As I haven't found means to do that in ScrollBarUI, I decided to extend JScrollPane (to extend ScrollBar which is used there, so I could draw my rounded rectangle in paintComponent). This is what I made:
public class MyScrollPane extends JScrollPane {
public MyScrollPane(Component view) {
super(view);
}
#Override
public JScrollBar createVerticalScrollBar() {
return new MyScrollBar(JScrollBar.VERTICAL);
}
#Override
public JScrollBar createHorizontalScrollBar() {
return new MyScrollBar(JScrollBar.HORIZONTAL);
}
protected class MyScrollBar extends ScrollBar {
public MyScrollBar(int orientation) {
super(orientation);
setUI(MyScrollBarUI.createUI(this));
setOpaque(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int borderDiameterX = 32;
int borderDiameterY = 32;
g2.translate(this.getX(), this.getY());
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.gray);
g2.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, borderDiameterX, borderDiameterY);
g2.translate(-this.getX(), -this.getY());
}
}
}
Unfortunately, this doesn't work:
if setOpacity(true) - it draws squares of default color around buttons
if setOpacity(false) - it doesn't draw background
Code is called, I checked. The inner elements of scrollbar - thumb, buttons are all fine.
What did I miss?
Ok. There were 3 issues in my code.
setOpacity must be false to prevent built-in background drawing.
g2.translate - not needed, mindlessly copied from ScrollBarUI code
super.paintComponent(g) - i moved it to the end of my paintComponent, otherwise drawing in MyScrollBarUI was behind my painted background.
So it looks like this now:
public class MyScrollPane extends JScrollPane {
public MyScrollPane(Component view) {
super(view);
}
#Override
public JScrollBar createVerticalScrollBar() {
return new MyScrollBar(JScrollBar.VERTICAL);
}
#Override
public JScrollBar createHorizontalScrollBar() {
return new MyScrollBar(JScrollBar.HORIZONTAL);
}
protected class MyScrollBar extends ScrollBar {
public MyScrollBar(int orientation) {
super(orientation);
setUI(MyScrollBarUI.createUI(this));
setOpaque(false);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int borderDiameter = 32;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.gray);
g2.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, borderDiameter, borderDiameter);
super.paintComponent(g);
}
}
}

paintComponent() and paint() - drawing JButton with decorator pattern

I found a decorator pattern example with Swing component. The following code is drawing three buttons on a JFrame. One of the button has slash on it and implemented with Decorator pattern. The original one has paint() method, but I replaced paint() with paintComponent(Graphics g), then it fails to draw lines on the button. Is it impossible to use paintComponent() instead of paint()? If possible how to do that? What is the problem of this trial? What I am missing?
Original code link is Decorator pattern in Java.
public class DecoWindow extends JFrame implements ActionListener {
JButton Quit;
public DecoWindow() {
super("Deco Button");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
getContentPane().add(jp);
jp.add(new CoolDDecorator(new JButton("Cbutton")));
jp.add(new SlashDDecorator(new CoolDDecorator(new JButton("Dbutton"))));
jp.add(Quit = new JButton("Quit"));
Quit.addActionListener(this);
setSize(new Dimension(200, 100));
setVisible(true);
Quit.requestFocus();
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
public static void main(String argv[]) {
new DecoWindow();
}
}
class DDecorator extends JComponent {
public DDecorator(JComponent c) {
setLayout(new BorderLayout());
add("Center", c);
}
}
class SlashDDecorator extends DDecorator {
int x1, y1, w1, h1;
public SlashDDecorator(JComponent c) {
super(c);
}
public void setBounds(int x, int y, int w, int h) {
x1 = x; y1 = y;
w1 = w; h1 = h;
super.setBounds(x, y, w, h);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.red);
g2d.drawLine(0, 0, w1, h1);
}
}
class CoolDDecorator extends DDecorator {
boolean mouse_over; //true when mose over button
JComponent thisComp;
public CoolDDecorator(JComponent c) {
super(c);
mouse_over = false;
thisComp = this; //save this component
//catch mouse movements in inner class
c.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
mouse_over = true; //set flag when mouse over
thisComp.repaint();
}
public void mouseExited(MouseEvent e) {
mouse_over = false; //clear flag when mouse not over
thisComp.repaint();
}
});
}
//paint the button
public void paintComponent(Graphics g) {
super.paintComponent(g); //first draw the parent button
Graphics2D g2d = (Graphics2D) g;
//if the mouse is not over the button
//erase the borders
if (!mouse_over) {
Dimension size = super.getSize();
g2d.setColor(Color.lightGray);
g2d.drawRect(0, 0, size.width - 1, size.height - 1);
g2d.drawLine(size.width - 2, 0, size.width - 2, size.height - 1);
g2d.drawLine(0, size.height - 2, size.width - 2, size.height - 2);
}
}
}
paint() calls paintComponent() then paintChildren(). Your component is painting the slash and returning from paintComponent(). Then the default paint() implementation moves on, eventually painting the children, which are those buttons, which then just paint right ontop of your slash.
Your IDE should let you place a breakpoint in your paint code. You can check the callstack to see what's going on. If you aren't using an IDE, you can look at what Swing is doing by looking at JComponent.java in src.zip within your JDK.
Why do you want to use paintComponent() anyway?

How to paint components in layers in Java?

I have big problem with coding graphic part of my app, where I need to have components one on top of each other:
First I have JFrame (with fixed size)
In it I have two JPanel components. I want them to have colour background.
That's the easy part.
On one of the JPanel components I want to draw fixed shapres - rectangles, lanes, etc. Here I have problem, that I have two classes: one extends JPanel and is background for this part and second extends JComponent and represents element I draw (there is several elements). I don't know how to draw the elements in the JPanel - I tried several methods and nothing showed up. It's important to me that the JComponents should be drawn and conected only with this JPanel, not with whole frame.
On top of that I want to have moving shapes. It's easy when I have only frame and let's say rectangle, because I only change position and call repaint() method, but how to do this to make the moving shapes be connected to and be inside JPanel and to left previous layers in their place?
For my tries I created few classes with rectangles:
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class Main{
public Main() {
JFrame frame = new JFrame();
frame.setSize(1200, 900);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JPanel background = new JPanel();
background.setBackground(Color.lightGray);
GreenRect gr = new GreenRect();
gr.setPreferredSize(new Dimension(500,800));
background.add(gr, BorderLayout.WEST);
RedRect rr = new RedRect();
rr.setPreferredSize(new Dimension(500,800));
background.add(rr, BorderLayout.EAST);
frame.add(background);
}
public static void main(String[] args) {
new Main();
}
}
class GreenRect extends JPanel {
ArrayList<BlackRect> r = new ArrayList<>();
ArrayList<MovingRec> m = new ArrayList<>();
public GreenRect() {
setBackground(Color.green);
addRec(10,10);
addRec(50,50);
addRec(100,100);
addRec(1000,1000);
}
public void addRec(int x, int y) {
r.add(new BlackRect(x,y));
}
}
class RedRect extends JPanel {
public RedRect() {
setBackground(Color.red);
}
}
class BlackRect extends JComponent {
int x, y;
int w = 100, h = 100;
public BlackRect (int x, int y){
this.x = x;
this.y = y;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.fillRect(x, y, w, h);
}
}
class MovingRec extends JComponent {
int x, y;
int w = 20, h = 20;
public MovingRec (int x, int y){
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
g2d.fillRect(x, y, w, h);
}
public void update() {
x += 5;
y += 5;
}
}
and now I have problems with points 3 and 4, because I can't place black rectangles on background and moving rectangles on the top.
I will be grateful for all help :)
You do not need to (and shouldn’t) extend BlackRect and MovingRect from JComponent.
For example, BlackRect could be a simple object, like:
class BlackRect {
int x, y;
int w = 100, h = 100;
public BlackRect(int x, int y) {
this.x = x;
this.y = y;
}
public void paint(Graphics2D g2d) {
g2d.setColor(Color.BLACK);
g2d.fillRect(x, y, w, h);
}
}
You should override GreenRect’s paint method, to paint rectangles on that panel:
public GreenRect extends JPanel {
// Existing members
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (BlackRect black_rect : r) {
black_rect.paint(g2d);
}
// Also paint list of moving rectangles here
}
}
When GreenRect.repaint() is called, it will paint its background, and all rectangles from the r (and m list when you add that code). If the m rectangles have had their positions updated, they will be drawn at their new positions, so they will appear to be moving. Since moving rectangles are drawn last, they would appear “on top”.
Use a Swing Timer to drive the animation. When the timer expires, it should move all of the moving rectangles slightly (ie, call MovingRec.update()), and call repaint() on GreenRect.

Can't draw more than one square in JFrame

Can't get the program to print more than one square.
My code right now
import java.awt.*;
import javax.swing.*;
public class MyApplication extends JFrame {
private static final Dimension WindowSize = new Dimension(600, 600);
private int xCord=9, yCord=32, width=80, height=80;
public MyApplication() {
//Create and set up the window
this.setTitle("Squares");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display the window centered on the screen
Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screensize.width / 2 - WindowSize.width / 2;
int y = screensize.height / 2 - WindowSize.height / 2;
setBounds(x, y, WindowSize.width, WindowSize.height);
setVisible(true);
}
public static void main(String args[]) {
MyApplication window = new MyApplication();
}
public void paint(Graphics g) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(Color.getHSBColor(red, green, blue));
g.fillRect(xCord, yCord, width, height);
while((yCord+height)<600){
if((xCord+width)>600){
xCord=9;
yCord+=80;
}
else xCord+=80;
repaint();
}
}
}
I'm trying to fill a 600x600 window with squares of different colours that go to a new line once a row is full.
First of all, don't.
Don't override paint of top level containers, like JFrame.
JFrame is a composite component, meaning that they're a number of layers between its surface and the user and because of the way the paint system works, these can be painted independent of the frame, which can produce weird results.
Top level containers are not double buffered, meaning your updates will flash.
DO call a paint methods super method, unless you are absolutely sure you know what you're doing.
Start by taking a look at Performing Custom Painting and Painting in AWT and Swing for more details about how painting works in Swing and how you should work with it.
This...
Dimension screensize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screensize.width / 2 - WindowSize.width / 2;
int y = screensize.height / 2 - WindowSize.height / 2;
setBounds(x, y, WindowSize.width, WindowSize.height);
is a bad idea on a number of levels.
Toolkit#getScreenSize does not take into consideration the size of other UI elements which will reduce the available viewable area available on the screen, things like the taskbar/dock or menu bar on some OS
Using setBounds(x, y, WindowSize.width, WindowSize.height); on a window based class is also a bad idea, as the avaliable viewable area is the window size MINUS the window's decorations, meaning the actually viewable area is smaller then you have specified and because you're painting directly to the frame, you run the risk of painting under the frame decorations.
You can have a look at How can I set in the midst? for more details
One thing you should now about painting, painting is destructive, that is, each time a paint cycle occurs, you are expected to completely repaint the current state of the component.
Currently, this...
public void paint(Graphics g) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(Color.getHSBColor(red, green, blue));
g.fillRect(xCord, yCord, width, height);
while ((yCord + height) < 600) {
if ((xCord + width) > 600) {
xCord = 9;
yCord += 80;
} else {
xCord += 80;
}
repaint();
}
}
will only paint a single rectangle, base on the last value of xCord and yCord most likely AFTER the paint method has exited.
Swing uses a passive rendering engine, meaning that the system will make determinations about what to paint and when, you don't control it. You can make a "request" to the system through the use repaint, but it's up to the system to decide when and what will get painted, this means that multiple requests can be optimised down to a single paint pass.
Also, painting should do nothing more than paint the current state. It should avoid changing the state, directly or indirectly, especially if that change triggers a new paint pass, as this can suddenly reduce the performance of your program to 0, crippling it.
So, what's the answer?
Well, change everything...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyApplication {
public static void main(String[] args) {
new MyApplication();
}
public MyApplication() {
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("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
private static final Dimension DESIRED_SIZE = new Dimension(600, 600);
private int width = 80, height = 80;
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return DESIRED_SIZE;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int xCord = 0, yCord = 0;
while ((yCord) < getHeight()) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g2d.setColor(Color.getHSBColor(red, green, blue));
g2d.fillRect(xCord, yCord, width, height);
if ((xCord + width) > getWidth()) {
xCord = 0;
yCord += 80;
} else {
xCord += 80;
}
}
g2d.dispose();
}
}
}
Break down...
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
This creates an instance of Jframe, you don't really want extend from JFrame, you're not adding any new functionality to the class
frame.pack() is packing the window around the content, this ensures that the frame is always larger (by the amount of the frame decorations) then the desired content size
frame.setLocationRelativeTo(null); will centre the window in a system independent manner.
Next...
private static final Dimension DESIRED_SIZE = new Dimension(600, 600);
private int width = 80, height = 80;
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return DESIRED_SIZE;
}
I've used DESIRED_SIZE to provide a sizing hint to the parent containers layout manager.
Finally...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int xCord = 0, yCord = 0;
while ((yCord) < getHeight()) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g2d.setColor(Color.getHSBColor(red, green, blue));
g2d.fillRect(xCord, yCord, width, height);
if ((xCord + width) > getWidth()) {
xCord = 0;
yCord += 80;
} else {
xCord += 80;
}
}
g2d.dispose();
}
Note here, I've changed the xCord and yCord positions to zero, I no longer need to "guess" at the frame decorations. As well as making the local variables, so that when ever the method is called again, the values are reset to zero.
You don't "have" to cast the Graphics reference to Graphics2D, but Graphics2D is a more powerful API. I also like to copy it's state, but that's me, your code is simple enough so it's unlikely to have adverse effects on anything else that might be painted after your component.
Notice also, I've use getWidth and getHeight instead of "magic numbers", meaning you can resize the window and the painting will adapt.
You could try placing the whole paint mechanism inside your loop to get it done with in a one call. Therefore you wont need to call repaint inside the paint method itself:
public void paint(Graphics g) {
while((yCord+height)<600){
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
g.setColor(Color.getHSBColor(red, green, blue));
g.fillRect(xCord, yCord, width, height);
if((xCord+width)>600){
xCord=9;
yCord+=80;
}
else xCord+=80;
}
}

Java Swing - draw consecutive rectangles after clicking a button

I want to draw a rectangle after pressing a button. When I press for the first time the button it draws a rectangle. I'm trying to draw more rectangles adjacent to the first one after pressing the button again, but nothing is drawn. Can anybody help me?
This is the code that I use. Thank you very much
class Coord{
int x = 0;
int y = 0;
}
public class DrawRectangle extends JPanel {
int x, y, width, height;
public DrawRectangle (int x, int y, int width, int height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public Dimension getPreferredSize()
{
return new Dimension(this.width, this.height);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
g2.fillRect(this.x, this.y, this.width, this.height);
}
public static void main(String[] args)
{
final Coord coord = new Coord();
final JPanel center = new JPanel();
center.setLayout(null);
center.setLocation(10, 10);
center.setSize(300, 300);
JButton button = new JButton("Button");
button.setBounds(350,200,75,50);
button.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
DrawRectangle component = new DrawRectangle(coord.x, coord.y, 30, 30);
component.setLocation(coord.x, coord.y);
component.setSize(component.getPreferredSize());
center.add(component);
center.repaint();
coord.x += 30;
coord.y +=30;
}
});
JFrame frame = new JFrame();
frame.setLayout(null);
frame.add(center);
frame.add(button);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Your paintComponent() only ever draws a single rectangle. It clears the background of the panel and then draws the rectangle.
If you want multiple rectangles then you need to either:
Keep a List of Rectangle to draw and then iterate through the List each time and draw the rectangle
Draw each rectangle onto a BufferedImage and then just paint the BufferedImage.
Check out Custom Painting Approaches for working examples of both of these approaches. Try both to see which you prefer better.

Categories

Resources