ImageIcon stops changing when I make my frame's background transparent? - java

For some reason, when I run "frame.setBackground(new Color(1.0f,1.0f,1.0f,0.0f));", then change my button's icon and repaint (even with paintImmediately) the icon of my button refuses to change. Just commenting out that line has it working again, but I kinda want that to work.
public static void main (String[] args) throws Exception
{
robot = new Robot();
frame = new JDialog();
frame.setUndecorated(true);
frame.setSize(59,61);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() - frame.getWidth() - 17;
int y = (int) rect.getMaxY() - frame.getHeight() - 40;
frame.setLocation(x, y);
frame.setAlwaysOnTop(true);
frame.setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
panel = new JPanel(new BorderLayout());
panel.setBackground(new Color(1.0f,1.0f,1.0f,0.0f));
frame.add(panel);
InputStream in = HelloWorld.class.getResourceAsStream("/Working/mic2.png");
notRecording = new ImageIcon(ImageIO.read(in));
in = HelloWorld.class.getResourceAsStream("/Working/mic3.png");
recording = new ImageIcon(ImageIO.read(in));
button = new JButton(notRecording);
button.setContentAreaFilled(false);
button.setBorder(BorderFactory.createEmptyBorder());
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try
{
record();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Exception");
}
}
});
frame.setVisible(true);
}
When I later run
button.setIcon(recording);
button.paintImmediately(button.getBounds());
Nothing happens.
Edit:
I've read over the other thread, and checked the answer they provided, but I can't seem to find any other source that verifies SWING can't handle alpha values, and in fact most sources recommend it. Additionally, calling setOpaque according to setOpaque(true/false); Java seems to imply that using setOpaque is a much more complex concept than just transparency. Additionally, replacing setBackground with setOpaque doesn't work, so I don't think the thread should be closed due to the other thread covering a similar material.
Here's an example of what isn't working for me. In theory, this would leave just the text, or at least only the section that the button occupies of the dialog remaining visible, with the rest not opaque.
import javax.swing.*;
import java.awt.*;
public class RunnableExample
{
public static void main(String[] args)
{
JDialog dialog = new JDialog();
dialog.setUndecorated(true);
dialog.setSize(59,61);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setAlwaysOnTop(true);
dialog.getRootPane().setOpaque(false);
JPanel panel = new JPanel();
panel.setOpaque(false);
dialog.add(panel);
JButton button = new JButton("test");
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setOpaque(false);
panel.add(button);
dialog.setVisible(true);
}
}

To make a window transparent, you must use setBackground (on an instance of window class, like JFrame or JDialog) and pass it a transparent color (new Color(0, 0, 0, 0))`), this is the ONLY time you can use a alpha based color on a Swing component.
Swing doesn't know how to paint components with a alpha based color, it only knows how to deal with fully transparent or fully opaque components, which is controlled via setOpaque, for example...
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JDialog dialog = new JDialog();
dialog.setUndecorated(true);
dialog.setBackground(new Color(0, 0, 0, 0));
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setAlwaysOnTop(true);
dialog.getRootPane().setOpaque(false);
JPanel panel = new JPanel();
panel.setOpaque(false);
dialog.add(panel);
JButton button = new JButton("test");
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setOpaque(false);
panel.add(button);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
});
}
}
I can further prove it by adding
panel.setBorder(new CompoundBorder(new LineBorder(Color.RED), new EmptyBorder(10, 10, 10, 10)));
to the code, which produces
The red line is actually the output of the frame (technically the panel, but for this, it's the same thing)
And because there's something wrong with the button/icons...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JDialog dialog = new JDialog();
dialog.setUndecorated(true);
dialog.setBackground(new Color(0, 0, 0, 0));
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setAlwaysOnTop(true);
dialog.getRootPane().setOpaque(false);
JPanel panel = new JPanel();
panel.setOpaque(false);
dialog.add(panel);
try {
JButton button = new JButton(new ImageIcon(ImageIO.read(getClass().getResource("/play.png"))));
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setOpaque(false);
panel.add(button);
panel.setBorder(new CompoundBorder(new LineBorder(Color.RED), new EmptyBorder(10, 10, 10, 10)));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
button.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/record.png"))));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
});
}
}

Related

Difference between LookAndFeel behavior

I created a JPopupmenu and i added a JTextField. When I am using metal or nimbus everything is alright. The problem is when I switch LookAndFeel to Windows. I can not press right ALT, because if I press this key, JPopupmenu will hide.
Can I use right ALT to write national signs in Windows LookAndFeel?
import javax.swing.*;
import java.awt.event.*;
public class Popup extends JFrame {
JPopupMenu popup;
JPanel panel;
JTextField field;
public Popup(){
setSize(500,400);
try {
//UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(this);
popup = new JPopupMenu();
field = new JTextField(10);
popup.add(field);
JButton button = new JButton("Options");
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
panel = new JPanel();
panel.add(button);
add(panel);
}
public static void main(String[] args){
Popup pop = new Popup();
pop.setVisible(true);
}
}
JPopupMenu has a very specific set of operation requirements, and yes, they do change between look and feels, that's kind of the point.
What you could do is create you own popup using an undecorated JFrame. The trick here is to mimic as much of the popup as need, for example, auto closer when another component gains focus, the ability to dismiss the popup with the escape key...etc...
This is just a quick example to provide a proof of concept, I'd personally also add a key binding for the escape key, some kind of listener interface to allow the search pane to request that the popup be dismissed and the ability to auto focus some component when the window was made visible, but that's just me...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestPopup {
public static void main(String[] args) {
new TestPopup();
}
public TestPopup() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton show;
public TestPane() {
setLayout(new GridBagLayout());
show = new JButton("...");
show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PopupWindow window = new PopupWindow();
window.show(show, 0, show.getHeight());
}
});
add(show);
}
}
public class SearchPane extends JPanel {
private JList list;
private JTextField search;
public SearchPane() {
setLayout(new BorderLayout());
list = new JList();
list.setPrototypeCellValue("This is just a test");
list.setVisibleRowCount(20);
search = new JTextField(10);
add(new JScrollPane(list));
add(search, BorderLayout.SOUTH);
}
}
public class PopupWindow extends JFrame {
private SearchPane searchPane;
public PopupWindow() {
setUndecorated(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowFocusListener(new WindowFocusListener() {
#Override
public void windowGainedFocus(WindowEvent e) {
}
#Override
public void windowLostFocus(WindowEvent e) {
dispose();
}
});
searchPane = new SearchPane();
add(searchPane);
pack();
}
public void show(JComponent parent, int x, int y) {
Point point = new Point(x, y);
SwingUtilities.convertPointToScreen(point, parent);
setLocation(point);
setVisible(true);
}
}
}

how to display only button with out jframe or jpanel visible?

Example below will display a button with jframe window. I want only button visible, how can it be implement?
public final void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton quitButton = new JButton("Quit");
quitButton.setBounds(50, 60, 80, 30);
quitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
panel.add(quitButton);
setTitle("Quit button");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Depending on what you mean by "with out jframe or jpanel visible?" you create a transparent window...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GhostButton {
public static void main(String[] args) {
new GhostButton();
}
public GhostButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JButton ghostButton = new JButton("Boo!");
ghostButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JFrame frame = new JFrame("Testing");
frame.setUndecorated(true);
frame.setBackground(new Color(0,0,0,0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(ghostButton);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
If you remove frame.setBackground(new Color(0,0,0,0));, you will get a frameless window
ps- This works under Java 7+, there is trick to make it work under Java 6, but I've not posted it here

How do I create a JPanel with two images where only a part of the one below is shown on mouse over?

I am trying to create a button panel where the button that was clicked becomes 'differently colored'; i.e show the background image. p.s I only need this approach(with 2 images), and not anything else. Thanks !
Eg:
public class TestPane extends JPanel {
private BufferedImage imgUnclicked;
private BufferedImage imgClicked;
private Point mousePoint;
public TestPane() {
try {
imgUnclicked = ImageIO.read(new File("C:\\Users\\Me\\Desktop\\tmp\\Uncolored.png"));
imgClicked = ImageIO.read(new File("C:\\Users\\Me\\Desktop\\tmp\\Colored.png"));
} catch (IOException ex) {
Logger.getLogger(Spotlight.class.getName()).log(Level.SEVERE, null, ex);
}
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
mousePoint = e.getPoint();
repaint();
}
});
}
}
#Override
protected void paintComponent(Graphics g) {
//Draw imgClicked
//Draw imgUnclicked with some rectangular area around mouse click subtracted
}
}
No need to reinvent the wheel. Instead use a JToggleButton (appropriately configured). A button will react to both mouse and keyboard input.
import java.awt.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
class ChangeImageOnClick {
public static void main(String[] args) throws Exception {
URL url1 = new URL("http://i.stack.imgur.com/gJmeJ.png");
final Image img1 = ImageIO.read(url1);
URL url2 = new URL("http://i.stack.imgur.com/wCF8S.png");
final Image img2 = ImageIO.read(url2);
Runnable r = new Runnable() {
#Override
public void run() {
JToggleButton btn = new JToggleButton("Click me!");
btn.setIcon(new ImageIcon(img1));
btn.setSelectedIcon(new ImageIcon(img2));
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
JOptionPane.showMessageDialog(null, btn);
}
};
SwingUtilities.invokeLater(r);
}
}
A different idea. Basically, load an image into a JLabel, set the Layout of the label and add two opaque components to it.
By using a simple MouseListener, you can either make the component invisible or transparent based on your needs...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class HideAndShow {
public static void main(String[] args) {
new HideAndShow();
}
public HideAndShow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
try {
BufferedImage img = ImageIO.read(new File("/Users/swhitehead/Dropbox/MegaTokyo/Haibane_Miho___Take_2_by_garrbage.png"));
JLabel label = new JLabel(new ImageIcon(img.getScaledInstance(-1, 200, Image.SCALE_SMOOTH)));
add(label);
label.setLayout(new GridLayout(2, 1));
JPanel top = new JPanel();
top.add(new JLabel("Top"));
JPanel bottom = new JPanel();
bottom.add(new JLabel("Bottom"));
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
((JPanel)e.getComponent()).setOpaque(false);
repaint();
}
};
top.addMouseListener(ma);
bottom.addMouseListener(ma);
label.add(top);
label.add(bottom);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Add an ActionListener to your button and call setIcon with the imgClicked.
Something like this:
JButton btn = new JButton();
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btn.setIcon(imgClicked);
}
});

How to set size of JButton?

i am trying to set size of JButton, but by default it take whole frame, it's height easily set but i can't set it's width & why its behaving like that i don't know.
my code :
JButton btnNewButton = new JButton("");
btnNewButton.setPreferredSize(new Dimension(32,0));
ImageIcon icon = new ImageIcon(this.getClass().getResource("/images/images_Left.png"));
btnNewButton.setIcon(icon);
boxTlacitek.add(btnNewButton);
getContentPane().add(btnNewButton, BorderLayout.NORTH);
any suggestion please ?
Change the layout. Try adding the button to another JPanel then add the panel the frame. BorderLayout will stretch the button across the available width of the panel when the component is placed in the NORTH or SOUTH position
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestBorderLayout {
public static void main(String[] args) {
new TestBorderLayout();
}
public TestBorderLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JButton fat = new JButton("Fat");
JButton skinny = new JButton("Skinny");
JPanel buttonPane = new JPanel();
buttonPane.add(skinny);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(fat, BorderLayout.NORTH);
frame.add(buttonPane, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
getContentPane().setLayout(null);
//setBounds(x,y,width,height)
btnNewButton.setBounds(10,10,250,100);
getContentPane().add(btnNewButton);

JLabel text position

I´m new with JLabel, i wonder if it's possible to set the text in a coordenate specific (x,y) over an image.
Like this:
So the text is "HI"
label.setText("HI");
label.setIcon(icon);
I'm trying to say that label contains an image and a text but i want to locate it in a specific position like the image above.
I don't want to use label.setHorizontalTextPosition(i);
or setVerticalTextPosition(i);
Sorry for my bad english
Thanks in advance ^ ^
By overriding the paintComponent method, text can be drawn in any position.
JLabel label = new JLabel(icon) {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hi", 10, 10); //these are x and y positions
}
};
There are any number of, reasonable, ways to do it.
However, you should avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
GridBagLayout and GridBagConstraints#insets
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class TestPane extends JPanel {
public TestPane() throws IOException {
setLayout(new GridBagLayout());
BufferedImage img = ImageIO.read(...);
JLabel background = new JLabel(new ImageIcon(img));
background.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(1, 46, 9, 0);
gbc.anchor = GridBagConstraints.SOUTH;
gbc.weighty = 1;
JLabel message = new JLabel("Go that way!");
message.setVerticalAlignment(JLabel.BOTTOM);
background.add(message, gbc);
add(background);
}
}
}
Graphics2D
You could paint the text directly onto the image, but as you can see, it becomes considerably more complex
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class TestPane extends JPanel {
public TestPane() throws IOException {
JLabel background = new JLabel();
BufferedImage img = ImageIO.read(...);
Graphics2D g2d = img.createGraphics();
g2d.setFont(background.getFont());
String text = "Go that way!";
FontMetrics fm = g2d.getFontMetrics();
int x = 46 + (((img.getWidth() - 46) - fm.stringWidth(text)) / 2);
int y = (((img.getHeight() - fm.getHeight())) + fm.getAscent()) - 9;
g2d.setColor(Color.BLACK);
g2d.drawString(text, x, y);
g2d.dispose();
background.setIcon(new ImageIcon(img));
add(background);
}
}
}
You can follow this Example, also take a look on setLocation() method for Components like JLabel, also try to use Layouts to manage better the position for each Component.
This guy also work with location with JLabel, you can see how he does the work and apply it in your project.
Example
JLabel label = new JLabel("Hi");
panel.add(label);
//This is to get the width and height
Dimension size = label.getPreferredSize();
//You can change 100(x) and 100(y) for your likes, so you can put that JLabel wherever you want
label.setBounds(100, 100, size.width, size.height);
You'll have to know what x and what y you want to put the JLabel right there.
If you want to do that, just do what tong1 did, but showing the x and y to know where exactly you want it.
Create a Container
Container container= getContentPane();
Add the JLabel on it
container.add(label);
Add an MouseListener() to get the x and y
container.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
//x and y are ints.
x = e.getX();
y = e.getY();
label.setBounds(x,y,150,50);
}
});

Categories

Resources