Problem in jcombobox
Hello friends
i create a mail editor window using Java swing components. i have a combo box in that it have the font names. when ever i change the font name it should reflect in editor its working when i select all the content if i select one particular word in first row and change its font and then i select some other word in some other row if i select the same font to that selected word its not applied to that. any one say how to implement the clicking event in combo box
Read the Swing tutorial on Using Text Components. It has an example of how you can set attributes on a piece of text using the StyledEditorKit actions.
The code will be slightly different for a combo box because you will need to invoke the action yourself with code something like:
public void actionPerformed(ActionEvent e)
JComboBox comboBox = (JComboBox)e.getSource();
Action action = (Action)comboBox.getSelectedItem();
action.actionPerformed(null);
}
Similar Messages
-
FocusListener problem with JComboBox
Hi,
I am facing a problem with JComboBox. When I make it as Editable it is not Listening to the FocucListener Event....
Please tell me if there is any way to overcome this..
Regards,
Chandan SharmaI searched the forum using "jcombobox focuslistener editable" and quess what, the first posting I read had the solution.
Search the forum before posting questions. -
Strange problem with JComboBox
I am having a strange problem with JComboBox, I created a method as a JComboBox factory which returns a JComboBox filled with items. the method works fine and I can see the items in the JComboBox. The problem is when I try using the method myCombo.SelectedItem(String item); the object myCombo does not set the selected item, it just leaves the item blank (or unselected).
//This method build a JComboBox
public javax.swing.JComboBox makeJComboBox(String[] items) {
javax.swing.JComboBox myComboBox = new javax.swing.JComboBox();
for (int index=0;index<items.length;index++){
myComboBox.addItem(makeObj(items[index]));
return myComboBox;
public Object makeObj(final String item) {
return new Object() {
public String toString() {
return item;
}Couple of better ways to populate a combo with items-
public javax.swing.JComboBox makeJComboBox(String[]items) {
javax.swing.ComboBoxModel cbModel = new DefaultComboBoxModel(items);
javax.swing.JComboBox myComboBox = new javax.swing.JComboBox(cbModel);
return myComboBox;
}OR
public javax.swing.JComboBox makeJComboBox(String[]items) {
return new javax.swing.JComboBox(items); -
Problem with JComboBox in a fixed JToolBar
Hi,
I've created a JComboBox in a JToolBar that contains all available fonts. When I click on the drop down arrow I only see the first font and a small part of the second. The JComboBox is dropped down in fact just as far as the border of the JToolbar. All the rest isn't visible to me; it seems that they are behind the other components of my JApplet. However, if I move the JToolBar from it's position (as it's a floatable component), there's no problem at all. So I'm wondering why I can't see everything when the JToolBar is docked.... Can anyone help me?
Thanks in advance!!
E_Jit seems that they are behind the other components of my JApplet.Sounds like you are mixing AWT components with your Swing application. Make sure you are using JPanel, JButton ... and not Panel, Button....
-
Problem with JComboBox in aTable Cell
I try to put JComboBox in JTableCell,
what i want to do is something like this...
Question | Answer |
1. what is your favourite | a. Pizza |
food? | b. Hot Dog |
2. what is your favourite | a. red |
color? | b. blue |
Object[][] data = {
{"1.What is your favourite food?", new AnswerChoices(new String[]{"a.Pizza","b.Hot Dog"})},
{"2.What is your favourite color?", new AnswerChoices(new String[]{"a.red","b.blue"})}
here my code;
//class AnswerChoicesCellEditor
import javax.swing.table.*;
import javax.swing.*;
import java.awt.Component;
import java.awt.event.MouseEvent;
import java.util.EventObject;
import de.falcom.table.*;
public class AnswerChoicesCellEditor extends AbstractCellEditor implements TableCellEditor{
protected JComboBox mComboBox;
public AnswerChoicesCellEditor(){
mComboBox = new JComboBox();
mComboBox.addActionListener(this);
mComboBox.setEditable(false);
public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column){
if(value instanceof AnswerChoices){
AnswerChoices a = (AnswerChoices)value;
String[] c = a.getChoices();
mComboBox.removeAllItems();
for(int i=0; i < c.length; i++)
mComboBox.addItem(c);
mComboBox.setSelectedIndex(a.getAnswer());
return mComboBox;
public Object getCellEditorValue(){
int nchoices = mComboBox.getItemCount();
String[] c = new String[nchoices];
for(int i = 0; i<nchoices; i++){
c[i] = mComboBox.getItemAt(i).toString();
return new AnswerChoices(c,mComboBox.getSelectedIndex());
//return mComboBox.getSelectedItem(); //here i get but after selection there is no comboBox in tableCell
//the Renderer class
import javax.swing.table.TableCellRenderer;
import javax.swing.*;
import java.awt.Component;
public class AnswerChoicesCellRenderer extends JComboBox implements TableCellRenderer {
private Object curValue;
/** Creates new AnswerChoiceCellRenderer */
public AnswerChoicesCellRenderer() {
setEditable(false);
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
if (value instanceof AnswerChoices) {
AnswerChoices nl = (AnswerChoices)value;
String[] tList = nl.getChoices();
if (tList != null) {
removeAllItems();
for (int i=0; i<tList.length; i++)
addItem(tList[i]);
setSelectedIndex(AnswerChoices.getAnswer());
//this.setSelectedItem();
//return this;
//this.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
if (table != null)
if (table.isCellEditable(row, column))
setForeground(CellRendererConstants.EDITABLE_COLOR);
else
setForeground(CellRendererConstants.UNEDITABLE_COLOR);
setBackground(table.getBackground());
return this;
public class AnswerChoices {
static int ans = 0;
String[] choices ;
public AnswerChoices(String[]c,int a){
choices = c;
ans = a;
public AnswerChoices(String[] c){
this(c,0);
public String[] getChoices(){
return choices;
public void setAnswer(int a){
ans = a;
public static int getAnswer(){
return ans;
//the TableModel i used in my app
import java.awt.Color;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.*;
public class FAL_Table extends JTable {
/** Creates new FAL_Table */
public FAL_Table(DefaultTableModel dtm) {
super(dtm);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setRowSelectionAllowed(false);
setColumnSelectionAllowed(false);
setBackground(java.awt.Color.white);
setDefaultCellEditorRenderer();
private void setDefaultCellEditorRenderer(Class forClass, TableCellEditor editor, TableCellRenderer renderer) {
setDefaultEditor(forClass, editor);
setDefaultRenderer(forClass, renderer);
private void setDefaultCellEditorRenderer() {
// Setting default editor&renderer of Boolean
setDefaultCellEditorRenderer(Boolean.class, new BooleanCellEditor(), new BooleanCellRenderer());
//Setting default editor&renderer of ComboBox
setDefaultCellEditorRenderer(JComboBox.class, new ComboBoxCellEditor( ),new ComboBoxRenderer());
// Number class
// Setting default editor&renderer of java.math.BigDecimal
setDefaultCellEditorRenderer(java.math.BigDecimal.class,new NumberCellEditor(), new NumberCellRenderer());
// Setting default editor&renderer of java.math.BigInteger
setDefaultCellEditorRenderer(java.math.BigInteger.class,new NumberCellEditor(), new NumberCellRenderer());
// Setting default editor&renderer of java.lang.Byte
setDefaultCellEditorRenderer(Byte.class,new NumberCellEditor(), new NumberCellRenderer());
// Setting default editor&renderer of Double
setDefaultCellEditorRenderer(Double.class,new NumberCellEditor(), new NumberCellRenderer());
// Setting default editor&renderer of Float
setDefaultCellEditorRenderer(Float.class,new NumberCellEditor(), new NumberCellRenderer());
// Setting default editor&renderer of Integer
setDefaultCellEditorRenderer(Integer.class,new NumberCellEditor(), new NumberCellRenderer());
// Setting default editor&renderer of Long
setDefaultCellEditorRenderer(Long.class,new NumberCellEditor(), new NumberCellRenderer());
// Setting default editor&renderer of Short
setDefaultCellEditorRenderer(Short.class,new NumberCellEditor(), new NumberCellRenderer());
// Setting default editor&renderer of String
setDefaultCellEditorRenderer(String.class,new StringCellEditor(), new StringCellRenderer());
// Setting default editor&renderer of FileName
setDefaultCellEditorRenderer(FileName.class,new FileNameCellEditor(), new FileNameCellRenderer());
// Setting default editor&renderer of Color
setDefaultCellEditorRenderer(Color.class,new ColorCellEditor(), new ColorCellRenderer());
setDefaultCellEditorRenderer(AnswerChoices.class, new AnswerChoicesCellEditor(), new AnswerChoicesCellRenderer());
setDefaultCellEditorRenderer(JSpinner.class, new SpinnerCellEditor(), new SpinnerRenderer());
public Class getCellClass(int row,int col) {
TableModel model = getModel();
if (model instanceof FAL_TableModel) {
FAL_TableModel ptm = (FAL_TableModel)model;
return ptm.getCellClass(row,convertColumnIndexToModel(col));
return model.getColumnClass(convertColumnIndexToModel(col));
public TableCellRenderer getCellRenderer(int row, int column) {
TableColumn tableColumn = getColumnModel().getColumn(column);
TableCellRenderer renderer = tableColumn.getCellRenderer();
if (renderer == null) {
renderer = getDefaultRenderer(getCellClass(row,column));
return renderer;
public TableCellEditor getCellEditor(int row, int column) {
TableColumn tableColumn = getColumnModel().getColumn(column);
TableCellEditor editor = tableColumn.getCellEditor();
if (editor == null) {
editor = getDefaultEditor(getCellClass(row,column));
return editor;
import javax.swing.table.*;
import java.util.Vector;
import java.awt.event.MouseEvent;
import java.util.EventObject;
public class FAL_TableModel extends DefaultTableModel implements TableModel {
public FAL_TableModel() {
this((Vector)null, 0);
public FAL_TableModel(int numRows, int numColumns) {
super(numRows,numColumns);
public FAL_TableModel(Vector columnNames, int numRows) {
super(columnNames,numRows);
public FAL_TableModel(Object[] columnNames, int numRows) {
super(convertToVector(columnNames), numRows);
public FAL_TableModel(Vector data, Vector columnNames) {
setDataVector(data, columnNames);
public FAL_TableModel(Object[][] data, Object[] columnNames) {
setDataVector(data, columnNames);
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
Object obj = getValueAt(row,col);
if (col != 1){
return false;
}else{
return true;
public Class getCellClass(int row,int col) {
Object obj = getValueAt(row,col);
if (obj != null)
return obj.getClass();
else
return Object.class;
public Object getCellValue(int row,int col) {
Object obj = getValueAt(row,col);
return obj;
my problem is, when i select an item from one of the comboBox in the table the value of the other cells changes too and i have the same problem with JSpinner.
please help i am stuck
Gebiand when i try to get the current value oa a cell it returns the Component class like this
AnswerChoices@bf1f20 ... -
Problem in JComboBox selected Index change
hi all
Can anyone send me the code for Loading values to JComboBox & then i want to Display Particular value for that Loaded value in JTextField.
Ex:
I loaded category cade for JComboBox & when JComboBox selected index change the particular category name should appear in JTextBox
ThankzHi,
I am sending a sample program.
Try this, if u had any problem just mail me at [email protected]
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class SwingDemo extends JFrame implements ItemListener
JComboBox combo;
JTextField text;
Properties props;
public SwingDemo() throws Exception
super();
combo=new JComboBox();
text=new JTextField();
addItems("combodata.dat");
setLayout(new GridLayout(2,1));
add(combo);
add(text);
combo.addItemListener(this);
setTitle("JComboBox - Demo");
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
public static void main(String[] args) throws Exception
new SwingDemo();
public void addItems(String str) throws Exception
FileInputStream fis=new FileInputStream(str);
props=new Properties();
props.load(fis);
Enumeration e=props.propertyNames();
while(e.hasMoreElements())
combo.addItem((String)e.nextElement());
public void itemStateChanged(ItemEvent ie)
//System.out.println(ie.getSource());
//System.out.println((ie.getSource()==combo));
if(ie.getSource()==combo)
System.out.println(combo.getSelectedItem());
System.out.println(props.getProperty(combo.getSelectedItem().toString()));
text.setText(props.getProperty(combo.getSelectedItem().toString()));
pack();
For the above program I took data from a file instead of the database
You have to create that file to execute the above program with the name combodata.dat and the values as follwos
1=BSc
2=BCA
3=BA/BCom
4=MSc(IS)
5=MSc(Cs)
6=MCA
7=BE/BTech
8=MBA
Bye...
Thanks & Regards,
Santhosh Reddy Mandadi -
Problem of JComboBox as cell editor in JTable
Hi,
I use JComboBox as cell editor in JTable. If the drop-down menu of the JComboBox out of the JTable area (as the editable cell is near the bottom of the JTable), the item in JComboBox can not be selected with mouse, in this situation there is no MouseEvent to be received in JTable. But it works when I use the keyboard to choose an item in JComboBox.Works fine for me.
If you need further help then you will need to provide [url http://www.physci.org/codes/sscce.jsp]Simple Demo Code that demonstrates the problem. -
Problem setting JComboBox background in Nimbus
I am having a problem setting the background component of a JComboBox when using the Nimbus L&F. The call to JComboBox.setBackground() changes the background of both the content area and the button. I do not want the background color of the button to be changed. I reviewed a number of similar posts in the forums and found a suggested change that results in the button keeping its original background. The code for the suggested change is shown below:
JComboBox bandComboBox;
bandComboBox.setBackground(Color.YELLOW);
// This next line of code changes the background color of the button back to its original value
bandComboBox.getComponent(0).setBackground(UIManager.getColor("control"));
This change did not work for the Nimbus L&F but it did work for the Metal L&F. I really need a solution for the Nimbus L&F. Any suggestions would be greatly appreciated.
I am currently running java 1.6_u13.
Thanks!
CaseyExcept for the actual arrow, the combo box arrow button doesn't paint anything in Nimbus. The highlight, the border, and the gradient background of the arrow button are drawn by the combo box painter. Hence, when you set the background color on the combo box, it also affects the look of the arrow button.
So I thought, what if I made the arrow button opaque? Well.. it does become its own color, but it essentially becomes a giant solid-color square appended to the end of the combo box. Not exactly what we were looking for.
So then I thought that maybe we could use the "Nimbus.Overrides" feature to override the colors on the combo box. Turns out you can't do that. The feature doesn't apply to colors. To change the base colors, you would have to go through the UIManager, and in effect change colors for all the components. Plus, the JComboBox uses colors derived from the same core color - "nimbusBase" - to paint the background of the combo box and the arrow button. So if you change "nimbusBase" to yellow then the whole combo box is still effected (although the results admittedly look better then setBackground(Color.yellow) since the gradient effects are retained).
Anyway, after fiddling around with some ideas, this is what I came up with.
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.Color;
import java.awt.Graphics;
public class Test {
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
public static void createAndShowGUI(){
try {
for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(!("Nimbus".equals(UIManager.getLookAndFeel().getName()))) {
System.err.println("Could not find/install Nimbus LAF!");
System.exit(-1);
SpecialNimbusComboBox specialBox = new SpecialNimbusComboBox(new String[] {
"One","Two","Three"
specialBox.boxColor ; = Color.yellow;
specialBox.arrowBoxColor = Color.red;
JComboBox regularBox = new JComboBox(new String[] {
"One","Two","Three"
JFrame frame = new JFrame();
frame.setLayout(new java.awt.FlowLayout());
frame.add(specialBox);
frame.add(regularBox);
frame.setSize(250,150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
public static class SpecialNimbusComboBox extends JComboBox{
public Color boxColor;
public Color arrowBoxColor;
private boolean ignoreRepaint;
public SpecialNimbusComboBox() {}
public SpecialNimbusComboBox(ComboBoxModel aModel) {super(aModel);}
public SpecialNimbusComboBox(Object[] items) {super(items);}
@Override
public void paintComponent(Graphics g) {
ignoreRepaint = true;
try {
java.awt.Rectangle b = getComponent(0).getBounds();
g.setClip(0, 0, getWidth() - b.width, getHeight());
setBackground(boxColor);
super.paintComponent(g);
g.setClip(b.x, b.y, b.width, b.height);
setBackground(arrowBoxColor);
super.paintComponent(g);
} finally {
ignoreRepaint = false;
@Override
public void repaint() {
if(!ignoreRepaint)
super.repaint();
} -
Hi, javamen.
I ve gotten a little problem when working with Itemlistener interface. My combo has 4 options, in which the first one always appears when the applet starts up. Whenever the user DOESNT change it and submit the applet form, throught a button click, the applet gets a NullPointerException. But, if the user changes the option, i always get it, throught my interface' methods(ItemStateChanged). Of course, i know its because there was no combobox event, just a button event (click). So, how can i deal with this situation, since i need to get the combobox option content.
Regards, Euclides.But, this is the question! I dont know how to initialize the combobox' first option. Help me, please! I am using the addItem method as follow:
MakeJCombo ( JComboBox ComboObj) {
ComboObj.addItem ("option1");
ComboObj.addItem ("option2");
ComboObj.addItem ("option3");
then:
public void itemStateChange(ItemEvent ie) ...
Object origem = ie.getSource()...
if (origem == ComboObj) ... -
Hi,
I have my own classes, in that one of the classes
is extending Jcombobox.
The problem is when i press tab , the focus
is not highlighted in the combobox when i use
J.D.K 1.3.1. But when i use J.D.K.1.2.2,
focus is highlighted.
I want the focus to be highlighted ,when i use
J.D.K.1.3.1. also.
Can anybody help me in this?
Rgds,
Sitas.Seems nobody got this type of problem before,
If anybody knows please help.
thanks in advance,
Rgds,
Suseela -
Problem with JComboBox in a JPanel
I have a JComboBox in a JPanel (with a gridbaglayout), and I add items to the combobox:
String[] stateList={"AL",.....};
JCombobox stateCB=new JComboBox(stateList);
and when I run the application, the states appear in the box, but when I click on the box, there is no drop-down list!
any ideas?Is the combobox Enabled if it is then after adding it to anything set it to true cause i poersonally tried out as u have given it it works and else if it does not show a list then use the setmodel function and set the model to DefaultComboBoxModel and then add the items using a for loop
-
Problem with JComboBox in j2sdk 1.4.2_01
Hi,
I've got a JComboBox, and I want to change its background color. I use this code:
BasicComboBoxEditor editor = (BasicComboBoxEditor)myJComboBox.getEditor();
editor.getEditorComponent().setBackground(SystemColor.control);
This code works with versions 1.3.1 and 1.4.1, but with version 1.4.2_01 it doesn't.
Can anyone tell me another way to change the background color??
Thanx in advance.Hi,
I've got a JComboBox, and I want to change its background color. I use this code:
BasicComboBoxEditor editor = (BasicComboBoxEditor)myJComboBox.getEditor();
editor.getEditorComponent().setBackground(SystemColor.control);
This code works with versions 1.3.1 and 1.4.1, but with version 1.4.2_01 it doesn't.
Can anyone tell me another way to change the background color??
Thanx in advance. -
hi,
i have a JComboBox that has 3 items, when user choose one of them,
how can i get it as a string to store into database.
thanks a lot..import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test extends JFrame implements ItemListener {
JComboBox comboBox;
public test() {
super("JComboBox");
String[] comboBoxItems = {
"one", "two", "three"
comboBox = new JComboBox(comboBoxItems);
comboBox.addItemListener(this);
JPanel panel = new JPanel();
panel.add(new JLabel("select one"));
panel.add(comboBox);
getContentPane().add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,100);
setLocationRelativeTo(null);
setVisible(true);
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
String selection = (String)e.getItem();
System.out.println("selection = " + selection);
public static void main(String[] args) {
new test();
} -
The problem in JComboBox, help!
Hi,
My case is to forbid the users using Up and Down arrow key to access items in the list, but they can still use mouse to access items.
But after I tried several ways, I still can't achieve that. I am using a editable comboBox. So, even my focus is in JTextField, when I press Up and Down arrow keys, the item list was still displayed on the screen. I don't want them appear, but only with mouse at that time.
Does anybody know how to fix that?
Many Thanks!
FengTry this code.
regards,
Stas
JComboBox cb;
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
cb.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "MoveUp");
cb.getActionMap().put("MoveUp", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("up key pressed");
ks = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
cb.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "MoveDown");
cb.getActionMap().put("MoveDown", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("down key pressed");
}); -
Problem adding JComboBox on JtoolBar
hi,
I wanted to added a JComboBox to a toolbar,but the size of the combobox is very big.I am not able to change its size.I tryed .setSize()
its not working.Lengh of the combobox is very long.How to reduce it
comboBox = new JComboBox();
comboBox.setMaximumRowCount(4);
comboBox.setSize(15,18);
//comboBox.setToolTipText("Font Size");
comboBox.setModel(new DefaultComboBoxModel(new String[] { "12", "14",
"16", "18", "20", "22", "24", "26", "28" }));
toolBar.add(comboBox);regards
neeltry this
JComboBox comboBox = new JComboBox();
comboBox.setMaximumRowCount(4);
comboBox.setSize(15,18);
//comboBox.setToolTipText("Font Size");
comboBox.setModel(new DefaultComboBoxModel(new String[] { "12", "14",
"16", "18", "20", "22", "24", "26", "28" }));
JPanel l_pnl = new JPanel();
l_pnl.add(comboBox);
add(l_pnl);
toolBar.add(comboBox);
i hope this will help you
Maybe you are looking for
-
Hi After using tcode ME9F - output message, Instead of going to vendor mailbox it is going to local printer Pl suggest me how to resolve this Thanks Raju
-
I burned disks of previously purchased content that is not available thru iTunes anymore but the latest ver. of iTunes won't let me copy this same content onto a new comp. Is there a way to do this or maybe an earlier ver. of iTunes to download?
-
i have a site that I need to drag and drop a link to the toolbar. I cant get safari to let me drag and drop. Any suggestions?
-
Where can you type in the color hex number in illustrator or photoshop?
There has been a number of occasions that I wanted to work with a particular color and had only the hex number. I can not find how to enter or designate a color using the hex number in Illustrator or Photoshop. How do you do this? This should be a s
-
Can't sync after installing vista
My PC was recently crippled by some serious viruses and i was forced to completely reinstall windows. As i thought i was resigned to losing most of my saved items i decided that this was a good oppertunity to try out vista. However, later when i had