Transparent JTexfield with background image - java

I wanted to know how to set an image to a JTextField if this is transparent, or how to make my JTextField look like this:
Here's how I make my field transparent, but I can't set its background image:
//Step 1: Remove the border line to make it look like a flat surface.
field.setBorder(BorderFactory.createLineBorder(Color.white, 0));
//Step 2: Set the background color to null to remove the background.
field.setBackground(null);

All Swing components have a concept of transparency, which is controlled via the use of opaque property. Setting the background to null tents to rest the background color of the field to it's UI default.
Having said that, some components can ignore this (partially or completely). In these case we can cheat...
In the following example, set the field transparent via the opaque property, this is important, as the RepaintManager will not paint areas behind components unless they are transparent, and use a fully transparent background color.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
field.setBackground(new Color(0, 0, 0, 0));
field.setOpaque(false);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.RED);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Updated based on comments...
This is a very specific example designed to provide a direct answer to the presented problem. Basically, what this does is creates a custom border and uses an Image to render the "border"
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;
import javax.swing.border.MatteBorder;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
try {
BufferedImage img = ImageIO.read(getClass().getResource("/FieldBorder.png"));
field.setBorder(new ImageBorder(img, 8, 6));
} catch (IOException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImageBorder implements Border {
private BufferedImage img;
private int bottomMargin;
private int leftMargin;
public ImageBorder(BufferedImage img, int leftMargin, int bottomMargin) {
this.img = img;
this.bottomMargin = bottomMargin;
this.leftMargin = leftMargin;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.drawImage(img, x, y + height - img.getHeight(), c);
}
#Override
public Insets getBorderInsets(Component c) {
return new Insets(0, leftMargin, bottomMargin, 0);
}
#Override
public boolean isBorderOpaque() {
return false;
}
}
}
Now, this could also be done using custom painting within the custom Border instead, but was quicker this way ;)
Another option...
Is to simply use a JPanel and add the field and a JLabel holding the border outline together, for example...
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
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.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
field.setBorder(null);
JPanel fieldPane = new JPanel(new GridBagLayout());
fieldPane.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 8, 0, 0);
fieldPane.add(field, gbc);
try {
BufferedImage img = ImageIO.read(getClass().getResource("/FieldBorder.png"));
gbc.insets = new Insets(0, 0, 0, 0);
fieldPane.add(new JLabel(new ImageIcon(img)), gbc);
} catch (IOException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(fieldPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
But this will come down to needs and requirements...
Text field with a background
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.Document;
public class TextFieldBackground {
public static void main(String[] args) {
new TextFieldBackground();
}
public TextFieldBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
TextFieldWithBackground field = new TextFieldWithBackground(40);
try {
field.setBackgroundImage(ImageIO.read(getClass().getResource("/clouds.jpg")));
} catch (IOException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TextFieldWithBackground extends JTextField {
private BufferedImage bg;
public TextFieldWithBackground() {
}
public TextFieldWithBackground(String text) {
super(text);
}
public TextFieldWithBackground(int columns) {
super(columns);
}
public TextFieldWithBackground(String text, int columns) {
super(text, columns);
}
public TextFieldWithBackground(Document doc, String text, int columns) {
super(doc, text, columns);
}
public void setBackgroundImage(BufferedImage bg) {
this.bg = bg;
setOpaque(bg == null);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
if (bg != null) {
int x = 0;
int y = (getHeight() - bg.getHeight()) / 2;
while (x < getWidth()) {
g.drawImage(bg, x, y, this);
x += bg.getWidth();
}
}
super.paintComponent(g);
}
}
}

Related

JAVA: Screenshot after JFrame change just black

I've written a program which makes a screenshot of JFrame by clicking on JMenuItem. If I only run the .java file in Eclipse, everything works and the screenshot shows the JFrame perfectly. But if I open the JFrame as a link from another JFrame, the screenshot is black instead of showing the JFrame. Here's my code:
JFrame1.java:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JFrame1 extends JFrame {
static JFrame1 frame1 = new JFrame1();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void CloseFrame(){
super.dispose();
}
public JFrame1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
JButton ok = new JButton("OK");
getContentPane().add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CloseFrame();
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
}
});
}
}
With a button (ok) I can go to JFrame2.java.
JFrame2.java:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame2.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem screen = new JMenuItem("Screenshot");
screen.addActionListener(new AbstractAction() {
#Override
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
});
file.add(screen);
menubar.add(file);
setJMenuBar(menubar);
}
public JFrame2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
createMenuBar();
}
}
If I click now on "Screenshot", it is just black.
And if I run only JFrame2.java without running JFrame1.java before, the real image is saved.
Why does the screenshot is black after going from one JFrame1 to JFrame2?
You're painting from the wrong frame...
In your first frame, you are doing this...
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
Looks pretty harmless, but, in JFrame2 you are doing this...
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
And...
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
But, frame2 (inside JFrame2) is not visible on the screen.
This is why static is evil and should be avoid. This is also why you should not extend directly from something like JFrame. You can to easily get yourself into a knot of not knowing what is actually on the screen and what you are referencing...
For example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JavaApplication254 {
public static void main(String[] args) {
new JavaApplication254();
}
public JavaApplication254() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JButton btn = new JButton("Click me away...");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TestPane testPane = new TestPane();
SnapshotAction snapshotAction = new SnapshotAction(testPane);
JMenuBar mb = new JMenuBar();
JMenu mnuFile = new JMenu("File");
mnuFile.add(snapshotAction);
mb.add(mnuFile);
JFrame frame = new JFrame("More Testing");
frame.setJMenuBar(mb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(testPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(20, 20, 20, 20));
JLabel label = new JLabel("I be a bananan");
label.setOpaque(true);
label.setBackground(Color.YELLOW);
label.setForeground(Color.RED);
label.setBorder(
new CompoundBorder(
new LineBorder(Color.RED),
new EmptyBorder(20, 20, 20, 20)));
setLayout(new GridBagLayout());
add(label);
}
}
public class SnapshotAction extends AbstractAction {
private JComponent parent;
public SnapshotAction(JComponent parent) {
this.parent = parent;
putValue(NAME, "Take Snapshot...");
}
#Override
public void actionPerformed(ActionEvent e) {
if (parent.isDisplayable()) {
BufferedImage img = new BufferedImage(parent.getWidth(), parent.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
parent.printAll(g2d);
g2d.dispose();
try {
ImageIO.write(img, "png", new File("Snapshot.png"));
Toolkit.getDefaultToolkit().beep();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(parent, "Failed to generate snapshot: " + ex.getMessage());
}
}
}
}
}
Which will output...

Is it possible to set a background image inside JTextArea (including JScrollPane) not all the frame window? [duplicate]

This question already has answers here:
Inserting an image under a JTextArea
(2 answers)
Closed 8 years ago.
I want to set background in JTextArea (having transparency), but I don't have any idea. Maybe it's not very important, but I just want have characteristically program. Please help.
This part of code, I create JTextArea.
notatnik_k = new JTextArea();
JScrollPane scrollPane2 = new JScrollPane(notatnik_k);
scrollPane2.setBounds(20,30, 263,200);
notatnik_k.setEditable(false);
add(scrollPane2);
This photo showing my problem:
Is there a simply way, to do it?
You will need to extend your JTextArea class and create a setBackground(Image image) method. This method would set a field to the image you want to use and then invoke the the repaint method (this.repaint()).
You should then override the paintComponent(Graphics) method to paint the component with the image you set using setBackground(Image image).
I found here on the site this sample of code, and I did a little change but I have one error and don't know why it's incorrect? It's shows error: "The method setBackgroundImage(Image) is undefined for the type JTextArea"
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
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.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BackgroundDemo {
public JTextArea notatnik;
private static void createAndShowUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("BackgroundDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonsPanel = new JPanel();
final JTextArea notatnik = new JTextArea();
JScrollPane scrollPane1 = new JScrollPane(notatnik);
scrollPane1.setBounds(20,270, 380,110);
JButton loadButton = new JButton("Set background");
buttonsPanel.add(loadButton);
loadButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser(System.getProperty("user.home"));
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
Image image = ImageIO.read(fc.getSelectedFile());
if (image != null)
notatnik.setBackgroundImage(image);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
JPanel content = new JPanel(new BorderLayout());
content.add(buttonsPanel, BorderLayout.SOUTH);
frame.add(scrollPane1);
frame.add(content);
frame.setSize(new Dimension(800, 500));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static class MyTextArea extends JTextArea {
private Image backgroundImage;
public MyTextArea() {
super();
setOpaque(false);
}
public void setBackgroundImage(Image image) {
this.backgroundImage = image;
this.repaint();
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
if (backgroundImage != null) {
g.drawImage(backgroundImage, 0, 0, this);
}
super.paintComponent(g);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

How to remove indents in the tabs JTabbedPane?

How to remove the indents around icon tabs in JTabbedPane? i.e. what would this icon was on the full size of the tabs?
You can try next trick with getTabInsets() method of BasicTabbedPaneUI:
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
public class TestFrame extends JFrame {
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
pack();
setVisible(true);
}
private void init() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JTabbedPane pane = new JTabbedPane(JTabbedPane.BOTTOM);
pane.addTab("", new ImageIcon(TestFrame.class.getResource("1111.png")), new JLabel("lbl"));
pane.addTab("test2", new JLabel("lbl2"));
pane.setFocusable(false);
pane.setUI(new BasicTabbedPaneUI() {
#Override
protected Insets getTabInsets(int tabPlacement, int tabIndex) {
return new Insets(0, 0, 0, 0);
}
});
add(pane);
}
public static void main(String... strings) {
new TestFrame();
}
}
Also try calculateTabWidth() and calculateTabHeight().

How to highlight all the text in a JTextPane?

jTextPane1.selectAll();
With the correctly shared events, that command permit to highlight the text in a JTextPane area (I am a bit rusty, I need to not forget to share the "good event focus priorities" ; thank you to : MadProgrammer)
Since selectAll is a method of JTextComponent, which JTextPane extends from I would take a wild guess and say, probably, yes.
Five minutes of coding probably would have gotten you the same answer yourself...
Highlighting not seem to appear in the jTextPane area (note : I use Java 7)
This is likely because the JTextPane doesn't have focus, try using requestFocusInWindow to bring keyboard focus back to the JTextPane.
The JTextComponents don't always render selection highlighting when they don't have focus.
For example...
import java.awt.BorderLayout;
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.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextPane {
public static void main(String[] args) {
new TestTextPane();
}
public TestTextPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JTextPane tp = new JTextPane();
JButton withFocus = new JButton("Select with focus");
withFocus.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tp.selectAll();
tp.requestFocus();
}
});
JButton withOutFocus = new JButton("Select without focus");
withFocus.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tp.selectAll();
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(tp));
JPanel panel = new JPanel();
panel.add(withFocus);
panel.add(withOutFocus);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You could also test it by using
textPane.selectAll();
System.out.println(textPane.getSelectedText());
For example...
And now with double clicking
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextPane {
public static void main(String[] args) {
new TestTextPane();
}
public TestTextPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JTextPane tp = new JTextPane();
JButton withFocus = new JButton("Select with focus");
tp.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
tp.selectAll();
}
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(tp));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

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