image not overlapping button - java

i want to overlap image on button(when it is clicked)....but on clicking it is not overlapping....please guide me where i am wrong....is it not possible to do so???
i am using frame to add buttons....
import java.awt.*;
import java.awt.event.*;
public class d extends Frame implements ActionListener {
Image img, i1, i2;
int x, y;
String msg;
Button one, two;
d() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setSize(1000, 500);
setVisible(true);
setLayout(null);
one = new Button("1");
two = new Button("2");
add(one);
add(two);
one.addActionListener(this);
two.addActionListener(this);
one.setBounds(200, 100, 100, 100);
two.setBounds(300, 100, 100, 100);
}
public void actionPerformed(ActionEvent e) {
msg = e.getActionCommand();
if (msg.equals("1")) {
msg = "Pressed 1";
img = i1;
x = 200;
y = 100;
} else {
msg = "Pressed 2";
img = i2;
x = 300;
y = 100;
}
repaint();
}
public void paint(Graphics g) {
Toolkit tool = Toolkit.getDefaultToolkit();
i1 = tool.getImage("F:/Memories/rawk garden/a.jpg");
i2 = tool.getImage("F:/Memories/rawk garden/b.jpg");
g.drawImage(img, x, y, 100, 100, this);
g.drawString(msg, 100, 300);
}
public static void main(String s[]) {
new d();
}
}

I have already shared you code for this in your last post where I suggested you some points with the sample code to achieve it using JLabel.
Read more points...
Don't use null layout. There are lots of Layout Managers choose any one that suits as per your application design.
How to Use Various Layout Managers
From comments below:
actually I am making minesweeper type game...i want button to change into image and once one button is converted to image...that image remains there.
Use JButton#setIcon() method to set the icon of the button.
Here is the sample code where
I have created a 9x9 grid that contains buttons.
Each cell has a random boolean flag whether it has mine or not.
When button is clicked I am setting its icon if it has mine.
Simply set the text empty and make it disabled to stop further clicks on already clicked button.
sample code:
final Image mine = ImageIO.read(new File("resources/mine.png"));
final boolean[][] showMine = new boolean[9][9];
Random random = new Random();
JPanel panel = new JPanel(new GridLayout(9, 9));
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
showMine[i][j] = random.nextBoolean();
final int x = i;
final int y = j;
final JButton button = new JButton();
button.setText(String.valueOf(i * 9 + j));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setEnabled(false);
button.setText("");
if (showMine[x][y]) {
button.setDisabledIcon(new ImageIcon(mine));
}
}
});
panel.add(button);
}
}
add(panel);
snapshot:

Setting an image on a button can be done as follows:
Button myButton = new Button(new ImageIcon("image_path"));

Related

Movement stuck when clicking buttons

Created a Program similar to paint where there is a rectangle whose movement inside the screen can be controlled by "w,a,s,d" keys and its size increased or decreased using the scroller on the mouse. There are also several buttons of various colours which when pressed fills the rectangular shape with the respective colours. Now the problem is after clicking any colour button the movement is stopped ie. the rectangle doesn't move. You can increase and decrease its size but you can't move with "w,a,s,d" keys. Please do help me with that.
And also as an optional request, I'm also trying to paint with this rectangle ie. when I press the space bar I want to fill the colour which is selected at the specified area. Now even though I can do that. The next action I do ie. either pressing "w,a,s,d" keys or the scroller, the colour disappears. Now I know that the colour or fillRect() has to be saved somehow so that the next action doesn't affect it, but I've tried several ways but it isn't happening. I've commented the code for the painting below.
My first request is my main request, the second one if you are unable to understand what I mean or don't know the solution just leave it.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Animation extends Frame implements KeyListener,MouseWheelListener,ActionListener {
int x,y,a,b;
char choice1;
int draw=1;
int n=0;
int color1,color2,color3;
Button button1,button2,button3,button4,button5,button6,button7,button8,button9,button10;
Animation() {
setSize(1000, 1000);
setVisible(true);
x = 500;
y = 500;
a = 20;
b = 50;
addKeyListener(this);
addMouseWheelListener(this);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
button1 = new Button("Black");
button2 = new Button("Blue");
button3 = new Button("Green");
button4 = new Button("Orange");
button5 = new Button("Red");
button6 = new Button("Yellow");
button7 = new Button("Gray");
button8 = new Button("Cyan");
button9 = new Button("Magenta");
button10 = new Button("Pink");
add(button1);add(button2);add(button3);add(button4);add(button5);
add(button6);add(button7);add(button8);add(button9);add(button10);
button1.setBounds(50,680,50,20); button2.setBounds(120,680,50,20);
button3.setBounds(190,680,50,20); button4.setBounds(260,680,50,20);
button5.setBounds(330,680,50,20); button6.setBounds(400,680,50,20);
button7.setBounds(470,680,50,20); button8.setBounds(540,680,50,20);
button9.setBounds(610,680,50,20); button10.setBounds(680,680,50,20);
button1.addActionListener(this);button2.addActionListener(this);
button3.addActionListener(this);button4.addActionListener(this);
button5.addActionListener(this);button6.addActionListener(this);
button7.addActionListener(this);button8.addActionListener(this);
button9.addActionListener(this);button10.addActionListener(this);
addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {
}
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
#Override
public void windowClosed(WindowEvent e) {
}
#Override
public void windowIconified(WindowEvent e) {
}
#Override
public void windowDeiconified(WindowEvent e) {
}
#Override
public void windowActivated(WindowEvent e) {
}
#Override
public void windowDeactivated(WindowEvent e) {
}
});
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
choice1 = e.getKeyChar();
if (choice1 == 'w') {
y = y - 10;
}
if (choice1 == 's') {
y = y + 10;
}
if (choice1 == 'a') {
x = x - 10;
}
if (choice1 == 'd') {
x = x + 10;
}
if(choice1 == ' '){
draw=2;
}
repaint();
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
double p = e.getPreciseWheelRotation();
if(p>0){
a=a+5;
b=b+5;
} else{
a=a-5;
b=b-5;
}
repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Black")){
color1 = 0;
color2 = 0;
color3 = 0;
}
if(e.getActionCommand().equals("Blue")){
color1 = 0;
color2 = 0;
color3 = 255;
}
if(e.getActionCommand().equals("Green")){
color1 = 0;
color2 = 255;
color3 = 0;
}
if(e.getActionCommand().equals("Orange")){
color1 = 255;
color2 = 165;
color3 = 0;
}
if(e.getActionCommand().equals("Red")){
color1 = 255;
color2 = 0;
color3 = 0;
}
if(e.getActionCommand().equals("Yellow")){
color1 = 255;
color2 = 255;
color3 = 0;
}
if(e.getActionCommand().equals("Gray")){
color1 = 169;
color2 = 169;
color3 = 169;
}
if(e.getActionCommand().equals("Cyan")){
color1 = 0;
color2 = 255;
color3 = 255;
}
if(e.getActionCommand().equals("Magenta")){
color1 = 255;
color2 = 0;
color3 = 255;
}
if(e.getActionCommand().equals("Pink")){
color1 = 255;
color2 = 192;
color3 = 203;
}
repaint();
}
public void paint(Graphics g) {
if(draw==1) {
g.drawRect(x, y, a, b);
g.setColor(new Color(color1,color2,color3));
g.fillRect(x,y,a,b);
}
// if(draw==2){
// fillColor(g);
// draw=1;
// }
}
// public void fillColor(Graphics g){
// g.setColor(Color.red);
// int[] temp1 = new int[50];
// temp1[n] = x;
// int[] temp2 = new int[50];
// temp2[n] = y;
// int[] temp3 = new int[50];
// temp3[n] = a;
// int[] temp4 = new int[50];
// temp4[n] = b;
//
//
// n++;
// for (int i=0;i<n;i++){
// System.out.println("abcd");
// g.fillRect(temp1[n],temp2[n],temp3[n],temp4[n]);
// }
//
// }
public static void main(String[] args) {
Animation animation = new Animation();
}
}
First of all there are basic design issues:
Don't extend Frame. There is no need to extend any class.
Don't use AWT components in a Swing application. JFrame is Swing. "Button" is AWT. For Swing your should be using JButton.
Don't use a null layout for the entire frame. Keep the default BorderLayout. Read the section from the Swing tutorial on How to Use BorderLayout.
For the buttons you should create a JPanel (which by default uses a FlowLayout) and add your buttons to this panel.
Then you add this panel to your frame using:
frame.add(buttonPanel, BorderLayout.PAGE_END);
Custom painting is done by extending JPanel and then you override the paintComponent(...) method. So you need to create a DrawingPanel to paint your rectangle. Read the Swing tutorial on Custom Painting for working examples to help you structure your code better.
Then you add the drawing panel to the frame using:
frame.add(drawingPanel, BorderLayout.CENTER):
Don't use a WindowListener to close the frame.
When you create the frame you can set the close property:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Using multiple nested if statements, like you do in the ActionListner is poor design. As you continue to support more colors the code just grows and grows. An alternative approach might be:
a) create a HashMap as an instance variable to contain the buttons and colors:
private HashMap<JButton, Color> buttonColors = new HashMap<>();
private Color rectangleColor = Color.BLACK;
b) now when you create each button you can update the hash map:
buttonColors.put(button1, Color.BLACK);
c) now the code in your ActionListener becomes:
JButton button = (JButton)e.getSource();
Color color = buttonColors.get(button);
rectangleColor = color;
repaint();
d) and the code in your paintComponent() method becomes:
//g.setColor(new Color(color1,color2,color3));
g.setColor( rectangleColor );
Don't create your buttons by brute force. Create a method.
Code to invoke method
buttonsPanel.add( createButton("Black", Color.BLACK) );
buttonsPanel.add( createButton("Blue", Color.BLUE) );
and the createButton(..) method would look something like:
public JButton (String text, Color color)
{
JButton button = new JButton( text );
button.addActionListener(this);
buttonColors.put(button, color);
return button;
}
A lot of suggestions here. The code is posted without testing, so understand each concept and make a change one at a time and test to make sure you implement each step correctly.
Now the problem is after clicking any colour button the movement is stopped ie. the rectangle doesn't move.
A KeyEvent is only passed to the component with focus. When you click on a button the painting panel loses focus and no longer responds to events.
The better solution is to use Key Bindings. Key bindings will work even when a component doesn't have focus. See: Motion Using the Keyboard for more information and working examples.
Short answer for the first. Add:
button1.setFocusable(false);
button2.setFocusable(false);
button3.setFocusable(false);
button4.setFocusable(false);
button5.setFocusable(false);
button6.setFocusable(false);
button7.setFocusable(false);
button8.setFocusable(false);
button9.setFocusable(false);
button10.setFocusable(false);

Java Choice Menu Difficulties, Colour and Draw_Line

I'm trying to create a MS Paint-like software with Java Choice Menus, but I'm experiencing some difficulties with two functions in particular
I get a massive wall of error text upon selecting a colour from my Colour Menu. What I wish to achieve is selecting the colour converts the string containing the option into lower case, before setting the PenColour into that option
Drawing Lines don't seem to work, despite the same code being functional in a different applet that didn't use Choice. I want it to select two points which then have a line drawn between them.
Here is my Code
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.Choice;
public class PockettProjectTest1 extends Applet implements ActionListener, MouseListener, MouseMotionListener{
//Coordinates and sizes used to draw GUI
private final int GUI_HEIGHT = 100;
private final int GUI_START_X = 10;
private final int GUI_START_Y = 10;
private final int FIELD_SIZE = 11; //Numbers of characters for text field display
////////////////////////GLOBAL VARIABLES////////////////////////
private Dimension appletSize; //used to encapsulate the Applets dimensions
private int x, y, appletHeight, appletWidth, PenThick, PenMode, ShapeMode, ClickXO, ClickYO, ClickXN, ClickYN, ClickCount;
private String SizeString;
//a Panel is a container used here to hold and position the GUI components
private Panel guiPanel;
private Color PenColour;
//GUI components cv
public void init(){
//Disables the applet layout manager and stops automatic GUI component positioning
setLayout(null);
setBackground(Color.white);
addMouseListener(this);
addMouseMotionListener(this);
addMouseListener(this);
ClickCount = 0;
ClickXO = 0;
ClickYO = 0;
ClickXN = 0;
ClickYN = 0;
PenMode = 0;
ShapeMode = 0;
appletSize = this.getSize(); //captures the Applet dimensions
appletHeight = appletSize.height; //captures the Applet height
appletWidth = appletSize.width; //captures the Applet width
//Set up the Panel ready to hold the GUI components
guiPanel = new Panel();
guiPanel.setLocation(0, 0);
guiPanel.setSize(appletWidth,GUI_HEIGHT);
guiPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 40));
guiPanel.setBackground(Color.lightGray);
add(guiPanel);
Choice mode = new Choice();
Choice size = new Choice();
Choice color = new Choice();
Choice shape = new Choice();
mode.add("Pen");
mode.add("Eraser");
mode.add("Fill");
mode.add("Shape");
size.add("01px");
size.add("02px");
size.add("03px");
size.add("05px");
size.add("10px");
size.add("15px");
size.add("20px");
size.add("30px");
size.add("50px");
shape.add("N/A");
shape.add("Line");
shape.add("Oval");
shape.add("Oblong");
shape.add("Square");
shape.add("Circle");
shape.add("FillOval");
shape.add("FillOblong");
shape.add("FillSquare");
shape.add("FillCircle");
//add choice or combobox
guiPanel.add(mode);
guiPanel.add(size);
guiPanel.add(shape);
PenThick = 1;
PenColour = Color.black;
mode.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
PenMode = mode.getSelectedIndex();
}
});
size.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
SizeString = size.getSelectedItem();
PenThick = Integer.parseInt(SizeString.substring(0,2));
Graphics g = getGraphics();
}
});
//// Start of Issue 1:
colour.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
ColourString = colour.getSelectedItem();
ColourString.toLowerCase();
Color PenColour.getColor(ColourString);
}
});
/// End of Issue 1
shape.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
ShapeMode = shape.getSelectedIndex();
}
});
}
public void actionPerformed(ActionEvent e) {
}
////Issue 2:
public void mouseReleased(MouseEvent me){
if (PenMode == 3) {
if (ClickCount == 0) {
ClickXO = me.getX();
ClickYO = me.getY();
ClickCount ++;
System.out.println(ClickCount);
return;
}
if (ClickCount == 1) {
ClickXN = me.getX();
ClickYN = me.getY();
System.out.println(ClickCount);
Graphics g = getGraphics();
g.setColor(Color.black);
g.drawLine(ClickXO, ClickYO, ClickXN, ClickYN);
System.out.println(ClickXO);
System.out.println(ClickYO);
System.out.println(ClickXN);
System.out.println(ClickYN);
ClickCount = 0;
}
}
}
/// End of Issue 2
public void mousePressed(MouseEvent e){
}
public void mouseDragged(MouseEvent e){
if (PenMode == 0){
Graphics g = getGraphics();
g.setColor(Color.black);
g.fillOval(e.getX(), e.getY(), PenThick, PenThick);
}
if (PenMode == 1){
Graphics g = getGraphics();
g.setColor(Color.white);
g.fillRect(e.getX(), e.getY(), PenThick, PenThick);
}
}
public void mouseMoved(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseClicked(MouseEvent e){
}
}
I have to have this code due by the end of Friday, so I hope I can get the issue solved by then.

Cannot display image icon

I have to display images using the fly weight pattern, I can't get the images to print to screen, here's the code that demonstrates the problem.
public void draw(Graphics g, int tx, int ty, String name) {
grem.paintIcon(null, g, tx, ty);
g.drawString(name, tx, ty + H + 15 );
ImageIcon grem = new ImageIcon("../images/grem.png");
}
/// next class that calls the above class
public void paint(Graphics g) {
Folder folderIcon;
String name;
int j = 0; //count number in row
int row = Top; //start in upper left
int x = Left;
//go through all the names and folders
for (int i = 0; i< names.size(); i++) {
name = (String)names.elementAt(i);
if (name.equals(selectedName))
folderIcon = fact.getFolder(true);
else
folderIcon = fact.getFolder(false);
//have that folder draw itself at this spot
folderIcon.paint(g);
x = x + HSpace; //change to next posn
j++;
if (j >= HCount) { //reset for next row
j = 0;
row += VSpace;
x = Left;
}
}
}
Don't override paint(). Custom painting is done by overriding paintComponent().
Don't do I/O in a painting method. You can't control when Swing will repaint a component so you don't want to read images in the painting method. The images should be read in the constructor of your class.
Override the getPreferredSize(...) method to return the size of your component, otherwise the size of the component will be (0, 0) so there may be nothing to paint (depending on the layout manager being used.
If you need more help the post a proper SSCCE that demonstrates the problem because we don't know the context of how your code is being used and don't have time to spend guessing what you may or may not be doing.
Read the section from the Swing tutorial on Custom Painting for more information. Also, instead of doing custom painting you could also use a JList to display the Icon in a grid pattern. Check out the table of contents for the tutorial link to find the section on How to Use Lists for more information.
Maybe the null is the problem : it should be something like this if im not mistaken
class MyComponent extends JComponent {
public void paint(Graphics g) {
ImageIcon icon = new ImageIcon("a.png");
int x = 0;
int y = 100;
icon.paintIcon(this, g, x, y);
}
public class Gremlin extends JFrame implements ActionListener {
String names[] = {"Andy","Bill","Bob","Dan","Eugene","Frank","Gary","Harry","Ian","Jack",
"Killlian","Liam","Mark","Nial","Obi","Phil","Richard","Stephan","Terry","Viny",}; // 20 names
public Icon img = new ImageIcon("grem1.jpg");
public JLabel grem = new JLabel(img);
JLabel bigLabel = new JLabel();
JLabel grem2 = new JLabel("New Gremlin");
public JPanel panel2 = new JPanel();
JPanel panel = new JPanel();
public Gremlin() {
JButton button = new JButton("Add Gremlin");
this.add(panel);
panel.setLayout(new GridLayout(9,6));
panel.add(panel2);
panel2.add(button);
for(int i = 0; i<20; i++){
bigLabel.add(grem = new JLabel(names[i]), panel.add(grem = new JLabel(img)));
panel.add(bigLabel);
}
button.addActionListener(this);
setSize(550,600);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
Gremlin frame = new Gremlin();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() != null ){
System.out.println("add a Gremlin");
panel.add(grem = new JLabel("NEW GREMLIN"), panel.add(grem = new JLabel(img)));
revalidate();
}
}
}

JButtons disappear after the popup menu shows

I added listeners to my JButtons for the popup menu but when the popup menu appears the JButtons disappear and I would need to hover my cursor on the buttons to make them appear again. Why is it like this?
(all the methods here are in the same class)
public Inventory() {
setLayout(null);
setBounds(0, 0, 175, 210);
initPopupMenu(); // this just sets what is inside the popup menu
int x;
// 30 buttons
for(x = 0; x < 30; x++) {
button[x] = new JButton();
add(button[x]);
button[x].addMouseListener(this);
}
x = 0;
// it's a grid of buttons
for(int i = 0; i < 5; i++)
for(int j = 0; j < 6; j++) {
button[x].setBounds(i*35+1,j*35+1, 33,33);
x++;
}
}
public void mouseClicked(MouseEvent e) {
for(int j = 0; j < 30; j++) // i tried this one but it still disappears
button[j].repaint();
for(int i = 0; i < 30; i++) {
if(e.getSource() == button[i]) {
System.out.println("You pressed Button "+i);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
This is what happens,
Stop using null Layout, seems like that can be one of the issues regarding this. Your JFrame appears sort of BLACK to me, is this some THEME or a new LOOK AND FEEL you are using, that can be the cause of this thing too. Here check this out, it's working flawlessly here with this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonPopUp
{
private static final int SIZE = 30;
private JButton[] button = new JButton[SIZE];
private JPopupMenu popup = new JPopupMenu("Hello World");
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Button POP UP Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
final JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 5));
JMenuItem menuItem1 = new JMenuItem("Menu Item 1");
JMenuItem menuItem2 = new JMenuItem("Menu Item 2");
//popup.add(greetings);
popup.insert(menuItem1, 0);
popup.insert(menuItem2, 1);
for (int i = 0; i < SIZE; i++)
{
button[i] = new JButton();
button[i].setBorder(BorderFactory.createEtchedBorder());
button[i].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
System.out.println("I am WORKING!!");
popup.show((JComponent)me.getSource(), me.getX(), me.getY());
}
});
contentPane.add(button[i]);
}
frame.getContentPane().add(contentPane);
frame.setSize(175, 250);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new ButtonPopUp().createAndDisplayGUI();
}
});
}
}
Here is the output :

Java Swing - Drag & Drop drawString text

I've had a look around for this problem but couldn't find an answer...
I currently have a JPanel in which I'm painting a load of unicode characters (music notes) using the Graphics2D g2.drawString() method.
I have an ArrayList of KeyPress objects, each of which contains one or more g2.drawString() calls.
So each KeyPress object is a music note and is painted on the JPanel.
How would I go about adding the functionality to enable the user to select and drag the objects?
Why not put your Strings in JLabels and simply drag them...
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class DragLabelEg {
private static final String[] LABEL_STRINGS = { "Do", "Re", "Me", "Fa",
"So", "La", "Ti" };
private static final int HEIGHT = 400;
private static final int WIDTH = 600;
private static final Dimension MAIN_PANEL_SIZE = new Dimension(WIDTH, HEIGHT);
private static final int LBL_WIDTH = 60;
private static final int LBL_HEIGHT = 40;
private static final Dimension LABEL_SIZE = new Dimension(LBL_WIDTH,
LBL_HEIGHT);
private JPanel mainPanel = new JPanel();
private Random random = new Random();
public DragLabelEg() {
mainPanel.setPreferredSize(MAIN_PANEL_SIZE);
mainPanel.setLayout(null);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
for (int i = 0; i < LABEL_STRINGS.length; i++) {
JLabel label = new JLabel(LABEL_STRINGS[i], SwingConstants.CENTER);
label.setSize(LABEL_SIZE);
label.setOpaque(true);
label.setLocation(random.nextInt(WIDTH - LBL_WIDTH),
random.nextInt(HEIGHT - LBL_HEIGHT));
label.setBackground(new Color(150 + random.nextInt(105), 150 + random
.nextInt(105), 150 + random.nextInt(105)));
label.addMouseListener(myMouseAdapter);
label.addMouseMotionListener(myMouseAdapter);
mainPanel.add(label);
}
}
public JComponent getMainPanel() {
return mainPanel;
}
private class MyMouseAdapter extends MouseAdapter {
private Point initLabelLocation = null;
private Point initMouseLocationOnScreen = null;
#Override
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
// get label's initial location relative to its container
initLabelLocation = label.getLocation();
// get Mouse's initial location relative to the screen
initMouseLocationOnScreen = e.getLocationOnScreen();
}
#Override
public void mouseReleased(MouseEvent e) {
initLabelLocation = null;
initMouseLocationOnScreen = null;
}
#Override
public void mouseDragged(MouseEvent e) {
// if not dragging a JLabel
if (initLabelLocation == null || initMouseLocationOnScreen == null) {
return;
}
JLabel label = (JLabel) e.getSource();
// get mouse's new location relative to the screen
Point mouseLocation = e.getLocationOnScreen();
// and see how this differs from the initial location.
int deltaX = mouseLocation.x - initMouseLocationOnScreen.x;
int deltaY = mouseLocation.y - initMouseLocationOnScreen.y;
// change label's position by the same difference, the "delta" vector
int labelX = initLabelLocation.x + deltaX;
int labelY = initLabelLocation.y + deltaY;
label.setLocation(labelX, labelY);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGui();
}
});
}
private static void createGui() {
JFrame frame = new JFrame("App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DragLabelEg().getMainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
See the tutorial on supporting user interaction. It comes down to determining which (if any) objects were underneath the mouse when it was clicked and held. On a drag event, the selected object is moved and the canvas is repainted.
You can obtain the bounds of the string by using FontMetrics:
String text = "Hello world!";
Rectangle2D bounds = g2.getFontMetrics().getStringBounds(text, g2);
I assume the rectangle top-left will be (0, 0), so you need to add (x, y) to it (where x, y are the parameters you passed to drawString).
This example shows one way to select multiple objects, using keyboard or mouse, and drag
them as a group. It manipulates arbitrary nodes rather than glyphs, but you may find it instructive.

Categories

Resources