Set Text in Editor Component in Combobox - java

My goal is to create a filtered combobox.
I create an editable combobox. When the user enters text, the code searches matching items in the model. When the user leaves the combobox, the code selects the selected item from the list. Further, the text from the editor component gets the value of the selected item.
When the focus goes back to the combobox via shift + tab, the editor component gets the text of the selected element. After releasing the shift key, the keylistener runs. In this case, the editor component contains the text entered previously, e.g., the value set when the focus is lost.
How can I set the text of the editorComponent to make it persist?
Here's the code:
package de.ccw.reports.gui.incomingOrder.MyComboBox;
import java.awt.FlowLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.plaf.basic.BasicComboPopup;
import javax.swing.text.JTextComponent;
import de.ccw.commons.ui.comp.XComboBox;
public class FilterableComboBox<E> extends XComboBox<E> {
ComboBoxModel<E> originalModel;
DefaultComboBoxModel<E> filteredModel;
JTextComponent editorComp;
JList<E> list;
public FilterableComboBox(ComboBoxModel<E> aModel) {
super();
receivePopupList();
originalModel = aModel;
filteredModel = new DefaultComboBoxModel<>();
setModel(filteredModel);
editorComp = (JTextComponent) getEditor().getEditorComponent();
editorComp.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
System.out.println("focusLostStart=" + getSelectedItem() + "|" + editorComp.getText());
String text = editorComp.getText();
editorComp.setText("");
setSelectedItem(null);
if(list.getSelectedIndex() != -1 && text.isEmpty() == false){
setSelectedIndex(list.getSelectedIndex());
editorComp.setText(getSelectedItem().toString());
}
System.out.println("focusLostEnd=" + getSelectedItem() + "|" + editorComp.getText());
}
#Override
public void focusGained(FocusEvent e) {
System.out.println("focusGainedStart=" + getSelectedItem() + "|" + editorComp.getText());
E element = getSelectedItem();
String text = editorComp.getText();
performModelFilter(null);
showPopup();
setSelectedItem(element);
editorComp.setText(text);
editorComp.selectAll();
System.out.println("focusGainedEnd=" + getSelectedItem() + "|" + editorComp.getText());
}
});
editorComp.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
}
String filterBkp = "";
#Override
public void keyReleased(KeyEvent e) {
String filter = editorComp.getText();
System.out.println("keyReleased-" + filterBkp + filter);
if(filter.equals(filterBkp) == false)
refreshModel();
filterBkp = filter;
}
#Override
public void keyPressed(KeyEvent e) {
}
});
setEditable(true);
}
#SuppressWarnings("unchecked")
private void receivePopupList() {
BasicComboPopup popup = (BasicComboPopup) getAccessibleContext().getAccessibleChild(0);
list = popup.getList();
}
private void refreshModel() {
String filter = editorComp.getText();
performModelFilter(filter);
editorComp.setText(filter);
}
private void performModelFilter(String filter) {
System.out.println("performModelFilter-" + filter);
filteredModel.removeAllElements();
for(int i = 0; i < originalModel.getSize(); i++){
E element = originalModel.getElementAt(i);
String value = element.toString().toUpperCase();
if (filter == null || value.contains(filter.toUpperCase())) {
filteredModel.addElement(element);
}
}
}
public static void main(String args[]){
FilterableComboBox<String> combo = new FilterableComboBox<>(new DefaultComboBoxModel<>(new String[]{"abc", "def", "ghi", "jkl", "mnoabc", "pqrdef"}));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(new JTextField(20));
frame.add(combo);
frame.add(new JTextField(20));
frame.pack();
frame.setVisible(true);
}
}

Related

Take JTextField text and display it on JTextarea in real time

I made this program for discord. This program takes your text and puts it in this 'format' that allows discord to convert it to fancy letters. My problem is that while typing the text lags behind by 1 character. I am only a beginner and I don't know what to do to fix it.
Ps. I do not feel like using a button to convert the text!
My Code :
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
textArea.setText("");
separatedText = textField.getText().toLowerCase().toCharArray();
for(int i = 0; i < separatedText.length; i++) {
textArea.append(separate ? ":regional_indicator_" + separatedText[i] + ":\n" : ":regional_indicator_" + separatedText[i] + ":");
}
}
});
You can achieve this by adding a Document Listener to your JTextField. You don't give us what the "separate" boolean is, so i made the example in case this boolean is always true.
Small Preview:
Source Code:
package test;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class DocListenerTest extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DocListenerTest r = new DocListenerTest();
r.setVisible(true);
});
}
public DocListenerTest() {
super("test");
getContentPane().setLayout(new GridLayout(5, 2));
JTextField textField = new JTextField();
textField.setBorder(BorderFactory.createTitledBorder("TextField"));
getContentPane().add(textField);
JTextArea textArea = new JTextArea();
textArea.setBorder(BorderFactory.createTitledBorder("TextArea"));
JScrollPane sp = new JScrollPane(textArea);
getContentPane().add(sp);
setSize(400, 400);
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
addTextToArea();
}
private void addTextToArea() {
textArea.setText("");
char[] separatedText = textField.getText().toLowerCase().toCharArray();
boolean separate = true; //Don't know the value of this.
for (int i = 0; i < separatedText.length; i++) {
textArea.append(separate ? ":regional_indicator_" + separatedText[i] + ":\n"
: ":regional_indicator_" + separatedText[i] + ":");
}
}
#Override
public void insertUpdate(DocumentEvent e) {
addTextToArea();
}
#Override
public void changedUpdate(DocumentEvent e) {
addTextToArea();
}
});
}
}

How to override the JPopupMenu method show?

my goal is to highlight a jlist item after a rightclick then show a jpopupmenu..
I read advice that overriding the method show is the way..
in my case i declare my jpopupmenu at the beginning of my class
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem masterlist,settings;
then i have a method to set up my menuItems
public void setPopupMenu(int depth//ignore this var){
//popupMenu = new JPopupMenu();
popupMenu.removeAll();
masterlist = new JMenuItem("Masterlist");
settings = new JMenuItem("Settings");
//action for marsterlist
masterlist.addActionListener(new ActionListener(){
//stuff here
}
});
//action for settings
settings.addActionListener(new ActionListener(){
//stuff here
}
});
popupMenu.add(masterlist);
popupMenu.add(settings);
}
and my list is in a different method
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
list.setComponentPopupMenu(popupMenu);
I tried putting this on a mouseAdapter of my list but the popupmenu fires first and ignores highlighting...
if ( SwingUtilities.isRightMouseButton(mouseEvent) )//highlight the right clicked item
{
int row = list.locationToIndex(mouseEvent.getPoint());
list.setSelectedIndex(row);
String val = (String)list.getSelectedValue();
System.out.println(val);
}
i know that overriding is something like this
popupmenu = new JPopupMenu(){
#Override
public void show(){}
}
but i cant do that because i am manipulating the menuitems on a method...
or is there any other approach that anyone can suggest...
Rather then trying to modify the state of the JPopupMenu, why not simply modify the state of the menu item when you detect a right click...
So, basically, I make use of the Actions API to define a menu item for a JPopupMenu, which allows it to register a ListSelectionListener to the underlying JList...
public class ShowItemAction extends AbstractAction {
private JList list;
public ShowItemAction(JList list) {
this.list = new JList();
putValue(NAME, "Showing ...");
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int index = list.getSelectedIndex();
String value = list.getSelectedValue().toString();
putValue(NAME, "Showing " + value + " # " + index);
}
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
// The actual action to be performed when selected
}
}
All this does is, when the selection is changed, is change the text (NAME) of the action, which changes the text of the menu item, based on the currently selected row.
When I create the JList, I assign it a JPopupMenu via the setComponentPopupMenu method, which means I no longer need to care about it and it will be displayed appropriately based on the current look and feel requirements
JList list = new JList(model);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(new ShowItemAction(list));
list.setComponentPopupMenu(popupMenu);
I then add a MouseListener to the JList which I use to change the row selection when you right click on the JList...
list.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
JList list = (JList)e.getComponent();
if (SwingUtilities.isRightMouseButton(e)) {
int row = list.locationToIndex(e.getPoint());
list.setSelectedIndex(row);
}
}
});
This not entirely fool proof, as if you right click the JList while the popup is visible, the MouseListener doesn't appear to get notified :P
Runnable example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import static javax.swing.Action.NAME;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultListModel model = new DefaultListModel();
model.addElement("One");
model.addElement("Two");
model.addElement("Three");
model.addElement("Four");
JList list = new JList(model);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(new ShowItemAction(list));
list.setComponentPopupMenu(popupMenu);
list.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
int row = list.locationToIndex(e.getPoint());
list.setSelectedIndex(row);
}
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(list));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ShowItemAction extends AbstractAction {
private JList list;
public ShowItemAction(JList list) {
this.list = new JList();
putValue(NAME, "Showing ...");
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int index = list.getSelectedIndex();
String value = list.getSelectedValue().toString();
putValue(NAME, "Showing " + value + " # " + index);
}
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
}

set focus to JList and have cursor on textField swing java autocomplete

I started to develop my own auto complete swing component and I want to set focus to the list when user press up or down keys and in the same time let the cursor on the textfield to allow him to type text or number....
to set focus to JList when typing up or down I have used
list.requestFocus();
is there any way to have focus on JList and cursor on JTextField
please view the image in here
here my code :
package examples.autocomplete;
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import com.gestioncaisse.dao.ClientDAO;
import com.gestioncaisse.dao.DAO;
import com.gestioncaisse.dao.MyConnection;
import com.gestioncaisse.pojos.Client;
import com.gestioncaisse.utils.utils;
public class testcombo extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
final DAO<Client> clientDao;
List<Client> list_clients;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testcombo frame = new testcombo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
boolean first_time = true;
/**
* Create the frame.
*/
public testcombo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
clientDao = new ClientDAO(MyConnection.getInstance());
list_clients = clientDao.findAll();
textField = new JTextField();
textField.setBounds(5, 11, 113, 20);
textField.setColumns(10);
final JButton btnNewButton = new JButton("...");
btnNewButton.setBounds(116, 10, 45, 23);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 31, 156, 144);
final JList list = new JList(
utils.fromListToObjectTable2Clients(list_clients));
scrollPane.setViewportView(list);
list.setVisibleRowCount(5);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
contentPane.add(scrollPane);
contentPane.add(textField);
contentPane.add(btnNewButton);
textField.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
int a = list.getSelectedIndex();
if (arg0.getKeyCode() == KeyEvent.VK_UP) {
list.requestFocus();
} else if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
list.requestFocus();
} else if (!first_time) {
} else {
first_time = false;
}
}
#Override
public void keyPressed(KeyEvent arg0) {
}
});
}
}
//if (a > 0)
//list.setSelectedIndex(a - 1);
//int first_vis = list.getFirstVisibleIndex();
//list.setListData(utils.fromListToObjectTable2Clients(clientDao.findByString(textField.getText())));
//list.setSelectedIndex(0);
Leave the focus on the JTextField but add KeyBindings to the UP/DOWN key. In the actions just change selection in JList (public void setSelectedIndex(int index) method)
UPDATE
An aslternative way would be to have focus on JList and add KeyListener translating typed chars to the JTextField. To Show caret use
jTextFieldInstance.getCaret().setVisible(true);
jTextFieldInstance.getCaret().setSelectionVisible(true);
Here i used to retrieve matched data from database
keywordssearcher.setEditable(true);
final JTextComponent sfield = (JTextComponent) keywordssearcher.getEditor().getEditorComponent();
sfield.setVisible(true);
sfield.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
comboFilter(sfield.getText(), con);
}
});
}
#Override
public void keyPressed(KeyEvent e) {
if (!(sfield.getText().equals("")) || (sfield.getText() == null)) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
addKeyWord(sfield.getText().toString());
}
}
}
});
public void comboFilter(String enteredText, Connection ncon) {
log.info("ncon autosuggest--->" + ncon);
ArrayList<String> filterArray = new ArrayList<String>();
String str1 = "";
try {
Statement stmt = dc.ConnectDB().createStatement();
String str = "SELECT k_word FROM T_KeyWords WHERE k_word LIKE '" + enteredText + "%'";
ResultSet rs = stmt.executeQuery(str);
while (rs.next()) {
str1 = rs.getString("k_word");
filterArray.add(str1);
con.close();
}
} catch (Exception ex) {
log.error("Error in getting keywords from database" + ex.toString());
JOptionPane.showMessageDialog(null, "Error in getting keywords from database" + ex.toString());
}
if (filterArray.size() > 0) {
keywordssearcher.setModel(new DefaultComboBoxModel(filterArray.toArray()));
keywordssearcher.setSelectedItem(enteredText);
keywordssearcher.showPopup();
} else {
keywordssearcher.hidePopup();
}
}
Here my keywordssearcher(jcombobox) is editable and the entered value can be added directly into the database.
use this as a reference and modify the code

JTextPane highlighting issue

The last days I have been trying to implement a highlighting feature in a small text editor. For some reason I get a strange result:
The given example should highlight each "dolor" - the first occurences are correctly found and highlighted but the next ones aren't.
Here is the code I wrote so far:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.text.DefaultStyledDocument;
/**
* Highlighting created on 04.11.2013<br>
* <br>
* Specification:<br>
*/
public class Highlighting extends JFrame implements MouseListener {
private JScrollPane scrollPane;
private JTextPane textPane;
private DefaultHighlighter highlighter;
private DefaultHighlightPainter painter;
public static void main(String[] args) {
new Highlighting().setVisible(true);
}
/**
*
*/
public Highlighting() {
this.initialize();
this.build();
this.configure();
}
/**
*
*/
public void initialize() {
this.scrollPane = new JScrollPane();
this.textPane = new JTextPane();
this.highlighter = new DefaultHighlighter();
this.painter = new DefaultHighlightPainter(Color.RED);
}
/**
*
*/
public void build() {
this.add(this.scrollPane);
}
/**
*
*/
public void configure() {
this.scrollPane.setViewportView(this.textPane);
this.textPane.setHighlighter(this.highlighter);
this.textPane.addMouseListener(this);
this.textPane.setDocument(new DefaultStyledDocument());
this.setPreferredSize(new Dimension(400, 500));
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
*
*/
private void highlight() {
this.highlighter.removeAllHighlights();
String selectedText = this.textPane.getSelectedText();
String text = this.textPane.getText();
int wordlength = selectedText.length();
int index = 0;
while ((index = text.indexOf(selectedText, index)) != -1) {
try {
this.highlighter.addHighlight(index, index + wordlength, this.painter);
} catch (BadLocationException e) {
e.printStackTrace();
}
index += wordlength;
}
}
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
this.highlight();
}
}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}
Does this has something to do with the line separators (\r\n) ?
A JTextComponent's getText() and A JTextPane/JEditorPane's getText() has different implementation. JTextPane/JEditorPane uses EditorKit to write the document content(text) to a StringWriter and then return the text with formatting and inserting a line/paragraph break into the document. But the JTextCompoent returns document content directly by:
document.getText(0, document.getLength());
You will better understand if you try to compare the length : jTextPane1.getText().length() and jTextPane1().getDocument().getLength().
Reproducing the difference in length by inserting string with:
DefaultStyleDocument.insertString(0, str, primaryStyle)
when str = "I\n not" ; document length = 6, getText().length = 7
when str = "I\r\n not" ; document length = 7, getText().length = 8
when str = "I\n\n not" ; document length = 7, getText().length = 9!
So, in your high-lighting text program try reading the content text using:
DefaultStyledDocument document = (DefaultStyledDocument) jTextPane1.getDocument();
try {
contText = document.getText(0, document.getLength());
} catch (BadLocationException ex) {
Logger.getLogger(JTextPaneTest.class.getName()).log(Level.SEVERE, null, ex);
}
Then search for your selected text position in the contText as you were doing and you should be good to go. Because, highlighter.addHighlight(int p0, int p1, Highlighter.HighlightPainter p) uses the document for position offset.
Use CaretListener:
To Highlight upon text selection, It is better to use CaretListener, no need to add mouse and key board selection handling code at all:
jTextPane1.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent evt) {
if(evt.getDot() == evt.getMark())return;
JTextPane txtPane = (JTextPane) evt.getSource();
DefaultHighlighter highlighter = (DefaultHighlighter) txtPane.getHighlighter();
highlighter.removeAllHighlights();
DefaultHighlightPainter hPainter = new DefaultHighlightPainter(new Color(0xFFAA00));
String selText = txtPane.getSelectedText();
String contText = "";// = jTextPane1.getText();
DefaultStyledDocument document = (DefaultStyledDocument) txtPane.getDocument();
try {
contText = document.getText(0, document.getLength());
} catch (BadLocationException ex) {
Logger.getLogger(JTextPaneTest.class.getName()).log(Level.SEVERE, null, ex);
}
int index = 0;
while((index = contText.indexOf(selText, index)) > -1){
try {
highlighter.addHighlight(index, selText.length()+index, hPainter);
index = index + selText.length();
} catch (BadLocationException ex) {
Logger.getLogger(JTextPaneTest.class.getName()).log(Level.SEVERE, null, ex);
//System.out.println(index);
}
}
}
});
for example, see
how to remove Highlighter highlighter.removeHighlight(h);
View.modelToView for a new Highlighter
note I don't know how to determine a new line \n inside selection, not possible from this code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
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.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
import javax.swing.text.LayeredHighlighter;
import javax.swing.text.Position;
import javax.swing.text.View;
public class HighlightExample {
private JFrame f = new JFrame("Highlight example");
private JPanel panel = new JPanel();
private JTextPane textPane = new JTextPane();
private JTextField tf = new JTextField("wrapping!");
private String word;
private Highlighter highlighter = new UnderlineHighlighter(null);
public HighlightExample() {
textPane.setHighlighter(highlighter);
textPane.setText("This text pane contains no html. It supports letter wrapping, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping?, "
+ "\nThis text pane contains no html. It supports letter wrapping-, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping_, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping?, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping-, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping?");
panel.setLayout(new BorderLayout());
panel.add(new JLabel("Enter word, then press ENTER key: "), "West");
panel.add(tf, "Center");
/*try {
textPane.read(new FileReader("links1.html"), null);
} catch (Exception e) {
System.out.println("Failed to load file " + args[0]);
System.out.println(e);
}*/
final WordSearcher searcher = new WordSearcher(textPane);
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
word = tf.getText().trim();
int offset = searcher.search(word);
if (offset != -1) {
try {
textPane.scrollRectToVisible(textPane
.modelToView(offset));
} catch (BadLocationException e) {
}
}
}
});
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 void main(String[] args) {
UIManager.put("TextPane.caretForeground", Color.yellow);
UIManager.put("TextPane.selectionBackground", Color.green);
UIManager.put("TextPane.selectionForeground", Color.blue);
/*try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception evt) {
}*/
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new HighlightExample();
}
});
}
}
// A simple class that searches for a word in
// a document and highlights occurrences of that word
class WordSearcher {
protected JTextComponent comp;
protected Highlighter.HighlightPainter painter;
public WordSearcher(JTextComponent comp) {
this.comp = comp;
this.painter = new UnderlineHighlighter.UnderlineHighlightPainter(Color.red);
}
// Search for a word and return the offset of the first occurrence.
// Highlights are added for all occurrences found.
public int search(String word) {
int firstOffset = -1;
Highlighter highlighter = comp.getHighlighter();
// Remove any existing highlights for last word
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; // Look for the word we are given - insensitive search
try {
Document d = comp.getDocument();
content = d.getText(0, d.getLength()).toLowerCase();
} catch (BadLocationException e) {
return -1; // Cannot happen
}
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;
}
}
class UnderlineHighlighter extends DefaultHighlighter {
protected static final Highlighter.HighlightPainter sharedPainter = new UnderlineHighlightPainter(null);// Shared painter used for default highlighting
protected Highlighter.HighlightPainter painter; // Painter used for this highlighter
public UnderlineHighlighter(Color c) {
painter = (c == null ? sharedPainter : new UnderlineHighlightPainter(c));
}
// Convenience method to add a highlight with the default painter.
public Object addHighlight(int p0, int p1) throws BadLocationException {
return addHighlight(p0, p1, painter);
}
#Override
public void setDrawsLayeredHighlights(boolean newValue) {
if (newValue == false) {// Illegal if false - we only support layered highlights
throw new IllegalArgumentException(
"UnderlineHighlighter only draws layered highlights");
}
super.setDrawsLayeredHighlights(true);
}
// Painter for underlined highlights
public static class UnderlineHighlightPainter extends LayeredHighlighter.LayerPainter {
protected Color color; // The color for the underline
public UnderlineHighlightPainter(Color c) {
color = c;
}
#Override
public void paint(Graphics g, int offs0, int offs1, Shape bounds,
JTextComponent c) {// Do nothing: this method will never be called
}
#Override
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;
}
}
}

why JRadioButton is not selected even by using setSelected(true)

i only want one of the above button to be selected by default
but setSelected(true) is not working .
when i run the below program none of the JRadoiButton is selected
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioDemo implements ActionListener {
String buttonName;
JPanel radioPanel=new JPanel();
ButtonGroup group = new ButtonGroup();
Enumeration enl;
int result;
ActionEvent e;
JRadioButton birdButton[];
int i;
Vector<JComponent> list;
Vector<String> listName;
public RadioDemo(Vector<JComponent> list,Vector<String> listName,Enumeration en,Enumeration enl)
{
birdButton=new JRadioButton[list.size()];
this.enl=enl;
this.list=list;
this.listName=listName;
for(i=0;i<list.size()-1;i++)
{
buttonName=(String)enl.nextElement();
birdButton[i] = new JRadioButton(buttonName);
birdButton[i].setSelected(false);
birdButton[i].setActionCommand(buttonName);
group.add(birdButton[i]);
birdButton[i].addActionListener(this);
radioPanel.add(birdButton[i]);
}
buttonName=(String)enl.nextElement();
birdButton[i] = new JRadioButton(buttonName);
birdButton[i].setSelected(true);
birdButton[i].setActionCommand(buttonName);
group.add(birdButton[i]);
birdButton[i].addActionListener(this);
radioPanel.add(birdButton[i]);
radioPanel.setLayout(new BoxLayout(radioPanel,BoxLayout.Y_AXIS));
//birdButton.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
result = JOptionPane.showConfirmDialog(null, radioPanel,
"Please choose", JOptionPane.OK_CANCEL_OPTION);
show();
}
/** Listens to the radio buttons. */
public void actionPerformed(ActionEvent e)
{
this.e=e;
}
public void show()
{
if (result == JOptionPane.OK_OPTION)
{ i=0;
while(!birdButton[i].isSelected())
{
i++;
System.out.println(i);
}
//list.removeElementAt(i);
//listName.removeElementAt(i);
System.out.println(i);
System.out.println(e.getActionCommand());
}
}
i also try birdButton[0].setSelected(true);
out of loop
You haven't posted how you call your constructor, so maybe there is something there. I slightly modified your code, added a main method and it seems to work ok. Take a look at it:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class RadioDemo implements ActionListener {
String buttonName;
JPanel radioPanel = new JPanel();
ButtonGroup group = new ButtonGroup();
int result;
JRadioButton birdButton[];
Vector<String> listName;
private JRadioButton selectedButton;
public RadioDemo(Vector<String> listName) {
birdButton = new JRadioButton[listName.size()];
this.listName = listName;
int i = 0;
for (String buttonName : listName) {
birdButton[i] = new JRadioButton(buttonName);
if (i == 0) {
birdButton[i].setSelected(true);
selectedButton = birdButton[i];
}
birdButton[i].setActionCommand(buttonName);
group.add(birdButton[i]);
birdButton[i].addActionListener(this);
radioPanel.add(birdButton[i]);
i++;
}
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
// birdButton.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
result = JOptionPane.showConfirmDialog(null, radioPanel, "Please choose", JOptionPane.OK_CANCEL_OPTION);
show();
}
/** Listens to the radio buttons. */
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton rb = (JRadioButton) e.getSource();
System.err.println(rb.getText() + " is selected");
selectedButton = rb;
}
public void show() {
if (result == JOptionPane.OK_OPTION) {
System.err.println(selectedButton.getText() + " is selected and approved");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Vector<String> buttonNames = new Vector<String>();
buttonNames.add("Show");
buttonNames.add("Something");
buttonNames.add("Else");
buttonNames.add("Beep");
new RadioDemo(buttonNames);
}
});
}
}

Categories