automatically highlights words in the textpane - java

I have this code from java2s.com and I just modified it. I don't know if I need to use the runnable or the documentlistener so that the application will automatically highlight the word that was defined in the code. I don't have much knowledge about the two, I tried the runnable but I encountered errors. Can someone help me? Here's the code.
public class Sample {
public static void main(String[] args) {
JFrame f = new JFrame();
JTextPane textPane = new JTextPane();
String word = "";
Highlighter highlighter = new UnderlineHighlighter(null);
textPane.setHighlighter(highlighter);
textPane.setText("This is a test");
final WordSearcher searcher = new WordSearcher(textPane);
final UnderlineHighlighter uhp = new UnderlineHighlighter(Color.red);
String w = "i";
int offset = searcher.search(w);
if (offset == -1) {
return;
}
try {
textPane.scrollRectToVisible(textPane.modelToView(offset));
} catch (BadLocationException ex) {
}
textPane.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void removeUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void changedUpdate(DocumentEvent evt) {
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f.add(panel, "South");
f.add(new JScrollPane(textPane), "Center");
f.setSize(400, 400);
f.setVisible(true);
}
public static String word;
public static Highlighter highlighter = new UnderlineHighlighter(null);
}
class WordSearcher {
public WordSearcher(JTextComponent comp) {
this.comp = comp;
this.painter = new UnderlineHighlighter.UnderlineHighlightPainter(
Color.red);
}
public int search(String word) {
int firstOffset = -1;
Highlighter highlighter = comp.getHighlighter();
Highlighter.Highlight[] highlights = highlighter.getHighlights();
for (int i = 0; i < highlights.length; i++) {
Highlighter.Highlight h = highlights[i];
if (h.getPainter() instanceof
UnderlineHighlighter.UnderlineHighlightPainter) {
highlighter.removeHighlight(h);
}
}
if (word == null || word.equals("")) {
return -1;
}
String content = null;
try {
Document d = comp.getDocument();
content = d.getText(0, d.getLength()).toLowerCase();
} catch (BadLocationException e) {
// Cannot happen
return -1;
}
word = word.toLowerCase();
int lastIndex = 0;
int wordSize = word.length();
while ((lastIndex = content.indexOf(word, lastIndex)) != -1) {
int endIndex = lastIndex + wordSize;
try {
highlighter.addHighlight(lastIndex, endIndex, painter);
} catch (BadLocationException e) {
// Nothing to do
}
if (firstOffset == -1) {
firstOffset = lastIndex;
}
lastIndex = endIndex;
}
return firstOffset;
}
protected JTextComponent comp;
protected Highlighter.HighlightPainter painter;
}
class UnderlineHighlighter extends DefaultHighlighter {
public UnderlineHighlighter(Color c) {
painter = (c == null ? sharedPainter : new UnderlineHighlightPainter(c));
}
public Object addHighlight(int p0, int p1) throws BadLocationException {
return addHighlight(p0, p1, painter);
}
public void setDrawsLayeredHighlights(boolean newValue) {
// Illegal if false - we only support layered highlights
if (newValue == false) {
throw new IllegalArgumentException(
"UnderlineHighlighter only draws layered highlights");
}
super.setDrawsLayeredHighlights(true);
}
public static class UnderlineHighlightPainter extends
LayeredHighlighter.LayerPainter {
public UnderlineHighlightPainter(Color c) {
color = c;
}
public void paint(Graphics g, int offs0, int offs1, Shape bounds,
JTextComponent c) {
// Do nothing: this method will never be called
}
public Shape paintLayer(Graphics g, int offs0, int offs1, Shape bounds,
JTextComponent c, View view) {
g.setColor(color == null ? c.getSelectionColor() : color);
Rectangle alloc = null;
if (offs0 == view.getStartOffset() && offs1 == view.getEndOffset()) {
if (bounds instanceof Rectangle) {
alloc = (Rectangle) bounds;
} else {
alloc = bounds.getBounds();
}
} else {
try {
Shape shape = view.modelToView(offs0,
Position.Bias.Forward, offs1,
Position.Bias.Backward, bounds);
alloc = (shape instanceof Rectangle) ? (Rectangle) shape
: shape.getBounds();
} catch (BadLocationException e) {
return null;
}
}
FontMetrics fm = c.getFontMetrics(c.getFont());
int baseline = alloc.y + alloc.height - fm.getDescent() + 1;
g.drawLine(alloc.x, baseline, alloc.x + alloc.width, baseline);
g.drawLine(alloc.x, baseline + 1, alloc.x + alloc.width,
baseline + 1);
return alloc;
}
protected Color color; // The color for the underline
}
protected static final Highlighter.HighlightPainter sharedPainter = new
UnderlineHighlightPainter(
null);
protected Highlighter.HighlightPainter painter;
}

Maybe your code has some import errors? It runs fine with Java 1.8. In this situation it is Ok to use DocumentListener. Made some modifications in main class for finding text "test":
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;
import java.awt.*;
public class Sample {
public static void main(String[] args) {
JFrame f = new JFrame();
JTextPane textPane = new JTextPane();
String word = "test";
Highlighter highlighter = new UnderlineHighlighter(null);
textPane.setHighlighter(highlighter);
textPane.setText("This is a test");
final WordSearcher searcher = new WordSearcher(textPane);
final UnderlineHighlighter uhp = new UnderlineHighlighter(Color.red);
String w = "i";
int offset = searcher.search(w);
if (offset == -1) {
return;
}
try {
textPane.scrollRectToVisible(textPane.modelToView(offset));
} catch (BadLocationException ex) {
}
textPane.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void removeUpdate(DocumentEvent evt) {
searcher.search(word);
}
#Override
public void changedUpdate(DocumentEvent evt) {
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(textPane), "Center");
f.setSize(400, 400);
f.setVisible(true);
searcher.search(word);
}
public static String word;
public static Highlighter highlighter = new UnderlineHighlighter(null);
}
}

Related

If there are two and more stickers in one column, not every sticker you click responds to it, showing the JToolBar with buttons

I'm trying to write a kanban board. But if there are two and more stickers in one column, often the JToolBar with buttons will be shown only if you click on a sticker in this column for the firs time.
I thought that there were some problems with coordinates, but I didn't found it. The StickerListener responds th event, even prints "условие работает" if coordinates are correct, but the JToolBar remainds invisible.
import java.awt.*;
import javax.swing.*;
public class Main {
public static void main(String[] args)
{
Window window = new Window();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame {
public JButton Edit;
public JButton Read;
public JButton Delete;
private Window window;
private JToolBar jtb;
public boolean stickerToolBarActivated;
public Window() {
window= this;
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
Desk d = new Desk();
createMenu(d);
add(d);
setDefaultSizeToProgressTypesColumns(d, this);
d.setBackground(new Color(255, 255, 255));
StickerListener sl = new StickerListener(d, this);
this.addMouseMotionListener(sl);
this.addMouseListener(sl);
this.addComponentListener(new ComponentListener() {
public void componentResized(ComponentEvent e) {
setDefaultSizeToProgressTypesColumns(d,window);
}
#Override
public void componentMoved(ComponentEvent e) {}
#Override
public void componentShown(ComponentEvent e) {}
#Override
public void componentHidden(ComponentEvent e) {}
});
jtb = new JToolBar();
Edit = new JButton("Редактровать");
jtb.add(Edit);
Delete = new JButton("Удалить");
jtb.add(Delete);
Read = new JButton("Просмотреть");
jtb.add(Read);
add(jtb, BorderLayout.NORTH);
jtb.setVisible(false);
stickerToolBarActivated=false;
setVisible(true);
}
private void createMenu(Desk d)
{
JMenuBar menuBar = new JMenuBar();
JMenu DeskFile = new JMenu("Файл");
JMenuItem SaveDesk = new JMenuItem("Сохранить доску");
DeskFile.add(SaveDesk);
menuBar.add(DeskFile);
JMenu StickerOptions = new JMenu("Стикер");
JMenuItem NewSticker = new JMenuItem("Добавить стикер");
NewSticker.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
d.ProgressTypes.get(0).addSticker();
setDefaultSizeToProgressTypesColumns(d, window);
d.repaint();
}
});
StickerOptions.add(NewSticker);
menuBar.add(StickerOptions);
add(menuBar, BorderLayout.NORTH);
setJMenuBar(menuBar);
}
public JToolBar getStickerToolbar() {
return jtb;
}
public static void setDefaultSizeToProgressTypesColumns(Desk d, Window window)
{
int x=0;
int y=0;
int WindowWidth = window.getWidth();
int WindowHeight = window.getHeight();
int ptCount = d.ProgressTypes.size();
for(ProgressType pt: d.ProgressTypes)
{
pt.x=x;
pt.y=y;
pt.width= WindowWidth/ptCount;
pt.height = WindowHeight;
x+=pt.width;
for(int s=0; s<pt.stickers.size(); ++s) {
pt.stickers.get(s).setWidth(pt.width);
pt.stickers.get(s).setHeight(pt.width);
pt.stickers.get(s).y=pt.height/20+pt.width*s;
pt.stickers.get(s).x=pt.x;
}
}
}
public JButton getEdit() {
return Edit;
}
}
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class Desk extends JPanel {
public ArrayList<ProgressType> ProgressTypes;
public int width;
public Desk()
{
ProgressTypes = new ArrayList<ProgressType>();
ProgressTypes.add(new ProgressType("Идеи"));
ProgressTypes.add(new ProgressType("Сделать"));
ProgressTypes.add(new ProgressType("В процессе"));
ProgressTypes.add(new ProgressType("Тестируется"));
ProgressTypes.add(new ProgressType("Готово"));
}
#Override
public void paint(Graphics g) {
super.paint(g);
for(ProgressType pt: ProgressTypes) {
pt.paint(g);
}
for(ProgressType pt: ProgressTypes)
for(Sticker s : pt.stickers)
s.paint(g);
}
}
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class ProgressType extends JPanel {
public ArrayList<Sticker> stickers;
public String name;
public int x, y, width, height;
public ProgressType(String n)
{
this.name = n;
stickers = new ArrayList<>();
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
final BasicStroke borderLine = new BasicStroke(4.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND, 5.0f);
g2d.setStroke(borderLine);
g2d.setColor(Color.black);
g2d.drawLine(x, y, x+width, y);
g2d.drawLine(x, y, x, y+height);
g2d.drawLine(x, y+height/20, x+width, y+height/20); //height/20 это высота шапки таблицы
g2d.drawLine(x+width, y, x+width, y+height);
}
public int findSticker(String search) {
for(int i=0; i<stickers.size(); ++i)
{
if(stickers.get(i).title.matches(search))
return i;
}
return -1;
}
public void addSticker()
{
StickerBuilder sb = new StickerBuilder();
Sticker s = sb.getSticker();
s.y=(height/20)+(width*stickers.size())+5;
stickers.add(s);
repaint();
}
public void addSticker(Sticker s)
{
for(int i=0; i<stickers.size(); ++i)
{
stickers.get(i).y=s.y=(height/20)+(width*(i+1))+5*(i+1);
}
s.y=(height/20);
stickers.add(s);
}
}
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Sticker extends JPanel {
public String text;
private String Progress;
public String title;
private BufferedImage img;
public int x;
public int y;
public int width;
public int height;
public Sticker ( String text, String Progress,String title, int x, int y)
{
this.text=text;
this.Progress=Progress;
this.title = title;
this.x=x;
this.y=y;
this.width = -1;
this.height = -1;
try {
URL resource = Sticker.class.getResource("\\transparentSticker.png");
img = null;
this.img = ImageIO.read(Paths.get(resource.toURI()).toFile());
System.out.println("c");
} catch (IOException | URISyntaxException e) {
System.out.println("caught");
}
}
public void setText(String text) {
this.text = text;
}
public void setProgress(String progress) {
Progress = progress;
}
public void setTitle(String title) {
this.title = title;
}
public void setWidth(int width){
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public Sticker clone()
{
Sticker s= new Sticker(text, Progress, title, x, y);
s.setHeight(width);
s.setWidth(width);
return s;
}
#Override
public void paint(Graphics g) {
super.paint(g);
System.out.print("p");
g.drawImage(img, x, y, width-4, height, null);
String NormStr;
if(title!=null) {
NormStr = NormalizeLabel(title, g);
g.drawString(NormStr, x, y + width / 5);
}
if(text!=null) {
NormStr = NormalizeLabel(text, g);
FontMetrics fm = g.getFontMetrics(g.getFont());
int hgt = fm.getHeight();
String [] n=NormStr.split("\n");
for(int i= 0; i<n.length; ++i) {
g.drawString(n[i], x, y + width / 5 + hgt * 13 / 10 * (i + 1));
if(width / 5 + hgt * 13 / 10 * (i + 1)>=width*0.75)
{
g.drawString("...", x, y + width / 5 + hgt * 13 / 10 * (i + 1));
break;
}
}
}
}
private String NormalizeLabel(String s, Graphics g)
{
String NormalizedString = "";
String buf="";
FontMetrics fm = g.getFontMetrics(g.getFont());
int hgt= fm.getHeight();
int strw=0;
for(int i=0; i<s.length(); ++i)
{
buf+=s.charAt(i);
strw=fm.stringWidth(buf);
if(strw>=width*0.75)
{
NormalizedString+=buf;
NormalizedString+="\n";
buf="";
}
}
NormalizedString+=buf;
return NormalizedString;
}
}
import java.util.ArrayList;
public interface Builder {
void setText(String text);
void setProgress(String Progress);
void setTitle(String title);
Sticker getSticker();
}
import java.util.ArrayList;
public class StickerBuilder implements Builder{
public StickerBuilder() {
}
private String text;
private String Progress;
private String title;
public void setText(String text) {
this.text = text;
}
public void setProgress(String progress) {
Progress = progress;
}
public void setTitle(String title) {
this.title = title;
}
public Sticker getSticker()
{
return new Sticker(text, Progress, title, 0, 0);//возможно, стоит добавить функцию для х и у
}
}
import java.util.ArrayList;
import javax.swing.*;
import java.awt.*;
public class StickerChanger implements Builder {
private Sticker sticker;
public StickerChanger(Sticker sticker) {
this.sticker = sticker;
}
#Override
public void setText(String text) {
this.sticker.setText(text);
}
#Override
public void setProgress(String Progress) {
this.sticker.setProgress(Progress);
}
#Override
public void setTitle(String title) {
this.sticker.setTitle(title);
}
#Override
public Sticker getSticker() {
return null;
}
}
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
public class StickerListener implements MouseMotionListener, MouseListener {
private ArrayList<ProgressType> PTs;
private boolean StickerIsBeingDragged;
private int DistanceToTheEndX;
private int DistanceToTheEndY;
private Sticker CurrentSticker;
private Desk d;
private Window window;
private boolean sd2;
private final int Y_DELTA=50;
private ActionListener del;
private ActionListener edit;
private ActionListener rd;
private StickerEditorWindow sew;
public StickerListener(Desk d, Window w)
{
this.d = d;
this.PTs=d.ProgressTypes;
this.DistanceToTheEndX=this.DistanceToTheEndY=0;
this.StickerIsBeingDragged = this.sd2=false;
this.window =w;
}
#Override
public void mouseDragged(MouseEvent e) {
if (StickerIsBeingDragged)
{
sd2=true;
CurrentSticker.x=e.getX()-DistanceToTheEndX;
CurrentSticker.y=e.getY()-DistanceToTheEndY;
System.out.println(CurrentSticker.x+" "+CurrentSticker.y+" "+e.getX()+" "+ e.getY()+" "+"dragged");
d.repaint();
}
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
boolean f = true;
if(e.getButton() == MouseEvent.BUTTON1)
for (ProgressType pt : PTs) {
for (Sticker s : pt.stickers) {
System.out.println((e.getX() >= s.x) + " " + (e.getX() <= (s.x + s.width))+ " " +
(e.getY()-Y_DELTA >= s.y ) + " " + (e.getY()-Y_DELTA <= (s.y + s.width)));
System.out.println(e.getX() + " "+ e.getY()+ " " + s.x+ " "+ s.y);
if (e.getX() >= s.x && e.getX() <= (s.x + s.width) &&
e.getY()-Y_DELTA >= s.y && e.getY()-Y_DELTA <= (s.y + s.width)) {
CurrentSticker = s;
f=false;
JToolBar jtb = window.getStickerToolbar();
jtb.setVisible(true);
System.out.println("условие работает");
window.stickerToolBarActivated = true;
setListeners(s, pt, jtb);
f = false;
//Sticker buf = (Sticker) CurrentSticker.clone();
//pt.addSticker(buf);
d.repaint();
} else {
window.getStickerToolbar().setVisible(false);
sew = null;
window.stickerToolBarActivated = false;
if(rd!=null)
{
window.Read.removeActionListener(rd);
rd = null;
}
if(del!=null)
{
window.Delete.removeActionListener(del);
del = null;
}
if(edit!=null)
{
window.Edit.removeActionListener(edit);
edit = null;
}
}
}
}
System.out.println(e.getX()+" "+ e.getY()+" "+"cliicked");
}
private void setListeners(Sticker s, ProgressType pt, JToolBar jtb) {
del = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int iRes = JOptionPane.showConfirmDialog(window, "Удалить этот стикер?", "",
JOptionPane.YES_NO_OPTION);
if (iRes == JOptionPane.YES_NO_OPTION) {
pt.stickers.remove(s);
jtb.setVisible(false);
d.repaint();
}
}
};
edit = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (sew == null) {
createStickerEditorWindow(s);
}
}
};
rd = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
StickerReadingWindow srw = new StickerReadingWindow(s);
}
};
window.Delete.addActionListener(del);
window.Edit.addActionListener(edit);
window.Read.addActionListener(rd);
}
#Override
public void mousePressed(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1)
for(ProgressType pt: PTs) {
for (Sticker s : pt.stickers) {
if (e.getX() >= s.x && e.getX() <= (s.x + s.width) &&
e.getY()-Y_DELTA >= s.y && e.getY()-Y_DELTA <= (s.y + s.width)) {
DistanceToTheEndX = e.getX()-s.x;
DistanceToTheEndY = e.getY()-s.y;
StickerIsBeingDragged = true;
CurrentSticker = s;
System.out.println(s.x+" "+s.y+" "+e.getX()+" "+ e.getY()+" "+"pressed");
}
}
}
}
private void createStickerEditorWindow(Sticker s)
{
DefaultListModel listModel = new DefaultListModel();
for (ProgressType pt: PTs)
listModel.addElement(pt.name);
sew = new StickerEditorWindow(s, listModel);
sew.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
sew=null;
d.repaint();
}
});
}
#Override
public void mouseReleased(MouseEvent e) {
if(StickerIsBeingDragged) {
if(sd2) {
System.out.println(CurrentSticker.x + " " + CurrentSticker.y + " " + e.getX() + " " + e.getY() + " " + "released");
StickerIsBeingDragged = false;
d.repaint();
if (CurrentSticker.x < 0)
CurrentSticker.x = 0;
else if (CurrentSticker.x > window.getWidth())
CurrentSticker.x = window.getWidth() - 15;
for (ProgressType pt : PTs) {
if (CurrentSticker.x >= pt.x && CurrentSticker.x < pt.x + pt.width && CurrentSticker.x >= 0) {
CurrentSticker.x = pt.x;
Sticker buf = (Sticker) CurrentSticker.clone();
pt.addSticker(buf);
}
if (pt.stickers.indexOf(CurrentSticker) != -1) {
pt.stickers.remove(CurrentSticker);
}
}
sd2=false;
d.repaint();
}
}
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
public class StickerEditorWindow extends JFrame {
private Sticker sticker;
private JTextField title;
private JTextArea text;
private JList ProgressTypes;
private JButton Save;
private JButton DelayTitleChanges;
private JButton DelayTextChanges;
private JButton DelayProgressTypeChanges;
private DefaultListModel listModel;
public StickerEditorWindow(Sticker s, DefaultListModel lm) {
this.sticker = s;
setSize(600,300);
setTitle("Редактировать стикер");
setAlwaysOnTop(true);
// setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(
0, 0,
1, 1,
4, 0,
GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
new Insets(5, 5, 5, 5),
0, 0
);
title = new JTextField("Тема");
text = new JTextArea("Введите текст");
this.listModel = lm;
ProgressTypes = new JList(listModel);
this.add(title, gbc);
++gbc.gridy;
gbc.weighty=4;
this.add(text, gbc);
this.add(new JScrollPane(text), gbc);
gbc.weighty=0;
++gbc.gridy;
this.add(ProgressTypes, gbc);
ProgressTypes.setFocusable(false);
this.add(new JScrollPane(ProgressTypes), gbc);
ProgressTypes.setVisible(true);
Save = new JButton("Cохранить");
DelayTitleChanges = new JButton("Отменить изм. темы");
DelayTextChanges = new JButton("Отменить изм. текста");
DelayProgressTypeChanges = new JButton("Отменить изм. колонки прогресса");
gbc.gridx=1;
gbc.weightx=1;
gbc.gridy = 3;
this.add(Save, gbc);
gbc.gridy = 0;
this.add(DelayTitleChanges, gbc);
gbc.gridy = 1;
gbc.weighty=4;
this.add(DelayTextChanges, gbc);
gbc.gridy = 2;
this.add(DelayProgressTypeChanges, gbc);
if(sticker.text!=null) {
text.setText(sticker.text);
}
if(sticker.title!=null)
title.setText(sticker.title);
setListeners();
setVisible(true);
}
private void setListeners()
{
StickerEditorWindow w = this;
this.Save.addActionListener(new StickerChangeListener(w, this.Save));
this.DelayProgressTypeChanges.addActionListener(new StickerChangeListener(w, this.DelayProgressTypeChanges));
this.DelayTitleChanges.addActionListener(new StickerChangeListener(w, this.DelayTitleChanges));
this.DelayTextChanges.addActionListener(new StickerChangeListener(w, this.DelayTextChanges));
}
public void SaveStickerChanges()
{
sticker.title=title.getText();
sticker.text = text.getText();
}
public void CancelTitleChanges()
{
title.setText(sticker.title);
}
public void CancelTextChanges()
{
text.setText(sticker.text);
}
}
import javax.swing.*;
import javax.swing.plaf.basic.BasicOptionPaneUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StickerChangeListener implements ActionListener {
private StickerEditorWindow sew;
private JButton sender;
public StickerChangeListener(StickerEditorWindow sew, JButton sender) {
this.sew = sew;
this.sender = sender;
}
#Override
public void actionPerformed(ActionEvent e) {
if(sender.getText().equals("Cохранить")){
sew.SaveStickerChanges();
}
if(sender.getText().equals("Отменить изм. темы")){
sew.CancelTitleChanges();
}
if(sender.getText().equals("Отменить изм. текста")){
sew.CancelTextChanges();
}
if(sender.getText().equals("Отменить изм. колонки прогресса")){}
}
}
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
public class StickerReadingWindow extends JFrame{
private Sticker sticker;
private int width;
private int height;
ReadingCrutch rc;
public StickerReadingWindow(Sticker s) throws HeadlessException {
this.sticker = s;
width=height=500;
String winHeader = "";
if(sticker.title!=null)
winHeader+="Тема: "+sticker.title+ " ";
setTitle(winHeader);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel jp = new JPanel();
add(jp);
Graphics g =jp.getGraphics();
setSize(width,height);
setTitle("Редактировать стикер");
setAlwaysOnTop(true);
BufferedImage img = null;
try {
URL resource = Sticker.class.getResource("\\transparentSticker.png");
img = ImageIO.read(Paths.get(resource.toURI()).toFile());
System.out.println("c");
} catch (IOException | URISyntaxException e) {
System.out.println("caught");
}
if(img!=null)
rc = new ReadingCrutch(img, sticker.text, width);
add(rc);
setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class ReadingCrutch extends JPanel {
private BufferedImage img;
private String str;
private int width;
public ReadingCrutch(BufferedImage img, String str, int w) {
this.img = img;
this.str = str;
this.width =w;
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(img, 0, 0, 450, 450, null);
g.setColor(Color.black);
String txt = str;
String [] s=txt.split(" ");
String buf= "";
String NormalizedString="";
FontMetrics fm = g.getFontMetrics(g.getFont());
int hgt= fm.getHeight();
int strw=0;
for(int i=0; i<s.length; ++i)
{
buf+=s[i]+" ";
strw=fm.stringWidth(buf);
if(strw>=width*0.75)
{
NormalizedString+=buf;
NormalizedString+="\n";
buf="";
}
}
NormalizedString+=buf;
g.setColor(Color.black);
String[] forWrite= NormalizedString.split("\n");
for(int i=0; i<forWrite.length; ++i)
{
g.drawString(forWrite[i]+" ", 0, 0 + width / 5 + hgt * 13 / 10 * (i + 1));
}
}
}
The problem is in the control flow of the StickerListener.mouseClicked(): you search the stickers to find the one that has been clicked.
Due to the if / else you reset the toolbar for every sticker that has not been clicked, meaning that your code only works if you clicked on the last sticker (in order of iteration).
Your code will work if you move the code from the else part before the loop (so that it executes only once):
#Override
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
window.getStickerToolbar().setVisible(false);
sew = null;
window.stickerToolBarActivated = false;
if (rd != null) {
window.Read.removeActionListener(rd);
rd = null;
}
if (del != null) {
window.Delete.removeActionListener(del);
del = null;
}
if (edit != null) {
window.Edit.removeActionListener(edit);
edit = null;
}
for (ProgressType pt : PTs) {
for (Sticker s : pt.stickers) {
System.out.println((e.getX() >= s.x) + " " + (e.getX() <= (s.x + s.width)) + " " +
(e.getY() - Y_DELTA >= s.y) + " " + (e.getY() - Y_DELTA <= (s.y + s.width)));
System.out.println(e.getX() + " " + e.getY() + " " + s.x + " " + s.y);
if (e.getX() >= s.x && e.getX() <= (s.x + s.width) &&
e.getY() - Y_DELTA >= s.y && e.getY() - Y_DELTA <= (s.y + s.width)) {
CurrentSticker = s;
JToolBar jtb = window.getStickerToolbar();
jtb.setVisible(true);
System.out.println("условие работает");
window.stickerToolBarActivated = true;
setListeners(s, pt, jtb);
//Sticker buf = (Sticker) CurrentSticker.clone();
//pt.addSticker(buf);
d.repaint();
return;
}
}
}
}
System.out.println(e.getX()+" "+ e.getY()+" "+"cliicked");
}

Exception in thread “main” java.awt.IllegalComponentStateException

package javax.swing;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.security.AccessController;
import javax.accessibility.*;
import javax.swing.plaf.RootPaneUI;
import java.util.Vector;
import java.io.Serializable;
import javax.swing.border.*;
import sun.awt.AWTAccessor;
import sun.security.action.GetBooleanAction;
#SuppressWarnings("serial")
public class JRootPane extends JComponent implements Accessible {
private static final String uiClassID = "RootPaneUI";
public static final int COLOR_CHOOSER_DIALOG = 5;
public static final int FILE_CHOOSER_DIALOG = 6;
public static final int QUESTION_DIALOG = 7;
public static final int WARNING_DIALOG = 8;
private int windowDecorationStyle;
protected JMenuBar menuBar;
/** The content pane. */
protected Container contentPane;
/** The layered pane that manages the menu bar and content pane. */
protected JLayeredPane layeredPane;
protected Component glassPane;
protected JButton defaultButton;
boolean useTrueDoubleBuffering = true;
static {
LOG_DISABLE_TRUE_DOUBLE_BUFFERING =
AccessController.doPrivileged(new GetBooleanAction(
"swing.logDoubleBufferingDisable"));
IGNORE_DISABLE_TRUE_DOUBLE_BUFFERING =
AccessController.doPrivileged(new GetBooleanAction(
"swing.ignoreDoubleBufferingDisable"));
}
public JRootPane() {
setGlassPane(createGlassPane());
setLayeredPane(createLayeredPane());
setContentPane(createContentPane());
setLayout(createRootLayout());
setDoubleBuffered(true);
updateUI();
}
public void setDoubleBuffered(boolean aFlag) {
if (isDoubleBuffered() != aFlag) {
super.setDoubleBuffered(aFlag);
RepaintManager.currentManager(this).doubleBufferingChanged(this);
}
}
public int getWindowDecorationStyle() {
return windowDecorationStyle;
}
public void setWindowDecorationStyle(int windowDecorationStyle) {
if (windowDecorationStyle < 0 ||
windowDecorationStyle > WARNING_DIALOG) {
throw new IllegalArgumentException("Invalid decoration style");
}
int oldWindowDecorationStyle = getWindowDecorationStyle();
this.windowDecorationStyle = windowDecorationStyle;
firePropertyChange("windowDecorationStyle",
oldWindowDecorationStyle,
windowDecorationStyle);
}
public RootPaneUI getUI() {
return (RootPaneUI)ui;
}
public void setUI(RootPaneUI ui) {
super.setUI(ui);
}
public void updateUI() {
setUI((RootPaneUI)UIManager.getUI(this));
}
public String getUIClassID() {
return uiClassID;
}
protected JLayeredPane createLayeredPane() {
JLayeredPane p = new JLayeredPane();
p.setName(this.getName()+".layeredPane");
return p;
}
protected Container createContentPane() {
JComponent c = new JPanel();
c.setName(this.getName()+".contentPane");
c.setLayout(new BorderLayout() {
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints == null) {
constraints = BorderLayout.CENTER;
}
super.addLayoutComponent(comp, constraints);
}
});
return c;
}
protected Component createGlassPane() {
JComponent c = new JPanel();
c.setName(this.getName()+".glassPane");
c.setVisible(false);
((JPanel)c).setOpaque(false);
return c;
}
protected LayoutManager createRootLayout() {
return new RootLayout();
}
public void setJMenuBar(JMenuBar menu) {
if(menuBar != null && menuBar.getParent() == layeredPane)
layeredPane.remove(menuBar);
menuBar = menu;
if(menuBar != null)
layeredPane.add(menuBar, JLayeredPane.FRAME_CONTENT_LAYER);
}
#Deprecated
public void setMenuBar(JMenuBar menu){
if(menuBar != null && menuBar.getParent() == layeredPane)
layeredPane.remove(menuBar);
menuBar = menu;
if(menuBar != null)
layeredPane.add(menuBar, JLayeredPane.FRAME_CONTENT_LAYER);
}
public JMenuBar getJMenuBar() { return menuBar; }
#Deprecated
public JMenuBar getMenuBar() { return menuBar; }
public void setContentPane(Container content) {
if(content == null)
throw new IllegalComponentStateException("contentPane cannot be set to null.");
if(contentPane != null && contentPane.getParent() == layeredPane)
layeredPane.remove(contentPane);
contentPane = content;
layeredPane.add(contentPane, JLayeredPane.FRAME_CONTENT_LAYER);
}
public Container getContentPane() { return contentPane; }
public void setLayeredPane(JLayeredPane layered) {
if(layered == null)
throw new IllegalComponentStateException("layeredPane cannot be set to null.");
if(layeredPane != null && layeredPane.getParent() == this)
this.remove(layeredPane);
layeredPane = layered;
this.add(layeredPane, -1);
}
public JLayeredPane getLayeredPane() { return layeredPane; }
public void setGlassPane(Component glass) {
if (glass == null) {
throw new NullPointerException("glassPane cannot be set to null.");
}
AWTAccessor.getComponentAccessor().setMixingCutoutShape(glass,
new Rectangle());
boolean visible = false;
if (glassPane != null && glassPane.getParent() == this) {
this.remove(glassPane);
visible = glassPane.isVisible();
}
glass.setVisible(visible);
glassPane = glass;
this.add(glassPane, 0);
if (visible) {
repaint();
}
}
public Component getGlassPane() {
return glassPane;
}
#Override
public boolean isValidateRoot() {
return true;
}
public boolean isOptimizedDrawingEnabled() {
return !glassPane.isVisible();
}
public void addNotify() {
super.addNotify();
enableEvents(AWTEvent.KEY_EVENT_MASK);
}
public void removeNotify() {
super.removeNotify();
}
public void setDefaultButton(JButton defaultButton) {
JButton oldDefault = this.defaultButton;
if (oldDefault != defaultButton) {
this.defaultButton = defaultButton;
if (oldDefault != null) {
oldDefault.repaint();
}
if (defaultButton != null) {
defaultButton.repaint();
}
}
firePropertyChange("defaultButton", oldDefault, defaultButton);
}
public JButton getDefaultButton() {
return defaultButton;
}
final void setUseTrueDoubleBuffering(boolean useTrueDoubleBuffering) {
this.useTrueDoubleBuffering = useTrueDoubleBuffering;
}
final boolean getUseTrueDoubleBuffering() {
return useTrueDoubleBuffering;
}
final void disableTrueDoubleBuffering() {
if (useTrueDoubleBuffering) {
if (!IGNORE_DISABLE_TRUE_DOUBLE_BUFFERING) {
if (LOG_DISABLE_TRUE_DOUBLE_BUFFERING) {
System.out.println("Disabling true double buffering for " +
this);
Thread.dumpStack();
}
useTrueDoubleBuffering = false;
RepaintManager.currentManager(this).
doubleBufferingChanged(this);
}
}
}
#SuppressWarnings("serial")
static class DefaultAction extends AbstractAction {
JButton owner;
JRootPane root;
boolean press;
DefaultAction(JRootPane root, boolean press) {
this.root = root;
this.press = press;
}
public void setOwner(JButton owner) {
this.owner = owner;
}
public void actionPerformed(ActionEvent e) {
if (owner != null && SwingUtilities.getRootPane(owner) == root) {
ButtonModel model = owner.getModel();
if (press) {
model.setArmed(true);
model.setPressed(true);
} else {
model.setPressed(false);
}
}
}
public boolean isEnabled() {
return owner.getModel().isEnabled();
}
}
protected void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
if(glassPane != null
&& glassPane.getParent() == this
&& getComponent(0) != glassPane) {
add(glassPane, 0);
}
}
#SuppressWarnings("serial")
protected class RootLayout implements LayoutManager2, Serializable
{
public Dimension preferredLayoutSize(Container parent) {
Dimension rd, mbd;
Insets i = getInsets();
if(contentPane != null) {
rd = contentPane.getPreferredSize();
} else {
rd = parent.getSize();
}
if(menuBar != null && menuBar.isVisible()) {
mbd = menuBar.getPreferredSize();
} else {
mbd = new Dimension(0, 0);
}
return new Dimension(Math.max(rd.width, mbd.width) + i.left + i.right,
rd.height + mbd.height + i.top + i.bottom);
}
public Dimension minimumLayoutSize(Container parent) {
Dimension rd, mbd;
Insets i = getInsets();
if(contentPane != null) {
rd = contentPane.getMinimumSize();
} else {
rd = parent.getSize();
}
if(menuBar != null && menuBar.isVisible()) {
mbd = menuBar.getMinimumSize();
} else {
mbd = new Dimension(0, 0);
}
return new Dimension(Math.max(rd.width, mbd.width) + i.left + i.right,
rd.height + mbd.height + i.top + i.bottom);
}
public Dimension maximumLayoutSize(Container target) {
Dimension rd, mbd;
Insets i = getInsets();
if(menuBar != null && menuBar.isVisible()) {
mbd = menuBar.getMaximumSize();
} else {
mbd = new Dimension(0, 0);
}
if(contentPane != null) {
rd = contentPane.getMaximumSize();
} else {
// This is silly, but should stop an overflow error
rd = new Dimension(Integer.MAX_VALUE,
Integer.MAX_VALUE - i.top - i.bottom - mbd.height - 1);
}
return new Dimension(Math.min(rd.width, mbd.width) + i.left + i.right,
rd.height + mbd.height + i.top + i.bottom);
}
public void layoutContainer(Container parent) {
Rectangle b = parent.getBounds();
Insets i = getInsets();
int contentY = 0;
int w = b.width - i.right - i.left;
int h = b.height - i.top - i.bottom;
if(layeredPane != null) {
layeredPane.setBounds(i.left, i.top, w, h);
}
if(glassPane != null) {
glassPane.setBounds(i.left, i.top, w, h);
}
// Note: This is laying out the children in the layeredPane,
// technically, these are not our children.
if(menuBar != null && menuBar.isVisible()) {
Dimension mbd = menuBar.getPreferredSize();
menuBar.setBounds(0, 0, w, mbd.height);
contentY += mbd.height;
}
if(contentPane != null) {
contentPane.setBounds(0, contentY, w, h - contentY);
}
}
public void addLayoutComponent(String name, Component comp) {}
public void removeLayoutComponent(Component comp) {}
public void addLayoutComponent(Component comp, Object constraints) {}
public float getLayoutAlignmentX(Container target) { return 0.0f; }
public float getLayoutAlignmentY(Container target) { return 0.0f; }
public void invalidateLayout(Container target) {}
}
protected String paramString() {
return super.paramString();
}
/////////////////
// Accessibility support
////////////////
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJRootPane();
}
return accessibleContext;
}
#SuppressWarnings("serial")
protected class AccessibleJRootPane extends AccessibleJComponent {
public AccessibleRole getAccessibleRole() {
return AccessibleRole.ROOT_PANE;
}
public int getAccessibleChildrenCount() {
return super.getAccessibleChildrenCount();
}
public Accessible getAccessibleChild(int i) {
return super.getAccessibleChild(i);
}
} // inner class AccessibleJRootPane
}
I'm newby in Java, i'm googled all descussions about my problem. They are doesn't help me. Hope for your help. Sorry for my English. :)
I'm newby in Java, i'm googled all descussions about my problem. They are doesn't help me. Hope for your help. Sorry for my English. :)
This exception was come in time building project, but intellij IDEA didn't mark any code strings.
All problem functions:
1 function (at javax.swing.JRootPane.setContentPane(JRootPane.java:621))
public void setContentPane(Container content) {
if(content == null)
throw new IllegalComponentStateException("contentPane cannot be set to null.");
if(contentPane != null && contentPane.getParent() == layeredPane)
layeredPane.remove(contentPane);
contentPane = content;
layeredPane.add(contentPane, JLayeredPane.FRAME_CONTENT_LAYER);
}
2 function (at javax.swing.JFrame.setContentPane(JFrame.java:698))
public void setContentPane(Container contentPane) {
getRootPane().setContentPane(contentPane);
}
3 function (at com.company.AuthorizationGUI.(AuthorizationGUI.java:21))
AuthorizationGUI() {
setContentPane(contentPane);
Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
int width = 300, height = 200;
int X = (s.width - width) / 2;
int Y = (s.height - height) / 2;
setBounds(X, Y, width, height);
errorInput.setVisible(false);
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enter();
}
});
registration.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
registration();
}
});
4 function (at com.company.Client.connect(Client.java:42))
private void connect() {
try {
clientSocket = new Socket("127.0.0.1", 1000);
coos = new ObjectOutputStream(clientSocket.getOutputStream());
cois = new ObjectInputStream(clientSocket.getInputStream());
new AuthorizationGUI();
} catch (IOException e) {
e.printStackTrace();
}
}
5 function (at com.company.Client.(Client.java:21))
private Client() {
connect();
}
6 function (at com.company.Client.getInstance(Client.java:30))
public static Client getInstance() {
Client localInstance = instance;
if (localInstance == null) {
synchronized (Client.class) {
localInstance = instance;
if (localInstance == null) {
instance = localInstance = new Client();
}
}
}
return localInstance;
}
7 function (at com.company.Client.main(Client.java:17))
public static void main(String[] arg) {
Client.getInstance();
}
One good solution for you. Don't use the Swing library in Java, it's too old technology. The better way is definitely JavaFX.
Some tutorials here

How to change description image in JList java

Below is my code that displays images in a JList. I want to edit the description by each of the images shown in the JList. I don't know how to do it & need help. Thanks...
import java.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.Serializable;
public class DesignPicture2 {
private static String imageName;
static ArrayList<String> imgName = new ArrayList<String>();
public static void main(String[] args) throws Exception {
DesignPicture2 mm = new DesignPicture2();
mm.getImageName("C:\\Images 2 display");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame = new JFrame("Image panel");
frame.setSize(800, 500);
//frame.setLocationByPlatform(true);
frame.setLocation(600, 300);
JList imageList = createImageList();
frame.getContentPane().add(new JScrollPane(imageList));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static JList createImageList() {
JList imageList = new JList(createModel("C:\\Images 2 display"));
imageList.setCellRenderer(new ImageCellRenderer());
imageList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
imageList.setVisibleRowCount(0);
imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
imageList.setFixedCellWidth(240);
imageList.setFixedCellHeight(120);
// imageList.setDragEnabled(false);
//imageList.setDropMode(DropMode.INSERT);
imageList.setTransferHandler(new ImageTransferHandler(imageList));
return imageList;
}
private static DefaultListModel createModel(String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
DefaultListModel model = new DefaultListModel();
int count = 0;
for (int i = 0; i < listOfFiles.length - 1; i++) {
System.out.println("check path: " + listOfFiles[i]);
imageName = imgName.get(i).toString();
String name = listOfFiles[i].toString();
//load only JPEGS
if (name.endsWith("jpg")) {
try {
ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
model.add(count, ii);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return model;
}
static class ImageTransferHandler extends TransferHandler {
private static final DataFlavor DATA_FLAVOUR = new DataFlavor(ColorIcon.class, "Images");
private final JList previewList;
private boolean inDrag;
ImageTransferHandler(JList previewList) {
this.previewList = previewList;
}
public int getSourceActions(JComponent c) {
return TransferHandler.MOVE;
}
protected Transferable createTransferable(JComponent c) {
inDrag = true;
return new Transferable() {
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DATA_FLAVOUR};
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(DATA_FLAVOUR);
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return previewList.getSelectedValue();
}
};
}
public boolean canImport(TransferSupport support) {
if (!inDrag || !support.isDataFlavorSupported(DATA_FLAVOUR)) {
return false;
}
JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
if (dl.getIndex() == -1) {
return false;
} else {
return true;
}
}
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
Transferable transferable = support.getTransferable();
try {
Object draggedImage = transferable.getTransferData(DATA_FLAVOUR);
JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
DefaultListModel model = (DefaultListModel) previewList.getModel();
int dropIndex = dl.getIndex();
if (model.indexOf(draggedImage) < dropIndex) {
dropIndex--;
}
model.removeElement(draggedImage);
model.add(dropIndex, draggedImage);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
protected void exportDone(JComponent source, Transferable data, int action) {
super.exportDone(source, data, action);
inDrag = false;
}
}
static class ImageCellRenderer extends JPanel implements ListCellRenderer {
int count = 0;
DefaultListCellRenderer defaultListCellRenderer = new DefaultListCellRenderer();
JLabel imageLabel = new JLabel();
JLabel descriptionLabel = new JLabel();
ImageCellRenderer() {
setLayout(new BorderLayout());
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
imageLabel.setBorder(emptyBorder);
descriptionLabel.setBorder(emptyBorder);
add(imageLabel, BorderLayout.AFTER_LINE_ENDS);
add(descriptionLabel, BorderLayout.SOUTH);
// imageLabel.setText(imgName.get(0).toString());
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
defaultListCellRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setBorder(defaultListCellRenderer.getBorder());
setBackground(defaultListCellRenderer.getBackground());
imageLabel.setIcon((Icon) value);
if (count > imgName.size() - 1) {
count = 0;
} else {
descriptionLabel.setText(imgName.get(count).toString());
}
return this;
}
}
public void getImageName(String path) {
int c = 0;
final File dir = new File(path);
// array of supported extensions (use a List if you prefer)
final String[] EXTENSIONS = new String[]{
"jpg", "gif", "png", "bmp" // and other formats you need
// filter to identify images based on their extensions
};
final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles(IMAGE_FILTER)) {
BufferedImage img = null;
c++;
try {
img = ImageIO.read(f);
// you probably want something more involved here
// to display in your UI
System.out.println("image: " + f.getName());
imgName.add(f.getName().toString());
} catch (final IOException e) {
// handle errors here
System.out.println("Error!");
}
}
System.out.println("C: " + c);
} else {
System.out.println("Invalid Directory!");
}
}
static class ColorIcon implements Icon, Serializable {
private Color color;
ColorIcon(Color color) {
this.color = color;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.fillRect(x, y, getIconWidth(), getIconHeight());
}
public int getIconWidth() {
return 200;
}
public int getIconHeight() {
return 100;
}
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
return color.equals(((ColorIcon) o).color);
}
}
}
When I run the above code, it show the image in proper way, but the description of each image is fixed and I don't know how to change it. Hope anyone can help me.
I agree with trashgod (+1 to his suggestion), a JTable will be a simpler solution, here's why...
JList doesn't support editability, so you'd need to create it...
So, first, we'd need some kind of ListModel that provided some additional functionality, in particular, the ability to set the value at a particular index...
import javax.swing.ListModel;
public interface MutableListModel<E> extends ListModel<E> {
public void setElementAt(E value, int index);
public boolean isCellEditable(int index);
}
Next, we'd need some kind editor, in this case, following standard Swing API conventions, this asks for some kind of base interface
import java.awt.Component;
import javax.swing.CellEditor;
import javax.swing.JList;
public interface ListCellEditor<E> extends CellEditor {
public Component getListCellEditorComponent(
JList<E> list,
E value,
boolean isSelected,
int index);
public void applyEditorValue(E value);
}
Now, we need to create ourselves a custom JList capable of actually performing all the required functionality of editing a cell value...
Things like...
Recognising a "start editing" event
Determine if the cell can be edited
Managing the editing process, preparing and showing the editor, knowing when the editor has stopped or canceled and clean up appropriately...
Handling selection changes while editing is in progress
Handling component focus change (which I've not done cause that's an awesome amount of fun in itself...)
For example...
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JList;
import javax.swing.KeyStroke;
import javax.swing.ListModel;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class EditableList<E> extends JList<E> {
private ListCellEditor<E> editor;
private int editingCell = -1;
private Component editorComponent;
private CellEditorHandler handler;
public EditableList(MutableListModel<E> model) {
this();
setModel(model);
}
public EditableList() {
InputMap im = getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "editorCell");
ActionMap am = getActionMap();
am.put("editorCell", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Edit baby");
int cell = getSelectedIndex();
editCellAt(cell);
}
});
addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (isEditing()) {
if (!stopCellEditing()) {
cancelCellEditing();
}
}
}
});
}
public boolean isEditing() {
return editorComponent != null;
}
public void cancelCellEditing() {
getEditor().cancelCellEditing();
}
public boolean stopCellEditing() {
return getEditor().stopCellEditing();
}
public CellEditorHandler getCellEditorHandler() {
if (handler == null) {
handler = new CellEditorHandler();
}
return handler;
}
public void setEditor(ListCellEditor<E> value) {
if (value != editor) {
ListCellEditor old = editor;
editor = value;
firePropertyChange("editor", old, editor);
}
}
public ListCellEditor<E> getEditor() {
return editor;
}
public boolean isCellEditable(int cell) {
boolean isEditable = false;
ListModel model = getModel();
if (model instanceof MutableListModel) {
MutableListModel mcm = (MutableListModel) model;
isEditable = mcm.isCellEditable(cell);
}
return isEditable;
}
protected void editCellAt(int index) {
if (isCellEditable(index)) {
ListCellEditor<E> editor = getEditor();
if (editor != null) {
Rectangle cellBounds = getCellBounds(index, index);
E value = getModel().getElementAt(index);
boolean selected = isSelectedIndex(index);
editingCell = index;
editor.addCellEditorListener(getCellEditorHandler());
editorComponent = editor.getListCellEditorComponent(this, value, selected, index);
editorComponent.setBounds(cellBounds);
ensureIndexIsVisible(index);
add(editorComponent);
revalidate();
}
}
}
public int getEditingCell() {
return editingCell;
}
protected void editingHasStopped(ListCellEditor editor) {
editingCell = -1;
if (editorComponent != null) {
remove(editorComponent);
}
if (editor != null) {
editor.removeCellEditorListener(getCellEditorHandler());
}
}
public class CellEditorHandler implements CellEditorListener {
#Override
public void editingStopped(ChangeEvent e) {
E value = getModel().getElementAt(getEditingCell());
getEditor().applyEditorValue(value);
((MutableListModel) getModel()).setElementAt(value, getEditingCell());
editingHasStopped((ListCellEditor)e.getSource());
}
#Override
public void editingCanceled(ChangeEvent e) {
editingHasStopped((ListCellEditor)e.getSource());
}
}
}
Now, having done all that, you will need change the way you've structured your program, instead of using a List and ListModel to manage the descriptions and images separately, you should probably merge the concept into a single, manageable object, for example...
public class ImagePreview {
private String name;
private ImageIcon image;
public ImagePreview(String name, ImageIcon image) {
this.name = name;
this.image = image;
}
public String getDescription() {
return name;
}
public ImageIcon getImage() {
return image;
}
protected void setDescription(String description) {
this.name = description;
}
}
Even if you choose to use a JTable instead, you'll find this easier to manage...
Now we need some way to render and edit these values, to this end, I choose to start with a base component which could display the image and text...
public class ImagePreviewPane extends JPanel {
private JLabel imageLabel = new JLabel();
private JLabel descriptionLabel = new JLabel();
public ImagePreviewPane() {
setLayout(new BorderLayout());
Border emptyBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
imageLabel.setBorder(emptyBorder);
descriptionLabel.setBorder(emptyBorder);
add(imageLabel, BorderLayout.CENTER);
add(descriptionLabel, BorderLayout.SOUTH);
}
protected JLabel getDescriptionLabel() {
return descriptionLabel;
}
protected JLabel getImageLabel() {
return imageLabel;
}
public void setImage(ImageIcon icon) {
imageLabel.setIcon(icon);
}
public void setDescription(String text) {
descriptionLabel.setText(text);
}
}
Create an extended version that could handle editing...
public static class ImagePreviewEditorPane extends ImagePreviewPane {
private JTextField editor;
public ImagePreviewEditorPane() {
super();
editor = new JTextField();
remove(getDescriptionLabel());
add(editor, BorderLayout.SOUTH);
}
#Override
public void setDescription(String text) {
editor.setText(text);
}
public String getDescription() {
return editor.getText();
}
public void setImagePreview(ImagePreview preview) {
setImage(preview.getImage());
setDescription(preview.getDescription());
}
#Override
public void addNotify() {
super.addNotify();
editor.requestFocusInWindow();
}
}
This is done to try and make it easier to modify the components later...
Next, a ListCellRenderer
public class ImageCellRenderer extends ImagePreviewPane implements ListCellRenderer {
public ImageCellRenderer() {
}
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Color bg = null;
Color fg = null;
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index) {
bg = DefaultLookup.getColor(this, getUI(), "List.dropCellBackground");
fg = DefaultLookup.getColor(this, getUI(), "List.dropCellForeground");
isSelected = true;
}
if (isSelected) {
setBackground(bg == null ? list.getSelectionBackground() : bg);
setForeground(fg == null ? list.getSelectionForeground() : fg);
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
if (value instanceof ImagePreview) {
ImagePreview ip = (ImagePreview) value;
setImage(ip.getImage());
setDescription(ip.getDescription());
} else {
setImage(null);
setDescription("??");
}
setEnabled(list.isEnabled());
setFont(list.getFont());
return this;
}
}
And editor...
public class ImagePreviewListCellEditor extends AbstactListCellEditor<ImagePreview> {
private ImagePreviewEditorPane previewPane;
public ImagePreviewListCellEditor() {
previewPane = new ImagePreviewEditorPane();
InputMap im = previewPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "accept");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel");
ActionMap am = previewPane.getActionMap();
am.put("accept", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
stopCellEditing();
}
});
am.put("cancel", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
cancelCellEditing();
}
});
}
public void applyEditorValue(ImagePreview preview) {
preview.setDescription(previewPane.getDescription());
}
#Override
public Component getListCellEditorComponent(JList<ImagePreview> list, ImagePreview value, boolean isSelected, int index) {
Color bg = null;
Color fg = null;
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index) {
bg = DefaultLookup.getColor(previewPane, previewPane.getUI(), "List.dropCellBackground");
fg = DefaultLookup.getColor(previewPane, previewPane.getUI(), "List.dropCellForeground");
isSelected = true;
}
if (isSelected) {
previewPane.setBackground(bg == null ? list.getSelectionBackground() : bg);
previewPane.setForeground(fg == null ? list.getSelectionForeground() : fg);
} else {
previewPane.setBackground(list.getBackground());
previewPane.setForeground(list.getForeground());
}
if (value instanceof ImagePreview) {
ImagePreview preview = (ImagePreview)value;
previewPane.setImagePreview(preview);
} else {
previewPane.setImagePreview(null);
}
return previewPane;
}
}
And finally, putting it altogether...
public class DesignPicture2 {
public static void main(String[] args) throws Exception {
DesignPicture2 mm = new DesignPicture2();
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFrame frame = new JFrame("Image panel");
frame.setSize(800, 500);
frame.setLocation(600, 300);
JList imageList = createImageList();
frame.getContentPane().add(new JScrollPane(imageList));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static JList createImageList() {
EditableList<ImagePreview> imageList = new EditableList(createModel("..."));
imageList.setEditor(new ImagePreviewListCellEditor());
imageList.setCellRenderer(new ImageCellRenderer());
imageList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
imageList.setVisibleRowCount(0);
imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
imageList.setFixedCellWidth(240);
imageList.setFixedCellHeight(120);
return imageList;
}
private static MutableListModel<ImagePreview> createModel(String path) {
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
DefaultMutableListModel<ImagePreview> model = new DefaultMutableListModel<>();
int count = 0;
for (int i = 0; i < listOfFiles.length - 1; i++) {
System.out.println("check path: " + listOfFiles[i]);
String name = listOfFiles[i].toString();
if (name.endsWith("jpg")) {
try {
ImageIcon ii = new ImageIcon(ImageIO.read(listOfFiles[i]));
model.addElement(new ImagePreview(name, ii));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return model;
}
}
JList does not support the notion of a cell editor. Instead, use a two-column JTable. Some important points:
Your model's isCellEditable() implementation should return true for the description column in order to make it editable.
Your model's implementation of getColumnClass() can let the default renderer display your image by returning ImageIcon or Icon .

how would be implements autosugesion in JTextArea swing

let me if have you anyone answer, this ans. basically required like as google search engine , when we press any key then it would be display suggestion related pressed key.
regard
Satish Dhiman
From my comment/previous code see this update:
Using JTextField with AutoSuggestor:
Using JTextArea (or any other JTextComponent besides JTextField will result in Pop up window being shown under caret) with AutoSuggestor:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JWindow;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
/**
* #author David
*/
public class Test {
public Test() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JTextField f = new JTextField(10);
JTextArea f = new JTextArea(10, 10);
//JEditorPane f = new JEditorPane();
//create words for dictionary could also use null as parameter for AutoSuggestor(..,..,null,..,..,..,..) and than call AutoSuggestor#setDictionary after AutoSuggestr insatnce has been created
ArrayList<String> words = new ArrayList<>();
words.add("hello");
words.add("heritage");
words.add("happiness");
words.add("goodbye");
words.add("cruel");
words.add("car");
words.add("war");
words.add("will");
words.add("world");
words.add("wall");
AutoSuggestor autoSuggestor = new AutoSuggestor(f, frame, words, Color.WHITE.brighter(), Color.BLUE, Color.RED, 0.75f) {
#Override
boolean wordTyped(String typedWord) {
System.out.println(typedWord);
return super.wordTyped(typedWord);//checks for a match in dictionary and returns true or false if found or not
}
};
JPanel p = new JPanel();
p.add(f);
frame.add(p);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
}
class AutoSuggestor {
private final JTextComponent textComp;
private final Window container;
private JPanel suggestionsPanel;
private JWindow autoSuggestionPopUpWindow;
private String typedWord;
private final ArrayList<String> dictionary = new ArrayList<>();
private int currentIndexOfSpace, tW, tH;
private DocumentListener documentListener = new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
#Override
public void removeUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
#Override
public void changedUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
};
private final Color suggestionsTextColor;
private final Color suggestionFocusedColor;
public AutoSuggestor(JTextComponent textComp, Window mainWindow, ArrayList<String> words, Color popUpBackground, Color textColor, Color suggestionFocusedColor, float opacity) {
this.textComp = textComp;
this.suggestionsTextColor = textColor;
this.container = mainWindow;
this.suggestionFocusedColor = suggestionFocusedColor;
this.textComp.getDocument().addDocumentListener(documentListener);
setDictionary(words);
typedWord = "";
currentIndexOfSpace = 0;
tW = 0;
tH = 0;
autoSuggestionPopUpWindow = new JWindow(mainWindow);
autoSuggestionPopUpWindow.setOpacity(opacity);
suggestionsPanel = new JPanel();
suggestionsPanel.setLayout(new GridLayout(0, 1));
suggestionsPanel.setBackground(popUpBackground);
addKeyBindingToRequestFocusInPopUpWindow();
}
private void addKeyBindingToRequestFocusInPopUpWindow() {
textComp.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
textComp.getActionMap().put("Down released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {//focuses the first label on popwindow
for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
((SuggestionLabel) suggestionsPanel.getComponent(i)).setFocused(true);
autoSuggestionPopUpWindow.toFront();
autoSuggestionPopUpWindow.requestFocusInWindow();
suggestionsPanel.requestFocusInWindow();
suggestionsPanel.getComponent(i).requestFocusInWindow();
break;
}
}
}
});
suggestionsPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
suggestionsPanel.getActionMap().put("Down released", new AbstractAction() {
int lastFocusableIndex = 0;
#Override
public void actionPerformed(ActionEvent ae) {//allows scrolling of labels in pop window (I know very hacky for now :))
ArrayList<SuggestionLabel> sls = getAddedSuggestionLabels();
int max = sls.size();
if (max > 1) {//more than 1 suggestion
for (int i = 0; i < max; i++) {
SuggestionLabel sl = sls.get(i);
if (sl.isFocused()) {
if (lastFocusableIndex == max - 1) {
lastFocusableIndex = 0;
sl.setFocused(false);
autoSuggestionPopUpWindow.setVisible(false);
setFocusToTextField();
checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
} else {
sl.setFocused(false);
lastFocusableIndex = i;
}
} else if (lastFocusableIndex <= i) {
if (i < max) {
sl.setFocused(true);
autoSuggestionPopUpWindow.toFront();
autoSuggestionPopUpWindow.requestFocusInWindow();
suggestionsPanel.requestFocusInWindow();
suggestionsPanel.getComponent(i).requestFocusInWindow();
lastFocusableIndex = i;
break;
}
}
}
} else {//only a single suggestion was given
autoSuggestionPopUpWindow.setVisible(false);
setFocusToTextField();
checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
}
}
});
}
private void setFocusToTextField() {
container.toFront();
container.requestFocusInWindow();
textComp.requestFocusInWindow();
}
public ArrayList<SuggestionLabel> getAddedSuggestionLabels() {
ArrayList<SuggestionLabel> sls = new ArrayList<>();
for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
SuggestionLabel sl = (SuggestionLabel) suggestionsPanel.getComponent(i);
sls.add(sl);
}
}
return sls;
}
private void checkForAndShowSuggestions() {
typedWord = getCurrentlyTypedWord();
suggestionsPanel.removeAll();//remove previos words/jlabels that were added
//used to calcualte size of JWindow as new Jlabels are added
tW = 0;
tH = 0;
boolean added = wordTyped(typedWord);
if (!added) {
if (autoSuggestionPopUpWindow.isVisible()) {
autoSuggestionPopUpWindow.setVisible(false);
}
} else {
showPopUpWindow();
setFocusToTextField();
}
}
protected void addWordToSuggestions(String word) {
SuggestionLabel suggestionLabel = new SuggestionLabel(word, suggestionFocusedColor, suggestionsTextColor, this);
calculatePopUpWindowSize(suggestionLabel);
suggestionsPanel.add(suggestionLabel);
}
public String getCurrentlyTypedWord() {//get newest word after last white spaceif any or the first word if no white spaces
String text = textComp.getText();
String wordBeingTyped = "";
text = text.replaceAll("(\\r|\\n)", " ");
if (text.contains(" ")) {
int tmp = text.lastIndexOf(" ");
if (tmp >= currentIndexOfSpace) {
currentIndexOfSpace = tmp;
wordBeingTyped = text.substring(text.lastIndexOf(" "));
}
} else {
wordBeingTyped = text;
}
return wordBeingTyped.trim();
}
private void calculatePopUpWindowSize(JLabel label) {
//so we can size the JWindow correctly
if (tW < label.getPreferredSize().width) {
tW = label.getPreferredSize().width;
}
tH += label.getPreferredSize().height;
}
private void showPopUpWindow() {
autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.setSize(tW, tH);
autoSuggestionPopUpWindow.setVisible(true);
int windowX = 0;
int windowY = 0;
if (textComp instanceof JTextField) {//calculate x and y for JWindow at bottom of JTextField
windowX = container.getX() + textComp.getX() + 5;
if (suggestionsPanel.getHeight() > autoSuggestionPopUpWindow.getMinimumSize().height) {
windowY = container.getY() + textComp.getY() + textComp.getHeight() + autoSuggestionPopUpWindow.getMinimumSize().height;
} else {
windowY = container.getY() + textComp.getY() + textComp.getHeight() + autoSuggestionPopUpWindow.getHeight();
}
} else {//calculate x and y for JWindow on any JTextComponent using the carets position
Rectangle rect = null;
try {
rect = textComp.getUI().modelToView(textComp, textComp.getCaret().getDot());//get carets position
} catch (BadLocationException ex) {
ex.printStackTrace();
}
windowX = (int) (rect.getX() + 15);
windowY = (int) (rect.getY() + (rect.getHeight() * 3));
}
//show the pop up
autoSuggestionPopUpWindow.setLocation(windowX, windowY);
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.revalidate();
autoSuggestionPopUpWindow.repaint();
}
public void setDictionary(ArrayList<String> words) {
dictionary.clear();
if (words == null) {
return;//so we can call constructor with null value for dictionary without exception thrown
}
for (String word : words) {
dictionary.add(word);
}
}
public JWindow getAutoSuggestionPopUpWindow() {
return autoSuggestionPopUpWindow;
}
public Window getContainer() {
return container;
}
public JTextComponent getTextField() {
return textComp;
}
public void addToDictionary(String word) {
dictionary.add(word);
}
boolean wordTyped(String typedWord) {
if (typedWord.isEmpty()) {
return false;
}
//System.out.println("Typed word: " + typedWord);
boolean suggestionAdded = false;
for (String word : dictionary) {//get words in the dictionary which we added
boolean fullymatches = true;
for (int i = 0; i < typedWord.length(); i++) {//each string in the word
if (!typedWord.toLowerCase().startsWith(String.valueOf(word.toLowerCase().charAt(i)), i)) {//check for match
fullymatches = false;
break;
}
}
if (fullymatches) {
addWordToSuggestions(word);
suggestionAdded = true;
}
}
return suggestionAdded;
}
}
class SuggestionLabel extends JLabel {
private boolean focused = false;
private final JWindow autoSuggestionsPopUpWindow;
private final JTextComponent textComponent;
private final AutoSuggestor autoSuggestor;
private Color suggestionsTextColor, suggestionBorderColor;
public SuggestionLabel(String string, final Color borderColor, Color suggestionsTextColor, AutoSuggestor autoSuggestor) {
super(string);
this.suggestionsTextColor = suggestionsTextColor;
this.autoSuggestor = autoSuggestor;
this.textComponent = autoSuggestor.getTextField();
this.suggestionBorderColor = borderColor;
this.autoSuggestionsPopUpWindow = autoSuggestor.getAutoSuggestionPopUpWindow();
initComponent();
}
private void initComponent() {
setFocusable(true);
setForeground(suggestionsTextColor);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);
replaceWithSuggestedText();
autoSuggestionsPopUpWindow.setVisible(false);
}
});
getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "Enter released");
getActionMap().put("Enter released", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
replaceWithSuggestedText();
autoSuggestionsPopUpWindow.setVisible(false);
}
});
}
public void setFocused(boolean focused) {
if (focused) {
setBorder(new LineBorder(suggestionBorderColor));
} else {
setBorder(null);
}
repaint();
this.focused = focused;
}
public boolean isFocused() {
return focused;
}
private void replaceWithSuggestedText() {
String suggestedWord = getText();
String text = textComponent.getText();
String typedWord = autoSuggestor.getCurrentlyTypedWord();
String t = text.substring(0, text.lastIndexOf(typedWord));
String tmp = t + text.substring(text.lastIndexOf(typedWord)).replace(typedWord, suggestedWord);
textComponent.setText(tmp + " ");
}
}
As you can see I changed the code by making its constructor accept a JTextComponent rather than a JTextField or JTextArea etc.
The problem we are left with is we have to show the pop up JWindow at a different position depending on the JTextComponent passed i.e a JTextField will have autosuggest window pop up at the bottom while JTextArea/JEditorPane etc would have the JWindow pop up under the caret/word.
Have a look at this specific method showPopUpWindow() in AutoSuggestor class:
private void showPopUpWindow() {
autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.setSize(tW, tH);
autoSuggestionPopUpWindow.setVisible(true);
int windowX = 0;
int windowY = 0;
if (textComp instanceof JTextField) {//calculate x and y for JWindow at bottom of JTextField
windowX = container.getX() + textComp.getX() + 5;
if (suggestionsPanel.getHeight() > autoSuggestionPopUpWindow.getMinimumSize().height) {
windowY = container.getY() + textComp.getY() + textComp.getHeight() + autoSuggestionPopUpWindow.getMinimumSize().height;
} else {
windowY = container.getY() + textComp.getY() + textComp.getHeight() + autoSuggestionPopUpWindow.getHeight();
}
} else {//calculate x and y for JWindow on any JTextComponent using the carets position
Rectangle rect = null;
try {
rect = textComp.getUI().modelToView(textComp, textComp.getCaret().getDot());//get carets position
} catch (BadLocationException ex) {
ex.printStackTrace();
}
windowX = (int) (rect.getX() + 15);
windowY = (int) (rect.getY() + (rect.getHeight() * 3));
}
//show the pop up
autoSuggestionPopUpWindow.setLocation(windowX, windowY);
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.revalidate();
autoSuggestionPopUpWindow.repaint();
}
As you can see we check to see what instance the JTextComponent is and if its not a JTextField simply get the caret position (via the Rectangle of the caret) of the JTextComponent and position JWindow pop up from there (underneath the caret in my case).
I can propose my own implementation. It is based on JList shown in JWindow.
As I wanted to use this code for a combo box, I've disabled UP and DOWN keys with keyEvent.consume() call.
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GAutoCompletionDecorator {
private final JTextComponent textComponent;
private final JWindow suggestionsPopup;
private final JList completionList;
private final DefaultListModel completionListModel;
public static void decorate(JComboBox comboBox, JFrame parent) {
comboBox.setEditable(true);
final JTextComponent textComponent = (JTextComponent) comboBox.getEditor().getEditorComponent();
decorate(textComponent, parent);
}
private static void decorate(JTextComponent textComponent, JFrame parent) {
final GAutoCompletionDecorator autoCompletionDecorator = new GAutoCompletionDecorator(textComponent, parent);
autoCompletionDecorator.decorate();
}
private GAutoCompletionDecorator(final JTextComponent textComponent, JFrame parent) {
this.textComponent = textComponent;
this.suggestionsPopup = new JWindow(parent);
this.completionListModel = new DefaultListModel();
this.completionList = new JList();
this.completionList.setModel(completionListModel);
this.suggestionsPopup.getContentPane().add(this.completionList);
}
private void decorate() {
textComponent.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent documentEvent) {
updateSuggestions();
}
public void removeUpdate(DocumentEvent documentEvent) {
updateSuggestions();
}
public void changedUpdate(DocumentEvent documentEvent) {
updateSuggestions();
}
});
this.textComponent.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN || keyEvent.getKeyCode() == KeyEvent.VK_UP) {
updateSuggestions();
completionList.requestFocus();
completionList.dispatchEvent(keyEvent);
keyEvent.consume();
}
}
public void keyReleased(KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN || keyEvent.getKeyCode() == KeyEvent.VK_UP) {
keyEvent.consume();
}
}
});
this.completionList.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) {
textComponent.requestFocus();
hideSuggestionsPopup();
} else if (keyEvent.getKeyCode() == KeyEvent.VK_UP) {
if (completionList.getSelectedIndex() == 0) {
completionList.setSelectedIndex(completionListModel.size() - 1);
keyEvent.consume();
}
} else if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN) {
if (completionList.getSelectedIndex() == completionListModel.size() - 1) {
completionList.setSelectedIndex(0);
keyEvent.consume();
}
} else if (keyEvent.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
textComponent.requestFocus();
hideSuggestionsPopup();
textComponent.dispatchEvent(keyEvent);
} else if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
textComponent.requestFocus();
hideSuggestionsPopup();
final String selectedSuggestion = (String) completionList.getSelectedValue();
if (selectedSuggestion != null) {
try {
final int caretPosition = textComponent.getCaretPosition();
textComponent.getDocument().insertString(caretPosition, getCompletionString(selectedSuggestion, textComponent.getText(), caretPosition), null);
} catch (BadLocationException e) {
//ignore
}
}
}
}
});
}
private String getCompletionString(String selectedSuggestion, String text, int caretPosition) {
//we may insert selectedSuggestion fully of some part of it
return selectedSuggestion;
}
private void updateSuggestions() {
final String text = textComponent.getText();
final int caretPosition = textComponent.getCaretPosition();
final List<String> suggestions = getSuggestions(text, caretPosition);
if (suggestions == null || suggestions.size() == 0) {
//hide suggestions window
hideSuggestionsPopup();
} else {
//show suggestions window
showSuggestionsPopup(suggestions);
}
}
private void hideSuggestionsPopup() {
suggestionsPopup.setVisible(false);
}
private void showSuggestionsPopup(List<String> suggestions) {
completionListModel.clear();
for (String suggestion : suggestions) {
completionListModel.addElement(suggestion);
}
final Point textComponentLocation = new Point(textComponent.getLocation());
SwingUtilities.convertPointToScreen(textComponentLocation, textComponent);
Point caretLocation = textComponent.getCaret().getMagicCaretPosition();
if (caretLocation != null) {
caretLocation = new Point(caretLocation);
SwingUtilities.convertPointToScreen(caretLocation, textComponent);
}
suggestionsPopup.pack();
suggestionsPopup.setLocation(caretLocation == null ? textComponentLocation.x : caretLocation.x,
textComponentLocation.y + textComponent.getHeight());
suggestionsPopup.setVisible(true);
}
private List<String> getSuggestions(String text, int caretPosition) {
final List<String> words = new ArrayList<String>();
words.add("suggestion 1");
words.add("suggestion 2");
words.add("suggestion 3");
words.add("suggestion 4");
words.add("suggestion 5");
//make suggestions funny
return text.length() < words.size() ? words.subList(0, words.size() - text.length()) : Collections.<String>emptyList();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComboBox comboBox = new JComboBox(new String[] {"Choice1", "Choice2"});
comboBox.setEditable(true);
GAutoCompletionDecorator.decorate(comboBox, frame);
frame.add(comboBox);
frame.pack();
frame.setVisible(true);
}
});
}
}

Nimbus L & F: Setting different background colors of a Check-Boxes in a CheckBox List

I had a list of check-boxes and I want to set different colors on each check-box.
Following code does not change the background color
checkBox[i] = new JCheckBox();
checkBox[i].setEnabled(false);
checkBox[i].setBackground(Color.GREEN);
Kindly let me know way of setting background color
for example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.event.*;
public class JListDisabledItemDemo implements ItemListener, Runnable {
private JFrame f = new JFrame("Colors");
private static final String ITEMS[] = {" black ", " blue ", " green ",
" orange ", " purple ", " red ", " white ", " yellow "};
private JList jList;
private JCheckBox[] checkBoxes;
private boolean[] enabledFlags;
#Override
public void run() {
JPanel pnlEnablers = new JPanel(new GridLayout(0, 1));
pnlEnablers.setBorder(BorderFactory.createTitledBorder("Enabled Items"));
checkBoxes = new JCheckBox[ITEMS.length];
enabledFlags = new boolean[ITEMS.length];
for (int i = 0; i < ITEMS.length; i++) {
checkBoxes[i] = new JCheckBox(ITEMS[i]);
checkBoxes[i].setSelected(true);
checkBoxes[i].addItemListener(this);
enabledFlags[i] = true;
pnlEnablers.add(checkBoxes[i]);
}
jList = new JList(ITEMS);
jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jList.setSelectionModel(new DisabledItemSelectionModel());
jList.setCellRenderer(new DisabledItemListCellRenderer());
jList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println("selection");
}
}
});
JScrollPane scroll = new JScrollPane(jList);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
Container contentPane = f.getContentPane();
contentPane.setLayout(new GridLayout(1, 2));
contentPane.add(pnlEnablers);
contentPane.add(scroll);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocation(240, 280);
UIManager.put("List.background", Color.lightGray);
UIManager.put("List.selectionBackground", Color.orange);
UIManager.put("List.selectionForeground", Color.blue);
UIManager.put("Label.disabledForeground", Color.magenta);
SwingUtilities.updateComponentTreeUI(f);
f.pack();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
f.setVisible(true);
}
});
}
#Override
public void itemStateChanged(ItemEvent event) {
JCheckBox checkBox = (JCheckBox) event.getSource();
int index = -1;
for (int i = 0; i < ITEMS.length; i++) {
if (ITEMS[i].equals(checkBox.getText())) {
index = i;
break;
}
}
if (index != -1) {
enabledFlags[index] = checkBox.isSelected();
jList.repaint();
}
}
public static void main(String args[]) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
System.out.println(info.getName());
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
// handle exception
} catch (ClassNotFoundException e) {
// handle exception
} catch (InstantiationException e) {
// handle exception
} catch (IllegalAccessException e) {
// handle exception
}
SwingUtilities.invokeLater(new JListDisabledItemDemo());
}
private class DisabledItemListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component comp = super.getListCellRendererComponent(list, value, index, false, false);
JComponent jc = (JComponent) comp;
if (enabledFlags[index]) {
if (isSelected & cellHasFocus) {
comp.setForeground(Color.black);
comp.setBackground(Color.red);
} else {
comp.setBackground(Color.white);
comp.setForeground(Color.black);
}
if (!isSelected) {
if ((value.toString()).trim().equals("yellow")) {
comp.setForeground(Color.blue);
comp.setBackground(Color.yellow);
} else if ((value.toString()).trim().equals("black")) {
comp.setForeground(Color.red);
comp.setBackground(Color.black);
}else if ((value.toString()).trim().equals("orange")) {
comp.setForeground(Color.blue);
comp.setBackground(Color.orange);
}
}
return comp;
}
comp.setEnabled(false);
return comp;
}
}
private class DisabledItemSelectionModel extends DefaultListSelectionModel {
private static final long serialVersionUID = 1L;
#Override
public void setSelectionInterval(int index0, int index1) {
if (enabledFlags[index0]) {
super.setSelectionInterval(index0, index0);
} else {
/*The previously selected index is before this one,
* so walk forward to find the next selectable item.*/
if (getAnchorSelectionIndex() < index0) {
for (int i = index0; i < enabledFlags.length; i++) {
if (enabledFlags[i]) {
super.setSelectionInterval(i, i);
return;
}
}
} /*
* Otherwise, walk backward to find the next selectable item.
*/ else {
for (int i = index0; i >= 0; i--) {
if (enabledFlags[i]) {
super.setSelectionInterval(i, i);
return;
}
}
}
}
}
}
}
Try setting your CheckBox Opacity to true.
myCheckBox.setOpaque(true);

Categories