How to define which button is pressed using MouseEvent - java

Idea of this app is to draw a shape on JPanel. First you would need to choose a shape by clicking a button and then click somewhere on the panel to draw it by using one MouseListener, but I can't figure out how to implement which button is activated after I click it. I tried using getSource(), but it doesn't seem to work. Here's the code:
public class Draw extends JFrame {
private JPanel contentPane;
private Point startPoint = null, endPoint = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Draw frame = new Draw();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Draw() {
getContentPane().setLayout(new BorderLayout(0, 0));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
final PnlDrawing pnldrawing = new PnlDrawing();
contentPane.add(pnldrawing, BorderLayout.CENTER);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
JSeparator separator = new JSeparator();
separator.setOrientation(SwingConstants.VERTICAL);
panel.add(separator);
JButton btnSelect = new JButton("Select");
panel.add(btnSelect);
JButton btnModify = new JButton("Modify");
panel.add(btnModify);
JButton btnRemove = new JButton("Remove");
panel.add(btnRemove);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.NORTH);
final JButton btnAddPoint = new JButton("Add Point");
panel_1.add(btnAddPoint);
final JButton btnAddLine = new JButton("Add Line");
panel_1.add(btnAddLine);
final JButton btnAddCircle = new JButton("Add Circle");
panel_1.add(btnAddCircle);
final JButton btnAddDonut = new JButton("Add Donut");
panel_1.add(btnAddDonut);
final JButton btnAddRectangle = new JButton("Add Rectangle");
panel_1.add(btnAddRectangle);
pnldrawing.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if(e.getSource().equals(btnAddPoint)) {
pnldrawing.shapes.add(new Point(e.getX(), e.getY()));
pnldrawing.repaint();
}
if(e.getSource().equals(btnAddLine)) {
if (startPoint == null)
{
startPoint = new Point(e.getX(),e.getY());
}
else if(endPoint == null)
{
endPoint = new Point(e.getX(),e.getY());
}
if (startPoint != null && endPoint != null)
{
Line line = new Line(startPoint,endPoint);
pnldrawing.shapes.add(line);
pnldrawing.repaint();
startPoint = null;
endPoint = null;
}
}
if(e.getSource().equals(btnAddCircle)) {
DlgCircle drawCircle = new DlgCircle();
drawCircle.setVisible(true);
Point center = new Point(e.getX(),e.getY());
if (drawCircle.isOk)
{
pnldrawing.shapes.add(new Circle(center,Integer.parseInt(drawCircle.txtCircle.getText())));
pnldrawing.repaint();
}
}
if(e.getSource().equals(btnAddDonut)) {
DlgDonut drawDonut = new DlgDonut();
drawDonut.setVisible(true);
Point center = new Point(e.getX(),e.getY());
if (drawDonut.isOk)
{
pnldrawing.shapes.add(new Donut(center,Integer.parseInt(drawDonut.txtRadius.getText()),Integer.parseInt(drawDonut.txtInner.getText())));
pnldrawing.repaint();
}
}
if(e.getSource().equals(btnAddRectangle)) {
DlgRectangleSec drawRect = new DlgRectangleSec();
drawRect.setVisible(true);
Point upperLeft = new Point(e.getX(),e.getY());
if(drawRect.isOk) {
pnldrawing.shapes.add(new Rectangle(upperLeft,Integer.parseInt(drawRect.txtWidth.getText()),Integer.parseInt(drawRect.txtHeight.getText())));
pnldrawing.repaint();
}
}
}
});
}
}
Here's the GUI

First of all you might want to change your painting logic to make it more user friendly. That is you could:
Use the mousePressed event to save the mouse point.
Add logic in the mouseDragged event to paint the shape as the mouse is being dragged.
Finally, in the mouseReleased event you would make the drawing shape permanent.
Check out Custom Painting Approaches for working example. It only paints rectangle, but it should give you a starting point.
but I can't figure out how to implement which button is activated
Use JRadioButton instead of JButton. The button will remain selected.
Then the logic in your MouseListener code becomes something like:
if (addLineButton.isSelected())
// do something
else if (addRectangleButton.isSelected())
// do something

Am I correct that you want to get the button pressed on the mouse? If so, take a look at this link to specify actions done by a certain click. Then you can set a String variable to what button was clicked like String buttonclicked = “left click”.
Right click mouse event

Related

Button not displaying frame connected to it

I am trying to write code for an application I'm making, I have my main frame with 6 buttons on them. When I push one of my buttons, it is meant to bring up a frame that has a tabbed layout set up.
I have the tabbed frame coded correctly and when I set each frame as visible they will appear to screen but they don't appear when the button is pushed.
I have action listeners connected to the buttons and the frames I want to connect with them as well as constructors but for some reason I can't get my code to work correctly.
I have added my driver and my first two forms I'm trying to connect to each other.
public class SimpsonsDriver {
//#param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame simpsonFrame = new JFrame("The Simpson");
JFrame homerFrame = new JFrame ("Homer Simpson");
JFrame margeFrame = new JFrame ("Marge Simpson");
JFrame bartFrame = new JFrame ("Bart Simpson");
JFrame lisaFrame = new JFrame("Lisa Simpson");
JFrame maggieFrame = new JFrame("Maggie Simpson");
SimpsonForm simpsonForm = new SimpsonForm(simpsonFrame, homerFrame, margeFrame, bartFrame,
lisaFrame, maggieFrame);
HomerForm homerForm = new HomerForm(homerFrame, simpsonFrame);
MargeForm margeForm = new MargeForm(margeFrame, simpsonFrame);
BartForm bartForm = new BartForm(bartFrame, simpsonFrame);
LisaForm lisaForm = new LisaForm(lisaFrame, simpsonFrame);
MaggieForm maggieForm = new MaggieForm(maggieFrame, simpsonFrame);
}
}
public class SimpsonForm implements ActionListener{
JFrame simpsonFrame, homerFrame, margeFrame, bartFrame, lisaFrame, maggieFrame;//instance variables
JButton homerBtn, margeBtn, bartBtn, lisaBtn, maggieBtn, closeBtn; //instance variables
public SimpsonForm(JFrame simpsonFrame, JFrame homerFrame, JFrame margeFrame, JFrame bartFrame, JFrame lisaFrame, JFrame maggieFrame) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
this.margeFrame = margeFrame;
this.bartFrame = bartFrame;
this.lisaFrame = lisaFrame;
this.maggieFrame = maggieFrame;
simpsonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createPanel();
}//end constructor method SimpsonForm
private void createPanel(){
homerBtn = new JButton ("Homer");
margeBtn = new JButton ("Marge");
bartBtn = new JButton ("Bart");
lisaBtn = new JButton ("Lisa");
maggieBtn = new JButton ("Maggie");
closeBtn = new JButton ("Close");
FlowLayout flow = new FlowLayout();
JPanel p1 = new JPanel();
p1.setLayout(flow);
JPanel p2 = new JPanel();
p2.setLayout(flow);
ImageIcon img = new ImageIcon(this.getClass().getResource("simpsons.png"));
JLabel imgLabel = new JLabel();
imgLabel.setIcon(img);
imgLabel.setBounds(10, 10, img.getIconWidth(), img.getIconHeight());
p1.add(imgLabel);
p2.add(homerBtn);
homerBtn.addActionListener(this);
p2.add(margeBtn);
margeBtn.addActionListener(this);
p2.add(bartBtn);
bartBtn.addActionListener(this);
p2.add(lisaBtn);
lisaBtn.addActionListener(this);
p2.add(maggieBtn);
maggieBtn.addActionListener(this);
p2.add(closeBtn);
closeBtn.addActionListener(this);
simpsonFrame.setLayout(new BorderLayout());
simpsonFrame.setResizable(false);
simpsonFrame.add(p1, BorderLayout.BEFORE_FIRST_LINE);
simpsonFrame.add(p2, BorderLayout.CENTER);
simpsonFrame.setSize(425, 425);
simpsonFrame.setLocationRelativeTo(null);
simpsonFrame.setVisible(true);
}//end method createPanel
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == homerBtn) {
homerFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == margeBtn) {
margeFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == bartBtn) {
bartFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == lisaBtn) {
lisaFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == maggieBtn) {
maggieFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == closeBtn) {
System.exit(0);
}//end if
}//end event handler
}
public class HomerForm implements ActionListener{
JFrame simpsonFrame, homerFrame;
JButton closeBtn;
public HomerForm(JFrame simpsonFrame, JFrame homerFrame ) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
createPanel();
}
private void createPanel() {
homerFrame = new JFrame("Homer Simpson");
closeBtn = new JButton("Close");
closeBtn.setSize(200, 50);
ImageIcon ogImage = new ImageIcon(this.getClass().getResource("/homer1.png"));
JLabel ogLabel = new JLabel();
ogLabel.setIcon(ogImage);
JPanel p1 = new JPanel();
p1.add(ogLabel);
ImageIcon hwImage = new ImageIcon(this.getClass().getResource("/homer2.png"));
JLabel hwLabel = new JLabel();
hwLabel.setIcon(hwImage);
JPanel p2 = new JPanel();
p2.add(hwLabel);
ImageIcon cImage = new ImageIcon(this.getClass().getResource("/homer3.png"));
JLabel cLabel = new JLabel();
cLabel.setIcon(cImage);
JPanel p3 = new JPanel();
p3.add(cLabel);
JPanel p4 = new JPanel();
JTabbedPane tab = new JTabbedPane();
tab.setBounds(100, 100, 300, 300);
tab.add("Original", p1);
tab.add("HalfWay", p2);
tab.add("Current", p3);
tab.add("Close", p4);
p4.add(closeBtn);
closeBtn.setLayout(new BorderLayout());
closeBtn.addActionListener(this);
homerFrame.add(tab);
homerFrame.setResizable(false);
homerFrame.setSize(500, 500);
homerFrame.setLocationRelativeTo(null);
homerFrame.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == closeBtn) {
homerFrame.setVisible(false);
simpsonFrame.setVisible(true);
}//end if
else
{
System.exit(0);
}
}
}
When i run it, i get this image. simpsonsFrame
this is what happens when i click the homer button i then have to max it to see a blank screen.homerFrame.
when i set the homerFrame to visible, it displays what i what to appear if the button was pushed.it shows homerFrame then it shows the simpsonFrame.homersetVisible true

Java add a JLabel in the middle of a JButton

I would like to simply add a JLabel into a JButton and center it horizontally. I've tried many thing but the text stay left side... Here is my code :
JLabel labeltest = new JLabel("Simple test");
JButton myButton = new JButton();
myButton.setHorizontalTextPosition(SwingConstants.CENTER);
myButton.add(labeltest);
Create an Icon of the text and give the Icon the foreground/background colors that you want.
I tried this but the problem comes when I had to do button.setenabled(false); after this the text becomes almost invisible
You can set the disabled Icon to be the same as the Icon and it will not be painted in the disabled state:
JButton button = new JButton( new ImageIcon(...) );
button.setDisabledIcon( button.getIcon() );
button.setEnabled(false);
Of course the problem with this approach is that the user doesn't know the button is disabled. So in reality you would need 2 icons:
one for the normal state
one for the disabled state
A JButton is also a java.awt.Container. Thus you can set a layout manager. E.g. you can use a GridBagLayout.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JToggleButton toggleButton = new JToggleButton();
JLabel jLabel = new JLabel("3");
JToggleButton.ToggleButtonModel toggleButtonModel = (JToggleButton.ToggleButtonModel) toggleButton.getModel()
ToggleForegroundAction toggleForegroundAction =
new ToggleForegroundAction(toggleButtonModel, Color.WHITE, Color.RED);
toggleForegroundAction.setComponent(jLabel);
toggleButton.setAction(toggleForegroundAction);
toggleButton.setLayout(new GridBagLayout());
toggleButton.add(jLabel, new GridBagConstraints());
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
panel.setLayout(new BorderLayout());
panel.add(toggleButton, BorderLayout.CENTER);
Container contentPane = frame.getContentPane();
contentPane.add(panel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
An action that toggles the label's foreground color might look like this
public class ToggleForegroundAction extends AbstractAction {
private JComponent component;
private JToggleButton.ToggleButtonModel toggleButtonModel;
private final Color selectedColor;
private final Color unselectedColor;
public ToggleForegroundAction(JToggleButton.ToggleButtonModel toggleButtonModel, Color selectedColor, Color unselectedColor) {
this.toggleButtonModel = toggleButtonModel;
this.selectedColor = selectedColor;
this.unselectedColor = unselectedColor;
}
public void setComponent(JComponent component) {
this.component = component;
setForeground(component, toggleButtonModel.isSelected());
}
#Override
public void actionPerformed(ActionEvent e) {
JComponent targetComponent = this.component;
if (targetComponent == null) {
targetComponent = (JComponent) e.getSource();
}
setForeground(targetComponent, toggleButtonModel.isSelected());
}
private void setForeground(JComponent targetComponent, boolean isSelected) {
Color foreground;
if (isSelected) {
foreground = selectedColor;
} else {
foreground = unselectedColor;
}
targetComponent.setForeground(foreground);
}
}
=>

Have some problems with my revalidate/repaint

i tried to fix it with revalidate() & repaint() but it didn't work out for me, i searched for some more solutions, but everytime i try it doesn't work for me, could anyone help me please?
thanks alot,
Here is my script (not full)
public JPanel createPanel() throws SQLException, ClassNotFoundException
{
FormLayout formlayout1 = new
FormLayout("FILL:DEFAULT:NONE,FILL:119PX:NONE,
FILL:30PX:NONE,FILL:24PX:NONE,FILL:130PX:NONE,
FILL:16PX:NONE","CENTER:DEFAULT:NONE,CENTER:30PX:NONE,
CENTER:30PX:NONE,CENTER:25PX:NONE,CENTER:25PX:NONE,
CENTER:25PX:NONE,CENTER:25PX:NONE,CENTER:25PX:NONE");
CellConstraints cc = new CellConstraints();
jpanel1.setLayout(formlayout1);
JLabel lbl = null;
JTextArea col = null;
int i = 3;
for (OverzichtVo o : OverzichtBusiness.getOverzicht()){
lbl = new JLabel(mapServices.get(o.getServiceid()));
jpanel1.add(lbl, cc.xy(2, i));
col = new JTextArea();
col.setEditable(false);
LineBorder lineborder1 = new LineBorder(new Color(0,0,0),2,false);
col.setBorder(lineborder1);
col.setBackground(colors[o.getStatusid()-1]);
jpanel1.add(col, cc.xy(3, i));
lbl = new JLabel(o.getExtrainfo());
jpanel1.add(lbl, cc.xy(5, i));
i++;
button.setFont(new Font("Poor Richard",Font.PLAIN,20));
button.setName("button");
LineBorder lnbord = new LineBorder(new Color(0,0,0),2,false);
button.setBorder(lnbord);
refresh();
jpanel1.add(button,cc.xy(5,2));
m_lbloverzicht.setFont(new Font("Poor Richard",Font.PLAIN,30));
m_lbloverzicht.setName("lbloverzicht");
m_lbloverzicht.setText("Overzicht");
LineBorder lineborder1 = new LineBorder(new Color(0,0,0),2,false);
m_lbloverzicht.setBorder(lineborder1);
jpanel1.add(m_lbloverzicht,cc.xy(2,2));
addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6 },new int[]{ 1,2,3,4,5,6,7,8 });
return jpanel1;
}
private void refresh(){
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
jpanel1.revalidate();
jpanel1.repaint();
}
});
}
and i activate it all in another class :
public static void main(String args[]) throws SQLException, ClassNotFoundException{
JFrame frame = new JFrame();
AlgemeneFrm frm_alg = new AlgemeneFrm();
frame.add(frm_alg);
frame.setVisible(true);
frame.setSize(350,250);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
});
}
I'm trying to refresh my whole Jpanel/panel cause my Jtextarea(background) is green, when i change something it's suppose to go red. that works fine for me if i stop application and start it again, but i added a button, so i could refresh/update my application or just panel. but it won't work with my 'refresh' button within 'panelname'.revalidate();and 'panelname'.repaint();
help please

positioning jpanel at the bottom

I want to position the JPanel that contains the send button and the textfield (and right now uses a flowlayout) at the bottom of the JTextArea (The white area).
How can I achieve this?
public GUI()
{
mainWindow = new JFrame("Chat GUI");
lowerPanel = new JPanel(new FlowLayout());
usersPanel = new JPanel(new GridLayout(GRIDLAYOUT_ROWS, GRIDLAYOUT_COLS));
users = new JList(data);
usersPanel.add(users);
sendButton = new JButton("Send");
textField = new JTextField(TEXTFIELD_WIDTH);
textArea = new JTextArea(TEXTAREA_HEIGHT, TEXTAREA_WIDTH);
textArea.setEditable(false);
}
private void addButtonListener(JButton b) {
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
public void createGUI() {
addButtonListener(sendButton);
lowerPanel.add(sendButton);
lowerPanel.add(textField);
mainWindow.add(users);
mainWindow.add(textArea);
mainWindow.add(lowerPanel);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setLayout(new FlowLayout());
mainWindow.pack();
}
You Will have Layout :
this.add(buttonPanel,BorderLayout.SOUTH);
see this answer

DnD - Why is dragged label displayed below other components?

I've written a basic DnD program that has four JLabels in a row. I've noticed
that when I drag a label to the left, it is displayed below the next label. However,
when I drag the label to the right, it is displayed above the next label.
The labels are added in order, left to right. So the dragged label is being
displayed below other labels that were added before the dragged label, and displayed
above other labels that were added after the dragged label.
Can anyone explain why this happens? Can anyone offer a fix so that the dragged label
is displayed above the other labels?
Thanks.
source code:
public class LabelDnd extends JPanel {
private JLabel[] labels;
private Color[] colors = { Color.BLUE, Color.BLACK, Color.RED, Color.MAGENTA };
public LabelDnd() {
super();
this.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
this.setBackground(Color.WHITE);
this.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
JPanel basePanel = new JPanel();
basePanel.setLayout(new GridLayout(1, 4, 4, 4));
basePanel.setBackground(Color.CYAN);
MouseAdapter listener = new MouseAdapter() {
Point p = null;
#Override
public void mousePressed(MouseEvent e) {
p = e.getLocationOnScreen();
}
#Override
public void mouseDragged(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
Point l = c.getLocation();
Point here = e.getLocationOnScreen();
c.setLocation(l.x + here.x - p.x, l.y + here.y - p.y);
p = here;
}
};
this.labels = new JLabel[4];
for (int i = 0; i < this.labels.length; i++) {
this.labels[i] = new JLabel(String.valueOf(i), JLabel.CENTER);
this.labels[i].setOpaque(true);
this.labels[i].setPreferredSize(new Dimension(100, 100));
this.labels[i].setBackground(this.colors[i]);
this.labels[i].setForeground(Color.WHITE);
this.labels[i].addMouseListener(listener);
this.labels[i].addMouseMotionListener(listener);
basePanel.add(this.labels[i]);
}
this.add(basePanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("LabelDnd");
frame.getContentPane().setLayout(new BorderLayout());
LabelDnd panel = new LabelDnd();
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You are not changing the order that the labels have been added or are being painted in your code. Consider elevating the JLabel to the glasspane when dragging (after removing it from the main container), and then re-adding it to the main container on mouse release.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.*;
import java.util.Comparator;
import java.util.PriorityQueue;
import javax.swing.*;
#SuppressWarnings("serial")
public class LabelDnd extends JPanel {
private static final String X_POS = "x position";
private JLabel[] labels;
private Color[] colors = { Color.BLUE, Color.BLACK, Color.RED, Color.MAGENTA };
public LabelDnd() {
super();
// this.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
this.setBackground(Color.WHITE);
this.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
JPanel basePanel = new JPanel();
basePanel.setLayout(new GridLayout(1, 4, 4, 4));
basePanel.setBackground(Color.CYAN);
MouseAdapter listener = new MouseAdapter() {
Point loc = null;
Container parentContainer = null;
Container glasspane = null;
JLabel placeHolder = new JLabel("");
private Point glassLocOnScn;
#Override
public void mousePressed(MouseEvent e) {
JComponent selectedLabel = (JComponent) e.getSource();
loc = e.getPoint();
Point currLocOnScn = e.getLocationOnScreen();
parentContainer = selectedLabel.getParent();
JRootPane rootPane = SwingUtilities.getRootPane(selectedLabel);
glasspane = (Container) rootPane.getGlassPane();
glasspane.setVisible(true);
glasspane.setLayout(null);
glassLocOnScn = glasspane.getLocationOnScreen();
Component[] comps = parentContainer.getComponents();
// remove all labels from parent
parentContainer.removeAll();
// add labels back except for selected one
for (Component comp : comps) {
if (comp != selectedLabel) {
parentContainer.add(comp);
} else {
// add placeholder in place of selected component
parentContainer.add(placeHolder);
}
}
selectedLabel.setLocation(currLocOnScn.x - loc.x - glassLocOnScn.x,
currLocOnScn.y - loc.y - glassLocOnScn.y);
glasspane.add(selectedLabel);
glasspane.setVisible(true);
parentContainer.revalidate();
parentContainer.repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
JComponent selectedLabel = (JComponent) e.getSource();
glassLocOnScn = glasspane.getLocationOnScreen();
Point currLocOnScn = e.getLocationOnScreen();
selectedLabel.setLocation(currLocOnScn.x - loc.x - glassLocOnScn.x,
currLocOnScn.y - loc.y - glassLocOnScn.y);
glasspane.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
JComponent selectedLabel = (JComponent) e.getSource();
if (parentContainer == null || glasspane == null) {
return;
}
// sort the labels based on their x position on screen
PriorityQueue<JComponent> compQueue = new PriorityQueue<JComponent>(
4, new Comparator<JComponent>() {
#Override
public int compare(JComponent o1, JComponent o2) {
// sort of a kludge -- checking a client property that
// holds the x-position
Integer i1 = (Integer) o1.getClientProperty(X_POS);
Integer i2 = (Integer) o2.getClientProperty(X_POS);
return i1.compareTo(i2);
}
});
// sort of a kludge -- putting x position before removing component
// into a client property to associate it with the JLabel
selectedLabel.putClientProperty(X_POS, selectedLabel.getLocationOnScreen().x);
glasspane.remove(selectedLabel);
compQueue.add(selectedLabel);
Component[] comps = parentContainer.getComponents();
for (Component comp : comps) {
JLabel label = (JLabel) comp;
if (!label.getText().trim().isEmpty()) { // if placeholder!
label.putClientProperty(X_POS, label.getLocationOnScreen().x);
compQueue.add(label); // add to queue
}
}
parentContainer.removeAll();
// add back labels sorted by x-position on screen
while (compQueue.size() > 0) {
parentContainer.add(compQueue.remove());
}
parentContainer.revalidate();
parentContainer.repaint();
glasspane.repaint();
}
};
this.labels = new JLabel[4];
for (int i = 0; i < this.labels.length; i++) {
this.labels[i] = new JLabel(String.valueOf(i), JLabel.CENTER);
this.labels[i].setOpaque(true);
this.labels[i].setPreferredSize(new Dimension(100, 100));
this.labels[i].setBackground(this.colors[i]);
this.labels[i].setForeground(Color.WHITE);
this.labels[i].addMouseListener(listener);
this.labels[i].addMouseMotionListener(listener);
basePanel.add(this.labels[i]);
}
this.add(basePanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("LabelDnd");
frame.getContentPane().setLayout(new BorderLayout());
LabelDnd panel = new LabelDnd();
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Because of z-index of your Swing component. You should use setComponentZOrder to change component's z-index value after you drag.
Please check this link to get more details

Categories

Resources