Draw custom stuff on top of opaque components in a JPanel - swing

I have an JPanel populated with several opaque custom components. Now I would like to draw something on top of these components by overriding the paintComponent() method. My problem is that the painted stuff is placed behind the embedded components and, as they are opaque, is covered by them.
Is there any way to let the painting appear on top of the components?
Here's a short example of what I'm trying to do:
public class DrawOnTop {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Draw on top");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
});
}
}
class MyPanel extends JPanel {
public MyPanel() {
setLayout(new BorderLayout(3, 3));
add(new JButton("Button 1"), BorderLayout.NORTH);
add(new JButton("Button 2"), BorderLayout.CENTER);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawLine(0, 0, getVisibleRect().width, getVisibleRect().height);
}
}

You were thinking along the right lines.
Only problem was that you should have Overridden the paintChildren() method like in the code below. This is because the paintComponent() method is called as first and does the background etc painting of the component itself (the MyPanel), then is called paintBorders() and lastly the paintChildren() which paints all that is inside of the component calling it.
public class DrawOnTop {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Draw on top");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
});
}
}
class MyPanel extends JPanel {
public MyPanel() {
setLayout(new BorderLayout(3, 3));
JButton b1 = new JButton("Button 1");
MouseListener ml = new MouseAdapter() {
#Override
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
MyPanel.this.repaint();
}
};
b1.addMouseListener(ml);
JButton b2 = new JButton("Button 2");
b2.addMouseListener(ml);
add(b1, BorderLayout.NORTH);
add(b2, BorderLayout.CENTER);
}
#Override
protected void paintChildren(Graphics g) {
super.paintChildren(g);
g.setColor(Color.red);
g.drawLine(0, 0, getVisibleRect().width, getVisibleRect().height);
}
}
Important to notice, in the code sample, that I added also a MouseListener to repaint the panel when a mouse exits a button, otherwise the buttons would always stay over the line once mouse enters over one of them.
But if you want to have a custom painting that is always on top of your components then I would suggest to use a glass pane. Examples of a glass pane use are provided here:
Simple one.
A more complex one.

Related

Adding another movable image in Swing

I have stumpled upon a problem. What I'm trying to do is to add another movable image in JPanel, movable as in that one could drag it with the mouse. This program only can view one image at the time and drag it arround. So how could I do to have more than one picture in my program?
=)
Here is my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
public class test2 {
public static void main(String[] args) {
new test2();
}
public test2() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
Bild bild = new Bild();
frame.add(new DragMyIcon("katt.gif"));
frame.setSize(640,460);
frame.setVisible(true);
}
});
}
protected class DragMyIcon extends JPanel {
public static final long serialVersionUID = 172L;
private JLabel label;
public DragMyIcon(String path) {
setLayout(null);
ImageIcon icon = null;
icon = new ImageIcon(path);
label = new JLabel(icon);
label.setBounds(0,0,icon.getIconWidth(), icon.getIconHeight());
setBounds(0,0,icon.getIconWidth(), icon.getIconHeight());
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
add(label);
MouseHandler handler = new MouseHandler();
label.addMouseListener(handler);
label.addMouseMotionListener(handler);
}
}
protected class MouseHandler extends MouseAdapter {
private boolean active = false;
private int xDisp;
private int yDisp;
#Override
public void mousePressed(MouseEvent e) {
active = true;
JLabel label = (JLabel) e.getComponent();
xDisp = e.getPoint().x - label.getLocation().x;
yDisp = e.getPoint().y - label.getLocation().y;
label.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
#Override
public void mouseReleased(MouseEvent e) {
active = false;
JLabel label = (JLabel) e.getComponent();
label.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mouseDragged(MouseEvent e) {
if (active) {
JLabel label = (JLabel) e.getComponent();
Point point = e.getPoint();
label.setLocation(point.x - xDisp, point.y - yDisp);
label.invalidate();
label.repaint();
}
}
#Override
public void mouseMoved(MouseEvent e) {
}
}}
What I'm trying to do is to add another movable image in JPanel,
Where? I don't see any code?
You only add a single label to the panel. If you want to drag more than one then you need to add more than one label to the panel.
This program only can view one image at the time and drag it arround.
Well maybe you need a method like addImage(Image image, int x, int y). Then when you invoke this method you:
create a JLabel using the image for the Icon
set the bounds of the label using the x/y and the image size
add the listeners to the label
add the label to the panel

NullPointerException at java.awt.Window.access$700(Window.java:132) while painting JPanel

I'm trying to paint component inside paint(Graphics) method of JPanel.
The following code snippet works just fine, a JButton is painted nicely in my JPanel:
#Override
public void paint(Graphics g) {
super.paint(g);
JButton btn = new JButton("hello");
Dimension dim = btn.getPreferredSize();
btn.setSize(dim.width, dim.height);
btn.paint(g); // paint the button
}
The code snippet works perfectly also for other components (JLabel, JTree, ...) except JPanel.
The following code will cause very strange NullPointerException at java.awt.Window.access$700(Window.java:132).
#Override
public void paint(Graphics g) {
super.paint(g);
JPanel panel = new JPanel();
panel.setSize(10, 10);
panel.paint(g); // paint the panel
}
Here the full stacktrace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.awt.Window.access$700(Window.java:132)
at java.awt.Window$1.isOpaque(Window.java:3458)
at javax.swing.RepaintManager.getVolatileOffscreenBuffer(RepaintManager.java:983)
at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1395)
at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:294)
at javax.swing.RepaintManager.paint(RepaintManager.java:1224)
at javax.swing.JComponent.paint(JComponent.java:1015)
at test.paintcontainer.TestPaintContainerMain$TestContentPane.paint(TestPaintContainerMain.java:48)
at javax.swing.JComponent.paintChildren(JComponent.java:862)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:567)
at javax.swing.JComponent.paintChildren(JComponent.java:862)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5131)
at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:278)
at javax.swing.RepaintManager.paint(RepaintManager.java:1224)
at javax.swing.JComponent.paint(JComponent.java:1015)
at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
at java.awt.Container.paint(Container.java:1780)
at java.awt.Window.paint(Window.java:3375)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:796)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:713)
at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:693)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:125)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Any idea how to solve this problem? I need to paint JPanel inside paint(Graphics) method.
I wrote a simple test application which you can copy-paste to reproduce the aforementioned exception:
package test.paintcontainer;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class TestPaintContainerMain extends JFrame {
public static void main(String[] args) {
TestPaintContainerMain test = new TestPaintContainerMain();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setBounds(0, 0, 300, 200);
test.setContentPane(new TestContentPane());
test.setVisible(true);
}
static class TestContentPane extends JPanel {
JRadioButton paintButtonCheck;
JRadioButton paintPanelCheck;
public TestContentPane() {
paintButtonCheck = createRadioButton("paint button", true);
paintPanelCheck = createRadioButton("paint panel", false);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(paintButtonCheck);
buttonGroup.add(paintPanelCheck);
add(paintButtonCheck);
add(paintPanelCheck);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.translate(100, 100);
if (paintButtonCheck.isSelected()) {
createButton().paint(g);
} else {
createPanel().paint(g);
}
}
private JButton createButton() {
JButton button = new JButton("button");
button.setSize(button.getPreferredSize().width, button.getPreferredSize().height);
return button;
}
private JPanel createPanel() {
JPanel panel = new JPanel();
panel.setBackground(Color.GREEN);
panel.add(createButton());
panel.setSize(panel.getPreferredSize().width, panel.getPreferredSize().height);
return panel;
}
private JRadioButton createRadioButton(String title, boolean selected) {
JRadioButton radio = new JRadioButton(title, selected);
radio.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TestContentPane.this.repaint();
}
});
return radio;
}
}
}
This is most likely not a bug in Swing, but more of a problem because you are trying to paint a component which has not yet been realized, meaning it has no active graphic context. You can realize a component by adding it to already realized component like your JFrame - which itself gets realized by setVisible(true).
Also one should probably never call JComponent.paint(Graphics) manually, because this is the job of Swing (more precisely the Event Dispatcher Thread) - it even says so in the documentation of the paint method:
Applications should not invoke paint directly, but should instead use the repaint method to schedule the component for redrawing.
What you can call is the method printAll(Graphics g), which paints the component and all its subcomponents. Also in Swing one should also not override paint but paintComponent.
So here is a test code:
JButton button = createButton();
JPanel panel = createPanel();
public TestContentPane() {
paintButtonCheck = createRadioButton("paint button", true);
paintPanelCheck = createRadioButton("paint panel", false);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(paintButtonCheck);
buttonGroup.add(paintPanelCheck);
add(paintButtonCheck);
add(paintPanelCheck);
//Hack, just prove something (realize both components)
add(panel);
add(button);
}
...
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.translate(100, 100);
if (paintButtonCheck.isSelected()) {
button.paintAll(g);
} else {
panel.paintAll(g);
}
g.translate(-100, -100);
}
This should work (although you will obviously have two components on the screen you don't want). Also note "reset" the graphics object, because it will still be used afterwards by Swing.
So this is the theory, but it's not yet an actual solution.
My solution to your problem is: "Don't do it like this"!
Components are not like images, in the sense that they don't look the same everywhere. The output of the paintAll call will be different, depending on how (or where) the components were realized.
So one suggestion is to show actual components. Create your tooltip box, add your panel and your button and let them draw themselves. You can even subclass these components and override their paintComponent() methods, add transparency and all. It will require some work, but Swing was never known to be easy.
I just found a solution.
The only modification of a sample code from my question is that called panel.setDoubleBuffered(false) on JPanel I was trying to paint.
However, I would still consider the exeption to be a Swing bug. If double buffering should be turned off by design you shouldn't get NullPointerException but some other, more meaningful exception which explains the condition.
Here is a fixed sample application:
package test.paintcontainer;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class TestPaintContainerMain extends JFrame {
public static void main(String[] args) {
TestPaintContainerMain test = new TestPaintContainerMain();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setBounds(0, 0, 300, 200);
test.setContentPane(new TestContentPane());
test.setVisible(true);
}
static class TestContentPane extends JPanel {
JRadioButton paintButtonCheck;
JRadioButton paintPanelCheck;
public TestContentPane() {
paintButtonCheck = createRadioButton("paint button", false);
paintPanelCheck = createRadioButton("paint panel", true);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(paintButtonCheck);
buttonGroup.add(paintPanelCheck);
add(paintButtonCheck);
add(paintPanelCheck);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.translate(100, 100);
if (paintButtonCheck.isSelected()) {
createButton().paint(g);
} else {
createPanel().paint(g);
}
}
private JButton createButton() {
JButton button = new JButton("button");
button.setSize(button.getPreferredSize().width, button.getPreferredSize().height);
return button;
}
private JPanel createPanel() {
JPanel panel = new JPanel();
panel.setBackground(Color.GREEN);
panel.add(createButton());
// --------------------------------
panel.setDoubleBuffered(false); // <-- TURN OFF DOUBLE BUFFERING
// --------------------------------
panel.setSize(panel.getPreferredSize().width, panel.getPreferredSize().height);
return panel;
}
private JRadioButton createRadioButton(String title, boolean selected) {
JRadioButton radio = new JRadioButton(title, selected);
radio.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TestContentPane.this.repaint();
}
});
return radio;
}
}
}

How to fit a JTable into a JPanel and make it auto resizeable?

i'm adding a JTable into a JPanel wich is using a GridLayout but i don't get the same behavior like when you add a JButton...
I want to know how can i get the same auto resizing behavior with my JTable like when you add a JButton into a JPanel that uses a GridLayout and also I want the table use the whole space of the panel.
Sorry about spelling, english is not my maternal language. Hope you guys can help me!
This is my code:
import javax.swing.*;
import java.awt.*;
class Frame extends JFrame {
private JPanel center;
private JTable table;
public Frame(){
super("Test Jtable");
this.setLayout(new BorderLayout());
this.center = new JPanel();
this.center.setLayout(new GridLayout());
this.table = new JTable(50,50);
this.table.setGridColor(Color.black);
this.table.setCellSelectionEnabled(true);
this.center.add(this.table);
this.add(this.center,BorderLayout.CENTER);
}
}
public class TestFrame {
public static void main(String... args) {
Frame f =new Frame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400,400);
f.setVisible(true);
}
}
Add your table to a scroll pane, as shown in this example.
this.center.add(new JScrollPane(this.table));
Addendum: I'd advocate something like this using pack(); other arrangements are possible, but less usable. The setPreferredScrollableViewportSize() method may be helpful, too.
import javax.swing.*;
import java.awt.*;
class Frame extends JFrame {
private JPanel center;
private JTable table;
public Frame() {
super("Test Jtable");
this.setLayout(new BorderLayout());
this.center = new JPanel();
this.center.setLayout(new GridLayout());
this.table = new JTable(50, 10);
this.table.setGridColor(Color.black);
this.table.setCellSelectionEnabled(true);
this.center.add(this.table);
this.add(new JScrollPane(this.center), BorderLayout.CENTER);
}
}
public class TestFrame {
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Frame f = new Frame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
});
}

JPopupMenu doesn't dissapear/move when minimising/moving the JFrame it is in

I am making an mp3 player, with several JLists in my JFrame. When I right click on a JList item, a popup with some options for that song appears. But when this popup is visible, and I minimise my JFrame, this popup stays visible! Also, when the popup is visible, and I drag my JFrame to somewhere else on the screen, the popup stays on it's original position (so it does not stay on the same position relative to the JFrame)... Can someone please help me out with this? I tried to strip down this class as much as possible :)
I would be really grateful if someone could help me out !!
Joe
public class playListPanel extends JPanel implements MouseListener {
private DefaultListModel model;
private Interface interFace;
private JList list;
private boolean emptyPlaylist;
private ArrayList<Song> currentPlayList;
private Song rightClickedSong;
private JPopupMenu popup;
private Point panelLocation;
public playListPanel(Interface interFace) // Interface extends JFrame,
// playListPanel is a part of
// this JFrame.
{
this.interFace = interFace;
this.panelLocation = new Point(559, 146);
setBackground(SystemColor.controlHighlight);
setBorder(new TitledBorder(null, "", TitledBorder.LEADING,
TitledBorder.TOP, null, null));
setBounds((int) panelLocation.getX(), (int) panelLocation.getY(), 698,
368);
setLayout(null);
currentPlayList = new ArrayList<Song>();
model = new DefaultListModel();
list = new JList(model);
list.setVisible(true);
list.addMouseListener(this);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setBounds(5, 5, 688, 357);
add(scrollPane);
emptyPlaylist = true;
}
private void openMenuPopup(Point point)
{
removePopup();
popup = new JPopupMenu();
int x = (int) point.getX();
int y = (int) point.getY();
popup.setLocation((int) (x+panelLocation.getX()),(int) (y+panelLocation.getY()));
//popup.setLabel("popup voor playlist");
JMenuItem removeSong;
popup.add(removeSong = new JMenuItem("Remove Song from Playlist", new ImageIcon("image.jpg")));
ActionListener menuListener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(event.getActionCommand().equals("Remove Song from Playlist"))
{
System.out.println("Remove Song from Playlist");
interFace.getPlaylistManager().removeOneSong(rightClickedSong);
removePopup();
}
};
//ADD THE LISTENERS TO THE MENU ITEMS
removeSong.addActionListener(menuListener);
popup.setVisible(true);
}
public void removePopup()
{
if(popup!==null)
{
popup.setVisible(false);
System.out.println("popup removed");
}
}
private int getRow(Point point) {
return list.locationToIndex(point);
}
public void refreshPlayList(ArrayList<Song> playlist) {
this.currentPlayList = playlist;
model.clear();
for (Song song : playlist) {
model.add(model.getSize(), song.getPlaylistString());
}
list.setVisible(true);
}
public void highlightSong(int index) {
list.setSelectedIndex(index);
}
public int getRowOfList(Point point) {
return list.locationToIndex(point);
}
#Override
public void mouseClicked(MouseEvent e) {
interFace.getPlaylistManager().doubleClickOnPlaylist(e);
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
rightClickedSong = currentPlayList.get(getRow(e.getPoint()));
openMenuPopup(e.getPoint());
System.out.println("should open popup at "
+ e.getPoint().toString());
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
There are some basic flaws in the way you are handling click for showing popup.
It is not advisable to call popup.setVisible in simple scenarios like this. Instead, you may rely on its default behavior. Also, better to use e.isPopupTrigger() than to check SwingUtilities.isRightMouseButton(e) to show popup.
You may do something like the following :
//at classlevel,
private JPopupMenu popup = new JPopupMenu();
//create a Popuplistener
PopupListener pl = new PopupListener();
list.addMouseListener(pl);
//Implementation of your popuplistener
class PopupListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger())
//e.getSource - and construct your popup as required.
//and then.
popup.show(((JApplet) e.getComponent()).getContentPane(), e
.getX(), e.getY());
}
}

Creating glasspane

I have a question. Can I create glasspane in body MousePressed ? If yes anyone can write me how? I mean that I press mouse button and glass pane is visible and I can painting on him.
EDIT
Ok I have now what I want. My glass pane is creating when I click mouse button and disapear when I release this button. Now I have another question. Where I should create my painting method. I want draw rectangle on this glasss pane using mouse dragged. Where I must implement paint method? In other class or in this events? I implement one my try paint function but I don't know if this is good way. This is my code:
public class Selection extends JPanel
{
static Point startPoint;
public static void GUI()
{
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Select");
final JPanel glassPane = new JPanel();
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.add(button);
glassPane.setOpaque(false);
frame.add(panel);
frame.setGlassPane(glassPane);
glassPane.addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
System.out.println("f.getGlassPane() mousePressed");
if(e.getButton() == MouseEvent.BUTTON1)
frame.getGlassPane().setVisible(true);
startPoint=e.getPoint();
Graphics2D g = null;
Graphics2D g2 = (Graphics2D) g;
Rectangle2D rect = new Rectangle2D.Double();
rect.setFrameFromDiagonal(e.getPoint().x, e.getPoint().y,startPoint.x, startPoint.y);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5F));
g2.setColor(Color.BLUE);
g2.fill(rect);
g2.draw(rect);
}
});
glassPane.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e)
{
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
});
frame.addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
if(e.getButton() == MouseEvent.BUTTON1)
frame.getGlassPane().setVisible(true);
}
public void mouseReleased(MouseEvent e)
{
frame.getGlassPane().setVisible(false);
}
});
frame.setVisible(true);
}
int x1, x2, y1,y2;
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.drawRect(x1,y1, x2, y2);
}
public static void main(String[] args)
{
GUI();
}
}
Hi please check out my answer to some other question where I present a way in which a glass pane can be used to simulated dialog behaviour. There you have shown how to show it and hide it on mouse click in my case right mouse click. This example should get you started nicely.
I see no problem creating a glasspane and attaching it to a RootPaneContainer from inside moussePressed() method.
However, I may wonder why create a new glass pane every time the user clicks the mouse; that wouldn't be very performant; it is probably wiser to create and attach a glass pane up front and then change its content during mouse click).
Now, regarding "painting on the glass pane", it depends on what you mean by "painting", if this means using a "Graphics" instance to directly draw on the glass pane, the answer is NO (well, actually you could but, your painting would disappear at first UI refresh...)
Such painting must occur in paintComponent() method of your glass pane (that you must override).