Overflow JLabel into Another JLabel - java

Let's say I have a JLabel sized 20x20. Now let's say I add the string "The quick brown fox jumps over the lazy dog." This sentence is too long for the JLabel, so it gets replaces with .... Is there a way that I could get it to overflow to another JLabel, so that the first JLabel would have "The quick brown fox" and the second JLabel would have "jumps over the lazy dog."?
JLabel lbl = new JLabel("The quick brown fox jumps over the lazy dog.");
lbl.setMaximumSize(new Dimension(20, 20));
add(lbl)
Produces a label that says "...".

It would be easier to answer if you provided some more information.
I'm assuming that what you want is two labels that can be placed side by side, or in any other layout. In case the first label's text overflows, the second label will display the remainder.
Here's a solution:
import java.awt.*;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.Override;
import javax.swing.*;
import javax.swing.JLabel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
public class Test extends JFrame {
public Test() {
super("Test overflowing label");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocation(200, 200);
setSize(300, 200);
createUI();
}
private void createUI() {
JLabel label2 = new JLabel();
JLabel label1 = new OverflowingLabel("text to truncate since it's too long ...", label2);
final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, label1, label2);
splitPane.setDividerSize(2);
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
splitPane.setDividerLocation(.5d);
}
});
setContentPane(splitPane);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test test = new Test();
test.setVisible(true);
}
});
}
private class OverflowingLabel extends JLabel {
private JLabel[] dependantLabels;
public OverflowingLabel(String text, JLabel... dependantLabels) {
super(text);
this.dependantLabels = dependantLabels;
addComponentListener(new ComponentAdapter() {
#Override
public void componentShown(ComponentEvent e) {
overflowText();
}
#Override
public void componentResized(ComponentEvent e) {
overflowText();
}
});
}
private void overflowText() {
int index = getIndexToChopText();
String text = getText().substring(index);
for (JLabel dependantLabel : dependantLabels)
dependantLabel.setText(text);
}
private int getIndexToChopText() {
Dimension size = getSize();
FontMetrics metrics = getFontMetrics(getFont());
String text = getText();
int index = 0;
int width = 0;
while ((index < text.length()) && (width < size.width)) {
int charWidth = metrics.charWidth(text.charAt(index));
if ((width + charWidth) > size.width)
break;
index ++;
width += charWidth;
}
return index;
}
#Override
public Dimension getMinimumSize() {
Dimension size = super.getMinimumSize();
return new Dimension(0, size.height);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g.create();
Rectangle clip = g2d.getClipBounds();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
g2d.setColor(getBackground());
g2d.fillRect(clip.x, clip.y, clip.width, clip.height);
g2d.setColor(getForeground());
g2d.setFont(getFont());
FontMetrics metrics = g2d.getFontMetrics();
int baseLine = metrics.getAscent() + metrics.getLeading();
int index = getIndexToChopText();
g2d.drawString(getText().substring(0, index), 0, (getHeight() + baseLine) / 2 - 1);
g2d.dispose();
}
}
}
Here are some screen shots to demonstrate the behavior:

Related

Display buttons one at time [duplicate]

I created a JFrame, and it contains a JPanel. I created a number of JLabels. I can add the JLabels to the JPanel, and display them correctly. But I want to implement them so as they displayed sequentially; a time delay between each JLabel to be displayed.
After searching the StackOverfLow, I tried some code, but it has no effect!. So How to use a timer to make components(Labels) displayed one after the other by setting a time delay.
I Don't want a fix for my code particularly in the answer. Just show how to display any type of components in a delayed manner, each component displayed after a period of time. That is all. I provided my code to show my effort in trying to solve the problem.
First this is a subclass of JLabel to use: (No problems with it)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
public class DLabel extends JLabel
{
Dimension size = new Dimension(70, 75);
Font font = new Font(Font.SANS_SERIF, 12, 35);
public DLabel(String t)
{
this.setPreferredSize(size);
this.setBorder(BorderFactory.createBevelBorder(1, Color.white, Color.black));
this.setVerticalAlignment(JLabel.CENTER);
this.setHorizontalAlignment(JLabel.CENTER);
this.setText(t);
this.setFont(font);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Color color1 = new Color(226, 218, 145);
Color color2 = color1.brighter();
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(
0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
super.paintComponent(g);
}
}
The other class that use the DLabel class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
public class DelayedLabels extends JPanel
{
static JFrame frame;
Timer timer; //timer to be used for dealy
DLabel card_1; //Defining the DLabels
DLabel card_2;
DLabel card_3;
JLabel[] labelsArray;
public DelayedLabels()
{
this.setLayout(null);
card_1 = new DLabel("1");
card_2 = new DLabel("2");
card_3 = new DLabel("3");
labelsArray = new DLabel[3]; //create the array
createLabelsArray(); //add the Labels Objects to labelsArray
setLabelsLocations(labelsArray); // set the locations of the Labels to be displayed on the JPanel
addLabelsToPanel(labelsArray); //The adding of the Labels to the JPanel
}
private void createLabelsArray()
{
labelsArray[0] = card_1;
labelsArray[1] = card_2;
labelsArray[2] = card_3;
}
private void setLabelsLocations(JLabel[] labels)
{
int length = labels.length;
int gap = 10;
int counter = 10;
for (int i = 0; i < length; i++)
{
labels[i].setBounds(170, counter, 60, 70);
counter = counter + labels[i].getBounds().height + gap;
}
}
private void addLabelsToPanel(JLabel[] labels)
{
for (int i = 0; i < labels.length; i++)
{
frame.revalidate();
frame.repaint();
this.add(labels[i]);
timer = new Timer(1000, timerAction); //timer to use with 1000 milliseconds
timer.start();
}
}
private ActionListener timerAction = new ActionListener() //action to be invoked after each label added
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.revalidate();
frame.repaint();
}
};
private static void createAndShowGUI()
{
frame = new JFrame();
frame.setSize(600, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DelayedLabels demo = new DelayedLabels();
demo.setOpaque(true);
frame.add(demo);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DelayedLabels extends JPanel {
static JFrame frame;
Timer timer; //timer to be used for dealy
JLabel card_1; //Defining the JLabels
JLabel card_2;
JLabel card_3;
JLabel[] labelsArray;
ActionListener listener;
public DelayedLabels() {
listener = new ActionListener() {
int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
Component c = DelayedLabels.this.getTopLevelAncestor();
DelayedLabels.this.add(labelsArray[i++]);
c.validate();
c.repaint();
if (i==labelsArray.length) {
timer.stop();
}
}
};
this.setLayout(new GridLayout(0, 1, 20, 20));
card_1 = new JLabel("Label 1");
card_2 = new JLabel("Label 2");
card_3 = new JLabel("Label 3");
labelsArray = new JLabel[3]; //create the array
createLabelsArray(); //add the Labels Objects to labelsArray
timer = new Timer(1000,listener);
timer.start();
}
private void createLabelsArray() {
labelsArray[0] = card_1;
labelsArray[1] = card_2;
labelsArray[2] = card_3;
}
private static void createAndShowGUI() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DelayedLabels demo = new DelayedLabels();
demo.setOpaque(true);
frame.add(demo, BorderLayout.PAGE_START);
frame.pack();
frame.setSize(200, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}

JPanel causing extra space to the side?

I made a simple program that uses drawString() to draw on a JPanel that gets repainted to change the background to a random color. It works fine, other than the ~10 pixel spaces to the right side and bottom side of the JPanel, which remain the default color. I think this problem might be happening because of the way I use pack() or getPrefferedSize(). Any help or suggestions to fix this are appreciated.
Birthday.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Birthday {
DrawString panel = new DrawString();
public Birthday() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
f.setTitle("Happy Birthday!");
f.setLocation(10, 10);
f.pack();
f.setVisible(true);
f.setResizable(false);
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
});
timer.start();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Birthday();
}
});
}
}
DrawString.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawString extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int x = 350;
int y = 250;
int red = random(0,255);
int green = random(0,255);
int blue = random(0,255);
Color black = new Color(0,0,0);
Color newColor = new Color(red,green,blue);
g.setColor(newColor);
g.fillRect(0,0,1000,500);
g.setColor(black);
g.setFont(new Font(null,Font.BOLD,40));
g.drawString("Happy Birthday!",x,y);
}
public static int random(int min, int max)
{
int range = max - min + 1;
int number = (int) (range * Math.random() + min);
return number;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1000, 500);
}
}
You never want to explicitly call paintComponent. Instead if you want the panel to repaint, you can call panel.repaint(), and the panel with implicitly call its own paintComponent method for you.
Don't do every thing inside the main method, you'll find you're going to run into a lot of problems with static references.
Don't use Thread.sleep(), it will block the Event Dispatch Thread., as that's where you should be running you Swing apps from. Instead use a java.swing.Timer. See this example for Timer usage.
As noted in 3, run your Swing apps from the EDT like this
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new MyApp();
}
});
}
Don't set the size of your frame. Instead override getPreferredSize() of your DrawingPanel and just pack() the frame.
You can center the frame by using setLocationRelativeTo(null)
Should make it a habit to use the #Override annotation to make sure you are override correctly.
Add-on to 2. What you make a habit of doing, is doing your work from the constructor, then just calling the constructor in the main. Here is a refactor of your code with all the above mentioned things fixed. You can run it.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Birthday {
DrawString panel = new DrawString();
public Birthday() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
f.setTitle("Happy Birthday!");
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setResizable(false);
Timer timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
});
timer.start();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Birthday();
}
});
}
}
class DrawString extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int x = 350;
int y = 250;
int red = random(0, 255);
int green = random(0, 255);
int blue = random(0, 255);
Color black = new Color(0, 0, 0);
Color newColor = new Color(red, green, blue);
g.setColor(newColor);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(black);
g.setFont(new Font(null, Font.BOLD, 40));
g.drawString("Happy Birthday!", x, y);
}
public static int random(int min, int max) {
int range = max - min + 1;
int number = (int) (range * Math.random() + min);
return number;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1000, 500);
}
}

Deleting images from JFrame

I created one JFrame. and set layout shown in below code
this.setLayout(new GridLayout());
JPanel panel=new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new PicturePanel1());
JTabbedPane jtp=new JTabbedPane();
jtp.addTab("show Images", panel);
jtp.addTab("Compare Image", new JButton());
this.add(jtp);
I created another class that draws Images from particular location.
protected void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g2 = (Graphics2D) g;
int k = 20,y=10;
for (int j = 0; j <= listOfFiles.length - 1; j++) {
g2.drawImage(b[j], k, y, 100, 100, null);
// add(new javax.swing.JCheckBox());
k = k + 120;
if(k>=960)
{
k=20;
y=y+120;
}
}
Its working fine. I want to delete Images when user clicks on particular Image.
This is my output window. I want to delete Image from list.
Here is an example I made (bored and tired of studying :)). It is by no means the best just a quick thing to show you an example, click the image you want to delete and then press the delete button or DEL to remove and image from the panel:
When app starts up (orange just shows focused label for hovering):
Image to delete is selected by clicking on the Label (Border becomes green highlighted and will remain this way until another label is clicked):
After delete button or key is pressed:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class JavaApplication5 {
public static void main(String[] args) {
createAndShowJFrame();
}
public static void createAndShowJFrame() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = createJFrame();
frame.setVisible(true);
}
});
}
private static JFrame createJFrame() {
JFrame frame = new JFrame();
//frame.setResizable(false);//make it un-resizeable
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Test");
ArrayList<BufferedImage> images = null;
try {
images = getImagesArrayList();
} catch (Exception ex) {
ex.printStackTrace();
}
final ImageViewPanel imageViewPanel = new ImageViewPanel(images);
JScrollPane jsp = new JScrollPane(imageViewPanel);
jsp.setPreferredSize(new Dimension(400, 400));
frame.add(jsp);
JPanel controlPanel = new JPanel();
JButton addLabelButton = new JButton("Delete Selected Image");
addLabelButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
imageViewPanel.removeFocusedImageLabel();
}
});
controlPanel.add(addLabelButton);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.pack();
return frame;
}
private static ArrayList<BufferedImage> getImagesArrayList() throws Exception {
ArrayList<BufferedImage> images = new ArrayList<>();
images.add(resize(ImageIO.read(new URL("http://icons.iconarchive.com/icons/deleket/sleek-xp-software/256/Yahoo-Messenger-icon.png")), 100, 100));
images.add(resize(ImageIO.read(new URL("https://upload.wikimedia.org/wikipedia/commons/6/64/Gnu_meditate_levitate.png")), 100, 100));
return images;
}
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
}
class ImageViewPanel extends JPanel {
JLabel NO_IMAGES = new JLabel("No Images");
ArrayList<BufferedImage> images;
ArrayList<MyLabel> imageLabels;
public ImageViewPanel(ArrayList<BufferedImage> images) {
this.images = images;
imageLabels = new ArrayList<>();
for (BufferedImage bi : images) {
imageLabels.add(new MyLabel(new ImageIcon(bi), this));
}
layoutLabels();
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, true), "Delete pressed");
getActionMap().put("Delete pressed", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
removeFocusedImageLabel();
}
});
}
void removeFocusedImageLabel() {
if (focusedLabel == null) {
return;
}
imageLabels.remove(focusedLabel);
remove(focusedLabel);
layoutLabels();
}
private void layoutLabels() {
if (imageLabels.isEmpty()) {
add(NO_IMAGES);
} else {
remove(NO_IMAGES);
for (JLabel il : imageLabels) {
add(il);
}
}
revalidate();
repaint();
}
private MyLabel focusedLabel;
void setFocusedLabel(MyLabel labelToFocus) {
if (focusedLabel != null) {
focusedLabel.setBorder(null);
focusedLabel.setClicked(false);
}
focusedLabel = labelToFocus;
focusedLabel.setBorder(new LineBorder(Color.GREEN));
}
}
class MyLabel extends JLabel {
private final ImageViewPanel imageViewPanel;
private boolean clicked = false;
public MyLabel(Icon image, ImageViewPanel imageViewPanel) {
super(image);
this.imageViewPanel = imageViewPanel;
initLabel();
}
public MyLabel(String text, ImageViewPanel imageViewPanel) {
super(text);
this.imageViewPanel = imageViewPanel;
initLabel();
}
private void initLabel() {
setFocusable(true);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
clicked = true;
imageViewPanel.setFocusedLabel(MyLabel.this);
}
#Override
public void mouseEntered(MouseEvent me) {
super.mouseEntered(me);
if (clicked) {
return;
}
setBorder(new LineBorder(Color.ORANGE));
//call for focus mouse is over this component
requestFocusInWindow();
}
});
addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
super.focusLost(e);
if (clicked) {
return;
}
setBorder(null);
}
});
}
public void setClicked(boolean clicked) {
this.clicked = clicked;
}
public boolean isClicked() {
return clicked;
}
}
simply find the location (x, and y) and the size(width, and height) of image, then with the Graphics object (g2) fill a rectangle over the image drawn, like this
g2.setColor(this.getBackground());//set the color you want to clear the bound this point to JFrame/JPanel
g2.fillRect(x, y, width, height);
where x and y where is the location that images is located, and width and height are size of the picture

Drawing warning symbol during form validation in Swing

I have developed a swing form which validates entries as the focus is lost from JTextComponent
and if the entry is correct ,the background is painted green Otherwise it is painted red.
Here is the code :-
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
public class Form extends JFrame implements FocusListener{
JTextField fname,lname,phone,email,address;
BufferedImage img;
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){public void run(){new Form();}});
}
public Form()
{
super("Form with Validation Capability");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
setLayout(new GridLayout(5,3));
try {
img=ImageIO.read(new File("src/warning.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
add(new JLabel("First Name :"));
add(fname=new JTextField(20));
add(new JLabel("Last Name :"));
add(lname=new JTextField(20));
add(new JLabel("Phone Number :"));
add(phone=new JTextField(10));
add(new JLabel("Email:"));
add(email=new JTextField(20));
add(new JLabel("Address :"));
add(address=new JTextField(20));
fname.addFocusListener(this);
lname.addFocusListener(this);
phone.addFocusListener(this);
email.addFocusListener(this);
address.addFocusListener(this);
setVisible(true);
}
public void focusGained(FocusEvent e)
{
((JTextComponent) e.getSource()).setBackground(Color.WHITE);
}
public void focusLost(FocusEvent e)
{
if(e.getSource().equals(fname))
{
validationForText(fname);
}
else if(e.getSource().equals(lname))
{
validationForText(lname);
}
else if(e.getSource().equals(email))
{
validationForEmail(email);
}
else if(e.getSource().equals(phone))
{
validationForNumber(phone);
}
else{
((JTextComponent) e.getSource()).setBackground(Color.GREEN);
}
}
public void validationForText(JTextComponent comp)
{
String temp=comp.getText();
if (temp.matches("^[A-Za-z]+$")) {
comp.setBackground(Color.GREEN);
}
else
comp.setBackground(Color.RED);
}
public void validationForNumber(JTextComponent comp)
{
String text=comp.getText();
if(text.matches("^[0-9]+$"))
comp.setBackground(Color.GREEN);
else
comp.setBackground(Color.RED);
}
public void validationForEmail(JTextComponent comp)
{
String text=comp.getText();
if(text.matches("[^#]+#([^.]+\\.)+[^.]+"))
comp.setBackground(Color.GREEN);
else
comp.setBackground(Color.RED);
}
}
Here is the output to my simple app :
Now I also want to draw a warning symbol (buffered image) at the lower left corner of incorrect field.Can anyone help me how to do this as i am not understanding where to paint the image.
(I would like to do it using JLayeredPane as I am learning its application,any code snippet will really help).
Why not simply add a JLabel (using an appropriate LayoutManager to position it) with the inbuilt Swing warning icon UIManager.getIcon("OptionPane.warningIcon")
like so:
JLabel label=new JLabel(UIManager.getIcon("OptionPane.warningIcon"));
see here for more.
UPDATE:
As per your comment I would rather use GlassPane (and add JLabel to glasspane) for this as opposed too JLayeredPane. See here for more on RootPanes
Some suggestions:
Dont extend JFrame unnecessarily
Dont call setSize on JFrame. Use a correct LayoutManager and/or override getPreferredSize() where necessary and replace setSize call with pack() just before setting JFrame visible.
Dont implement FocusListener on the class unless you want to share the functionality with other classes.
Also get into the habit of using FocusAdapter vs FocusListener this applies to a few with appended Listener i.e MouseListener can be replaced for MouseAdapter. This allows us to only override the methods we want. In this case listener is correct as we do something on both overridden methods, but as I said more about the habit
Also always call super.XXX implementation of overridden methods i.e focusGained(FocusEvent fe) unless you are ignoring it for a reason
Here is code with above fixes including glasspane to show warning icon when field is red:
And removes it when is corrected:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;
/**
*
* #author David
*/
public class GlassValidationPane extends JComponent {
private static JTextField fname, lname, phone, email, address;
private static GlassValidationPane gvp = new GlassValidationPane();
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Form with Validation Capability");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f.setResizable(false);
f.setLayout(new GridLayout(5, 3));
f.add(new JLabel("First Name :"));
f.add(fname = new JTextField(20));
f.add(new JLabel("Last Name :"));
f.add(lname = new JTextField(20));
f.add(new JLabel("Phone Number :"));
f.add(phone = new JTextField(10));
f.add(new JLabel("Email:"));
f.add(email = new JTextField(20));
f.add(new JLabel("Address :"));
f.add(address = new JTextField(20));
f.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent ce) {
super.componentResized(ce);
gvp.refreshLocations();
}
});
FocusAdapter fl = new FocusAdapter() {
#Override
public void focusGained(FocusEvent fe) {
super.focusGained(fe);
((JTextComponent) fe.getSource()).setBackground(Color.WHITE);
}
#Override
public void focusLost(FocusEvent fe) {
super.focusLost(fe);
if (fe.getSource().equals(fname)) {
validationForText(fname);
} else if (fe.getSource().equals(lname)) {
validationForText(lname);
} else if (fe.getSource().equals(email)) {
validationForEmail(email);
} else if (fe.getSource().equals(phone)) {
validationForNumber(phone);
} else {
gvp.removeWarningIcon(((Component) fe.getSource()));
((JTextComponent) fe.getSource()).setBackground(Color.GREEN);
}
}
};
fname.addFocusListener(fl);
lname.addFocusListener(fl);
phone.addFocusListener(fl);
email.addFocusListener(fl);
address.addFocusListener(fl);
f.setGlassPane(gvp);
f.pack();
f.setVisible(true);
gvp.setVisible(true);
}
public void validationForText(JTextComponent comp) {
String temp = comp.getText();
if (temp.matches("^[A-Za-z]+$")) {
setGreen(comp);
} else {
setRed(comp);
}
}
public void validationForNumber(JTextComponent comp) {
String text = comp.getText();
if (text.matches("^[0-9]+$")) {
setGreen(comp);
} else {
setRed(comp);
}
}
public void validationForEmail(JTextComponent comp) {
String text = comp.getText();
if (text.matches("[^#]+#([^.]+\\.)+[^.]+")) {
setGreen(comp);
} else {
setRed(comp);
}
}
private void setRed(JTextComponent comp) {
comp.setBackground(Color.RED);
gvp.showWarningIcon(comp);
}
private void setGreen(JTextComponent comp) {
comp.setBackground(Color.GREEN);
gvp.removeWarningIcon(comp);
}
});
}
private HashMap<Component, JLabel> warningLabels = new HashMap<>();
private ImageIcon warningIcon;
public GlassValidationPane() {
setLayout(null);//this is the exception to the rule case a layoutmanager might make setting Jlabel co-ords harder
setOpaque(false);
Icon icon = UIManager.getIcon("OptionPane.warningIcon");
int imgW = icon.getIconWidth();
int imgH = icon.getIconHeight();
BufferedImage img = ImageUtilities.getBufferedImageOfIcon(icon, imgW, imgH);
warningIcon = new ImageIcon(ImageUtilities.resize(img, 24, 24));
}
void showWarningIcon(Component c) {
if (warningLabels.containsKey(c)) {
return;
}
JLabel label = new JLabel();
label.setIcon(warningIcon);
//int x=c.getX();//this will make it insode the component
int x = c.getWidth() - label.getIcon().getIconWidth();//this makes it appear outside/next to component
int y = c.getY();
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
add(label);
label.setVisible(true);
revalidate();
repaint();
warningLabels.put(c, label);
}
public void removeWarningIcon(Component c) {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component component = entry.getKey();
JLabel jLabel = entry.getValue();
if (component == c) {
remove(jLabel);
revalidate();
repaint();
break;
}
}
warningLabels.remove(c);
}
public void refreshLocations() {
for (Map.Entry<Component, JLabel> entry : warningLabels.entrySet()) {
Component c = entry.getKey();
JLabel label = entry.getValue();
//int x=c.getX();//this will make it insode the component
int x = c.getWidth() - label.getIcon().getIconWidth();//this makes it appear outside/next to component
int y = c.getY();
label.setBounds(x, y, label.getIcon().getIconWidth(), label.getIcon().getIconHeight());
revalidate();
repaint();
}
}
}
class ImageUtilities {
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
public static BufferedImage getBufferedImageOfIcon(Icon icon, int imgW, int imgH) {
BufferedImage img = new BufferedImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
return img;
}
}

How to auto-adjust font size of multiple JLabel based on container size in a smooth way?

I need to resize the font of multiple JLabel based on the scaling factor used to resize the container. To do this, I am setting the font of each JLabel to null so that they take the font of the container. It works, but it also produces strange results.
To be specific, the text seems to "lag" behind the container and sometimes it gets even truncated. I would like to avoid this behavior. Any idea how?
Example code simulating the behavior:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.geom.AffineTransform;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TextResize implements Runnable {
public static void main(String[] args) {
TextResize example = new TextResize();
SwingUtilities.invokeLater(example);
}
public void run() {
JFrame frame = new JFrame("JLabel Text Resize");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(800, 400));
Container container = frame.getContentPane();
container.setLayout(new BorderLayout());
final JPanel labelContainer = new JPanel(new GridBagLayout());
labelContainer.setBorder(BorderFactory.createLineBorder(Color.black));
//initial font
final Font textFont = new Font("Lucida Console", Font.PLAIN, 10).deriveFont(AffineTransform.getScaleInstance(1, 1));
labelContainer.setFont(textFont);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(0, 10, 0, 10);
c.weightx = 1;
for (int i = 0; i < 5; i++) {
JLabel f = new JLabel("Text here with possibly looooooooong words");
f.setBorder(BorderFactory.createLineBorder(Color.green));
f.setFont(null);//take the font from parent
c.gridy = i;
labelContainer.add(f, c);
}
JSlider slider = new JSlider(0,50000,10000);
slider.addChangeListener(new ChangeListener() {
double containerWidth = labelContainer.getPreferredSize().getWidth();
double containerHeight = labelContainer.getPreferredSize().getHeight();
#Override
public void stateChanged(ChangeEvent ev) {
JSlider source = (JSlider) ev.getSource();
double scale = (double) (source.getValue() / 10000d);
//scaling the container
labelContainer.setSize((int) (containerWidth * scale), (int) (containerHeight * scale));
//adjusting the font: why does it 'lag' ? why the truncation at times?
Font newFont = textFont.deriveFont(AffineTransform.getScaleInstance(scale, scale));
labelContainer.setFont(newFont);
//print (font.getSize() does not change?)
System.out.println(scale + " " + newFont.getTransform() + newFont.getSize2D());
}
});
container.add(slider, BorderLayout.NORTH);
JPanel test = new JPanel();
test.setLayout(null);
labelContainer.setBounds(5, 5, labelContainer.getPreferredSize().width, labelContainer.getPreferredSize().height);
test.add(labelContainer);
container.add(test, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
Picture:
http://i.stack.imgur.com/tZLOO.png
Thanks,
-s
You can use any of the following methods:
by #trashgod
by #StanislavL
by #coobird
I sort of solved the problem adding:
#Override
protected void paintComponent(Graphics g) {
final Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
super.paintComponent(g2d);
}
Thanks anyway.
If performance speed is an issue, then you might find the following information about the 3 methods pointed to by MKorbel above useful.
Coobird's code has some limitations if used on a multi-call basis (eg in a sizeChanged Listener or a LayoutManager)
Trashgod's method is between 2 and 4 times slower than Stanislav's (but it also is designed to fill the area BOTH directions as the OP asked in that question, so not unexpected.)
The code below improves on Stanislav's rectangle method (by starting from the current font size each time rather than reverting back to MIN_FONT_SIZE each time) and thus runs between 20 and 50 times faster than that code, especially when the window/font is large.
It also addresses a limitation in that code which only effectively works for labels located at 0,0 (as in the sample given there). The code below works for multiple labels on a panel and at any location.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
// Improved version of http://java-sl.com/tip_adapt_label_font_size.html
public class FontResizingLabel extends JLabel {
public static final int MIN_FONT_SIZE=3;
public static final int MAX_FONT_SIZE=240;
Graphics g;
int currFontSize = 0;
public FontResizingLabel(String text) {
super(text);
currFontSize = this.getFont().getSize();
init();
}
protected void init() {
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
adaptLabelFont(FontResizingLabel.this);
}
});
}
protected void adaptLabelFont(JLabel l) {
if (g==null) {
return;
}
currFontSize = this.getFont().getSize();
Rectangle r = l.getBounds();
r.x = 0;
r.y = 0;
int fontSize = Math.max(MIN_FONT_SIZE, currFontSize);
Font f = l.getFont();
Rectangle r1 = new Rectangle(getTextSize(l, l.getFont()));
while (!r.contains(r1)) {
fontSize --;
if (fontSize <= MIN_FONT_SIZE)
break;
r1 = new Rectangle(getTextSize(l, f.deriveFont(f.getStyle(), fontSize)));
}
Rectangle r2 = new Rectangle();
while (fontSize < MAX_FONT_SIZE) {
r2.setSize(getTextSize(l, f.deriveFont(f.getStyle(),fontSize+1)));
if (!r.contains(r2)) {
break;
}
fontSize++;
}
setFont(f.deriveFont(f.getStyle(),fontSize));
repaint();
}
private Dimension getTextSize(JLabel l, Font f) {
Dimension size = new Dimension();
//g.setFont(f); // superfluous.
FontMetrics fm = g.getFontMetrics(f);
size.width = fm.stringWidth(l.getText());
size.height = fm.getHeight();
return size;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.g=g;
}
public static void main(String[] args) throws Exception {
FontResizingLabel label=new FontResizingLabel("Some text");
JFrame frame=new JFrame("Resize label font");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label);
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Categories

Resources