我有一个,里面JPanel
有一个JLabel
,是否可以用鼠标单击JLabel
,然后再用鼠标单击 上的任何位置JPanel
以创建JLabel
. 基本上,我可以单击JLabel
并在JPanel
.
问问题
1022 次
2 回答
2
这是您正在寻找的一个简单示例。您需要的是deepCopy
单击JLabel
然后将其检索回来并将其绘制到JPanel
.
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
import javax.swing.border.*;
class CopyLabel extends JFrame
{
JPanel panel ;
JPanel centerPanel;
int clickCount = 0;
ByteArrayOutputStream baos;
ByteArrayInputStream bins;
public void createAndShowGUI()
{
setTitle("Copy JLabel");
JLabel label1 = new JLabel("JLabel1");
JLabel label2 = new JLabel("JLabel2");
panel = new JPanel();
label1.setForeground(Color.blue);
label2.setForeground(Color.red);
panel.add(label1);
panel.add(label2);
class MyMouseAdapter extends MouseAdapter
{
@Override
public void mouseClicked(MouseEvent evt)
{
clickCount = 1;
try
{
deepCopy((JLabel)evt.getSource());
}
catch (Exception ex){}
}
}
label1.addMouseListener(new MyMouseAdapter());
label2.addMouseListener(new MyMouseAdapter());
panel.setBorder(BorderFactory.createTitledBorder("Controllers"));
getContentPane().add(panel,BorderLayout.SOUTH);
centerPanel = new JPanel();
centerPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(),"Drawing Pad",TitledBorder.CENTER,TitledBorder.TOP));
centerPanel.setLayout(null);
centerPanel.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent evt)
{
if (clickCount == 1)
{
try
{
pasteLabel(evt.getX(),evt.getY());
}
catch (Exception ex){}
}
}
});
getContentPane().add(centerPanel);
setSize(300,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void deepCopy(JLabel label)throws Exception
{
baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(label);
oos.close();
}
public void pasteLabel(int x, int y)throws Exception
{
if (clickCount == 1)
{
bins = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream oins = new ObjectInputStream(bins);
JLabel obj = (JLabel)oins.readObject();
centerPanel.add(obj);
obj.setBounds(x,y,obj.getWidth(),obj.getHeight());
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
CopyLabel cl = new CopyLabel();
cl.createAndShowGUI();
}
});
}
}
于 2013-03-19T21:39:34.263 回答
1
You can attach mouse listener to your JLabel like this
final JLabel jlabel = new JLabel("Test");
jlabel.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Hello : "+ e);
Point location = MouseInfo.getPointerInfo().getLocation();
targetPanel.add(cloneLabelAt(jlabel, location));
}
});
private JLabel cloneLabelAt(JLabel label, Point location)
{
JLabel cloned = new JLabel(label.getText());
cloned.setLocation(location);
return cloned;
}
Inside your mouse click handler you can create another JLabel and add it to your target panel
于 2013-03-19T20:44:29.603 回答