How to drag and drop an image from label to label? - java

I'm new in using the DnD in java.I'm trying to drag an drop an image from a label to another. The first label is the source, the second is the destination. My trouble is that I need to drag the image from the source and recognize that i'm dropping on the correct destination; if the destination is correct the image from the source must disappear, else must come back to the source and notify it to the user using a window message or just a System.out.println(). I've tried using TransferHandler, DragSource, but I didn't get a single good result.
How to drag and drop an image from label to label?
The Drag Listener
public class DragMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
}
The Source labels that contain the images
public ShipsGUI() {
// setBorder(new EmptyBorder(10,10,10,10));
setLayout(new GridLayout(2, 5));
MouseListener listener = new DragMouseAdapter();
for (int i = 0; i < 10; i++) {
JPanel p = new JPanel(new BorderLayout(5, 0));
JLabel a = new JLabel(ship,JLabel.CENTER);
a.setName("ship");
JLabel n = new JLabel("[" + Integer.toString(i + 1) + "]");
n.setForeground(Color.BLUE);
// a.setBorderPainted(false);
// a.setBackground(Color.white);
// a.setOpaque(true);
//a.setIcon(ship,JLabel.CENTER);
a.setTransferHandler(new TransferHandler("icon"));
a.addMouseListener(listener);
p.add(a);
p.add(n, BorderLayout.LINE_START);
add(p);
}
}
The destination (it's a grid fo labels)
public NewAreaGioco(int r,int c, boolean enable){
this.setLayout(new GridLayout(r,c,1,1));
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
JLabel l= new JLabel(" ");
l.setSize(30, 30);
l.setBorder(BorderFactory.createLineBorder(Color.BLUE));
if(enable)l.setTransferHandler(new TransferHandler("icon"));
add(l);
}//fine for
}//fine for
}

Well, you can't use the default TransferHandler class. You need to make your own.
I would start by looking at the DropDemo and ListTransferHandler class found on the examples page of the Drag and Drop tutorial.
A couple of change that I think you will need to make:
export an image instead of text. I think the link provided by Sergiy above might help.
The key point is in the exportDone(...) method. Your cleanup code would set the icon of the source component to null.
You will probably need to read the tutorial to understand the concept of these two classes.

Related

I want to replace a JLabel with another JLabel but keep it in the same position, is this possible?

Here is the code that I am trying to edit:
game = new JPanel();
ImageIcon bbb = new ImageIcon("bbb.gif");
JLabel bbbl = new JLabel(bbb);
ImageIcon bbbH = new ImageIcon("bbbH.gif");
JLabel bbbHl = new JLabel(bbbH);
game.setLayout(new GridLayout(2,2));
game.add(bbol);
game.add(bbgl);
game.add(bbgrl);
game.add(bbbl);
if (flashed == 1)
{
game.remove(bbol);
game.add(bboHl);
}
else
{
}
I want the JLabel bboHl to go in the same position as the JLabel bbol however there are other JLabels after this one, 3 more to be exact, therefor explaining why the layout is (GridLayout(2,2))
Would I need to change the layout?
Removing/adding components to the layout is way too expensive.
From what I understand, you just want to toogle an image :
Add only one JLabel, and use setIcon on it to change the image.
game = new JPanel();
ImageIcon bbb = new ImageIcon("bbb.gif");
ImageIcon bbbH = new ImageIcon("bbbH.gif");
JLabel bbbl = new JLabel(bbb);
game.setLayout(new GridLayout(2, 2));
game.add(bbol);
game.add(bbgl);
game.add(bbgrl);
game.add(bbbl);
if (flashed == 1) {
bbbl.setIcon(bbbH);
} else {
bbbl.setIcon(bbb);
}
Let say if there are multiple labels like label1 ,label2 , label3etc. And you want to set them on the position of label bbo1. Then it can be done by getting the location of label bbo1 and setting it to all other labels.
For Example
label1.setLocation(bbo1.getLocation());
label2.setLocation(bbo1.getLocation());
label3.setLocation(bbo1.getLocation());

single function call on click any label JInternalFrame Java Swing

I am new to learning Java.
I am creating a JInternalFrame which have 28 labels in matrix forms in it. I want to change label text from - to + on click & vice versa.
I can do it adding EventListeners to each label one by one. But I want some simple solution in which I don't need to add eventlisteners for each label individually. A long ago I have tried same methodology on array of buttons in VisualBasic.
But I want some simple solution in which I don't need to add eventlisteners for each label individually
Why? You can share the MouseListener. Then you just add the listener to the label when you create the label. This is the better approach then trying to search for the clicked label after the fact.
For example:
MouseListener ml = new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
JLabel label = (JLabel)e.getComponent();
label.setText( label.getText().equals("-") ? "+" : "-" );
}
}
for (int i = 0; i < 28)
{
JLabel label = new JLabel("-");
label.addMouseListener( ml );
panel.add(label);
}

Vertical JPanel manual positioning: which layout?

Given my requirements:
Single vertical column of JPanels.
Set the vertical location* of the JPanel without using the properties of a sibling.
Component position and size are fixed when the frame is resized.
Keep other layout aspects automatic (such as preferred size calculation), as much as possible
(*) Location: I mean location as in Component.setLocation(x, y).
is there a solution which is obvious, and if this is GridBagLayout, how to do this?
Details:
I want to put components vertically in a column container (like a vertical Box) by specifying their vertical location only. What is the best way to do this without loosing the other benefits of a layout such as BoxLayout?
In a vertical Box, setting the vertical position of a component must be done using a filler, or by adjusting the size of the component just above, there is no such possibility like:
panel.setLocation(getLocation().x, y)
On the other hand using a no layout container puts on me the task manage:
The initial size of the component
The container resizing events.
Here the solution of null layout is recommended, here this is a custom one, and here this is GridBagLaout. Also MIGLayout appears to be universal one (but I'd prefer no adding another library to my project).
I have written the following program for someone who was also looking for the same requirements.
Note: Make sure to add the first element to 0 position because there will be no more components and no position will be available other than 0, 2nd to 0 or 1, 3rd to 0 or 1 or 2 and so on
public class VerticalList extends JFrame {
JPanel pnl = null;
TextField tf = new TextField(10);
Box center = Box.createVerticalBox();
JScrollPane jsp = new JScrollPane(center);
JPanel ctrl = new JPanel(new FlowLayout());
JButton send = new JButton("Send");
public VerticalList() {
jsp.setAutoscrolls(true);
ctrl.add(send);
ctrl.add(new JLabel("Position:"));
ctrl.add(tf);
Container cnt = getContentPane();
cnt.add(jsp, BorderLayout.CENTER);
cnt.add(ctrl, BorderLayout.SOUTH);
send.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pnl = new JPanel(new FlowLayout());
pnl.setBorder(BorderFactory.createLineBorder(Color.red));
pnl.add(new JLabel("Added to Position: "+tf.getText()));
pnl.setMaximumSize(new Dimension(Integer.MAX_VALUE, (int)pnl.getPreferredSize().getHeight()));
try{
int index = Integer.parseInt(tf.getText());
center.add(pnl, index);
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Please Provide a Valid position", "Position Error", JOptionPane.ERROR_MESSAGE);
}
validate();
}
});
setPreferredSize(new Dimension(300, 300));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
pack();
}
public static void main(String[] args) {
new VerticalList();
}
}

Creating Square Buttons in Swing

I would like to create something like the following in Swing:
The top part is relatively easy: I can just create a table and display it. What I'm having trouble with is the square plus and minus buttons at the bottom, which are designed to add a new item or remove the selected item respectively. In particular, I haven't been able to make the square shape because on Mac OS X and some other platforms, JButtons are rectangles with rounded corners and I can't find a way to change that. Also, I'm wanting to make sure it's a perfect square and without any space in between buttons.
How can this be accomplished in a cross-platform way on Swing?
JButtons are rectangles with rounded corners and I can't find a way to change that.
Change the Border:
button.setBorder( new LineBorder(Color.BLACK) );
Edit.
Another approach is to create your own icon from an existing button. Something like the following:
JButton button = new JButton("+");
Dimension size = button.getPreferredSize();
size.x += 6;
size.y += 6;
button.setPreferredSize(size);
Rectangle rectangle = new Rectangle(3, 3, size.x - 3, size.y - 3);
ScreenImage buttonImage = ScreenImage(button, rectangle);
ImageIcon icon = new ImageIcon(buttonImage);
JButton plus = new JButton(icon);
plus.setBorder( ... );
The above code should create an image of your button on any platform. I increased the preferred size to avoid taking an image of the border.
You will need to use the Screen Image class.
This is most easily achieved by returning a preferred size that is NxN - where N is the larger of preferred width or height.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class SquareButton extends JButton {
SquareButton(String s) {
super(s);
}
#Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
int s = (int)(d.getWidth()<d.getHeight() ? d.getHeight() : d.getWidth());
return new Dimension (s,s);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JComponent gui = new JPanel(new FlowLayout());
for (int ii=0; ii<5; ii++) {
gui.add(new SquareButton("" + ii));
}
gui.setBorder(new EmptyBorder(4, 8, 4, 8));
JFrame f = new JFrame("Square Buttons");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
You can set the size of a button using using setPreferredSize():
JButton button = new JButton("+");
button.setPreferredSize(new Dimension(10, 10));
You might be able to remove the rounded corners using:
button.setBorder(BorderFactory.createEmptyBorder());
If this does not work then you can override the paintComponent() method on JButton.
Well in order to make them square, you have 2 options: 1. Make the button hold an icon image of just a square image of a transparent image. 2. you could set the button dimensions on your own. I am not sure how to set the dimensions, but that is a an option you could choose. You can just create a JToolBar that is set on the BorderLayout.SOUTH end of the window whenever you add, and whatever buttons are added onto that, will be right next to each other. To add the buttons do this:
JButton button1 = new JButton("+");
JButton button2 = new JButton("-");
JToolBar toolbar = new JToolBar();
<JPanel,JFrame,Whatever>.add(toolbar, BorderLayout.SOUTH);
toolbar.add(button1);
toolbar.add(button2);
This will add the toolbar onto the JFrame, JPanel, or whatever you're adding it onto, and it will set it to the bottom of the screen as you see above.
Hope this helps!

Java JFrame refuses to refresh

I am making a monopoly game in Java and for some reason I cant seem to get this JFrame popup to refresh. When I click the button, the popup will appear, but when I close it and click it again later on it the game, it continues to show the features of the 1st JFrame. I assume that a totally new JFrame is created every time you click the button, but I cant seem to refresh the content. How do I fix this?
final static JButton tradeButton = new JButton("Click to Trade Property");
tradeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
final JPanel tradePanelcombo = new JPanel();
for(int x = 1; x< Player.Props.size(); x++)
{
if(x != Player.CurrentPlayer)
{
ArrayList<Property> props = Player.Props.get(x);
ArrayList<String> propnames = new ArrayList<String>();
for(Property prop : props)
{
propnames.add(prop.getName());
}
String[] strings = new String[propnames.size()];
for (int y = 0; y<propnames.size(); y++)
{
strings[y] = propnames.get(y);
}
JLabel confirmLabel = new JLabel("Player :" + x);
JComboBox petList = new JComboBox(strings);
petList.setPreferredSize(new Dimension(100, 150));
tradeFrame.add(confirmLabel);
tradePanelcombo.add(petList);
}
}
tradeFrame.add(tradePanelcombo, BorderLayout.PAGE_END);
tradeFrame.setPreferredSize(new Dimension(500,500));
tradeFrame.setResizable(true);
tradeFrame.pack();
tradeFrame.setVisible(true);
}
});
It appears to me that a new frame and components are created every time.
So, if the frame doesn't update, then I guess it would be because your Properties are not updated so the data added to the components doesn't change.
Edit:
You need to create a new JFrame every time, or you need to remove all the old components from the frame before adding the new components.
When you add a component to a BorderLayout, the previous component doesn't get removed. So you actually have two components in the container. When Swing paints components it actually paints the components in the reverse order that they where added to the container (this is how Z-Ordering works).
If you remove the setResizable() method, and then resize the frame I believe you should see the new components start to show given that they should increase in size as the frame size increases.

Categories

Resources