I am programming an editable combobox in a JFrame Form, but i want to change te background color.
How the program works:
If i click the button "press", then the combobox his background needs to become black.
I tried:
1.
cbo.setBackground(Color.BLACK);
But it did nothing
2
cbo.getEditor().getEditorComponent().setBackground(Color.BLACK);
((JTextField) cbo.getEditor().getEditorComponent()).setOpaque(true);
Does this:
Code example:
public class NewJFrame extends javax.swing.JFrame {
private JComboBox cboCategorie;
public NewJFrame() {
initComponents();
cboCategorie = new JComboBox();
cboCategorie.setBounds(10, 10, 250, 26);
cboCategorie.setVisible(true);
cboCategorie.setEditable(true);
this.add(cboCategorie);
}
private void pressActionPerformed(java.awt.event.ActionEvent evt) {
cboCategorie.getEditor().getEditorComponent().setBackground(Color.BLACK);
((JTextField) cboCategorie.getEditor().getEditorComponent()).setOpaque(true);
}
I am working with the Java JDK7
Any sugestions?
see my code example
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.metal.MetalComboBoxButton;
public class MyComboBox {
private Vector<String> listSomeString = new Vector<String>();
private JComboBox someComboBox = new JComboBox(listSomeString);
private JComboBox editableComboBox = new JComboBox(listSomeString);
private JComboBox non_EditableComboBox = new JComboBox(listSomeString);
private JFrame frame;
public MyComboBox() {
listSomeString.add("-");
listSomeString.add("Snowboarding");
listSomeString.add("Rowing");
listSomeString.add("Knitting");
listSomeString.add("Speed reading");
//
someComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
someComboBox.setFont(new Font("Serif", Font.BOLD, 16));
someComboBox.setEditable(true);
someComboBox.getEditor().getEditorComponent().setBackground(Color.YELLOW);
((JTextField) someComboBox.getEditor().getEditorComponent()).setBackground(Color.YELLOW);
//
editableComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
editableComboBox.setFont(new Font("Serif", Font.BOLD, 16));
editableComboBox.setEditable(true);
JTextField text = ((JTextField) editableComboBox.getEditor().getEditorComponent());
text.setBackground(Color.YELLOW);
JComboBox coloredArrowsCombo = editableComboBox;
Component[] comp = coloredArrowsCombo.getComponents();
for (int i = 0; i < comp.length; i++) {// hack valid only for Metal L&F
if (comp[i] instanceof MetalComboBoxButton) {
MetalComboBoxButton coloredArrowsButton = (MetalComboBoxButton) comp[i];
coloredArrowsButton.setBackground(null);
break;
}
}
//
non_EditableComboBox.setPrototypeDisplayValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
non_EditableComboBox.setFont(new Font("Serif", Font.BOLD, 16));
//
frame = new JFrame();
frame.setLayout(new GridLayout(0, 1, 10, 10));
frame.add(someComboBox);
frame.add(editableComboBox);
frame.add(non_EditableComboBox);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
UIManager.put("ComboBox.background", new ColorUIResource(Color.yellow));
UIManager.put("JTextField.background", new ColorUIResource(Color.yellow));
UIManager.put("ComboBox.selectionBackground", new ColorUIResource(Color.magenta));
UIManager.put("ComboBox.selectionForeground", new ColorUIResource(Color.blue));
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyComboBox aCTF = new MyComboBox();
}
});
}
}
Turned out to be easy. Create a renderer and set the background color. Then override the renderer's setOpaque method to always set the opacity to true.
class PDFChooser extends JComboBox<String> {
PDFChooser() {
setRenderer(new Renderer());
}
class Renderer extends DefaultListCellRenderer {
#Override
public void setOpaque(boolean makeBackGroundVisible) {
super.setOpaque(true); // THIS DOES THE TRICK
}
#Override
public Component getListCellRendererComponent(JList<?> list,
Object value, int index,
boolean isSelected, boolean cellHasFocus) {
setText((String)value);
setBackground(Color.cyan);
return this;
}
}
}
If you want the popup menu to use the LAF background, you can add a PopupMenuListener to note when the popup is popped. At that time, the setOpaque method would set the opacity false.
It works for me to change the color of a selected item in JComboBox.
JComboBox cmb = new JComboBox();
cmb.setEditable(true);
cmb.setEditor(new WComboBoxEditor(getContentPane().getBackground()));
// To change the arrow button's background
cmb.setUI(new BasicComboBoxUI(){
protected JButton createArrowButton()
{
BasicArrowButton arrowButton = new BasicArrowButton(BasicArrowButton.SOUTH, null, null, Color.GRAY, null);
return arrowButton;
}
});
cmb.setModel(new DefaultComboBoxModel(new String[] { "a", "b", "c" }));
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxEditor;
import javax.swing.JTextField;
public class WComboBoxEditor implements ComboBoxEditor
{
JTextField tf;
public WComboBoxEditor(Color background)
{
tf = new JTextField();
tf.setBackground(background);
tf.setBorder(null);
}
public Component getEditorComponent()
{
return tf;
}
public void setItem(Object anObject)
{
if (anObject != null)
{
tf.setText(anObject.toString());
}
}
public Object getItem()
{
return tf.getText();
}
public void selectAll()
{
tf.selectAll();
}
public void addActionListener(ActionListener l)
{
tf.addActionListener(l);
}
public void removeActionListener(ActionListener l)
{
tf.removeActionListener(l);
}
}
If you'd like to change the color of items in JCombobox except for a selected one, customize ListCellRenderer.
Related
I'm writing a GUI using Swing. I have a custom written JComboBox using a ListCellRenderer and a BasicComboBoxEditor.
In my getListCellRendererComponent() method I change the color of the the list based on whether the item is "selected" (mouse is hovering above), which is nice and all, but I don't want the selection to change background color once a choice is made, which it currently does.
The first picture shows how the interface looks before a selection is made, and the second one shows how it looks after.
QUESTION
How do I change the background of the "selection" to the "stockColor"?
MCVE
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.plaf.basic.BasicComboBoxEditor;
public class TFComboBox extends JComboBox{
public static void main(String[] args){
createAndShowGUI();
}
public static void createAndShowGUI(){
JFrame frame = new JFrame("MCVE");
JPanel pane = new JPanel(new BorderLayout());
TFComboBox cb = new TFComboBox();
boolean[] tf = {true, false};
cb.addItems(tf);
JButton b = new JButton("Click me!");
pane.add(cb, BorderLayout.CENTER);
pane.add(b, BorderLayout.LINE_END);
frame.add(pane);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private DefaultComboBoxModel model;
private Vector<Boolean> comboBoxItems;
private JComboBox comboBox;
public TFComboBox(){
comboBoxItems = new Vector<Boolean>();
comboBoxItems.add(Boolean.TRUE);
comboBoxItems.add(Boolean.FALSE);
comboBox = new JComboBox(comboBoxItems);
model = new DefaultComboBoxModel();
setModel(model);
setRenderer(new TrueFalseComboRenderer());
setEditor(new TrueFalseComboEditor());
}
public void addItems(boolean[] items){
for(boolean anItem : items){
model.addElement(anItem);
}
}
}
class TrueFalseComboRenderer extends JPanel implements ListCellRenderer {
private JLabel labelItem = new JLabel();
private Color stockColor = labelItem.getBackground();
public TrueFalseComboRenderer(){
setLayout(new BorderLayout());
labelItem.setOpaque(true);
labelItem.setHorizontalAlignment(JLabel.CENTER);
add(labelItem);
setBackground(Color.LIGHT_GRAY);
}
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
boolean tempValue = (boolean) value;
labelItem.setText(Boolean.toString(tempValue));
if(isSelected){
labelItem.setBackground(stockColor.darker());
labelItem.setForeground(Color.WHITE);
} else {
labelItem.setBackground(stockColor);
labelItem.setForeground(Color.BLACK);
}
return this;
}
}
class TrueFalseComboEditor extends BasicComboBoxEditor {
private JLabel labelItem = new JLabel();
private JPanel panel = new JPanel();
private Object selectedItem;
public TrueFalseComboEditor() {
labelItem.setOpaque(false);
labelItem.setHorizontalAlignment(JLabel.CENTER);
labelItem.setForeground(Color.WHITE);
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 2));
panel.setBackground(Color.BLUE);
panel.add(labelItem);
}
public Component getEditorComponent(){
return this.panel;
}
public Object getItem(){
return this.selectedItem;
}
public void setItem(Object item){
if(item == null){
return;
}
this.selectedItem = item;
labelItem.setText(item.toString());
}
}
EDIT
I've added a MCVE and as you can see it is the "problem" that the JComboBox is focused that has to do with my issue. I've placed a button next to the ComboBox to help with removing the focus from the ComboBox.
Simply doing a setFocusable(false) would fix it, but also take away some of the functionality of the rest of the program, so this is not desired.
for better help sooner post an SSCCE / MCVE, short, runnable, compilable, with hardcoded value for JComboBox / XxxComboBoxModel in local variable
JList has Boolean array implemented as default in API (no idea whats hidden in
String trueFalseItem = Boolean.toString(tempValue); and with value stored JComboBox model)
this is just code minimum to test isSelected and to change JList.setSelectionXxx inside DefaultListCellRenderer
for example (code in SSCCE / MCVE form)
.
.
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.SwingUtilities;
public class ComboBoxBooleanModel {
private javax.swing.Timer timer = null;
private Vector<Boolean> comboBoxItems;
private JComboBox box;
public ComboBoxBooleanModel() {
comboBoxItems = new Vector<Boolean>();
comboBoxItems.add(Boolean.TRUE);
comboBoxItems.add(Boolean.FALSE);
box = new JComboBox(comboBoxItems);
box.setRenderer(new DefaultListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
if (Boolean.TRUE.equals(value)) {
l.setBackground(Color.RED);
if (isSelected) {
list.setSelectionForeground(Color.RED);
list.setSelectionBackground(Color.BLUE);
}
} else if (Boolean.FALSE.equals(value)) {
l.setBackground(Color.BLUE);
if (isSelected) {
list.setSelectionForeground(Color.BLUE);
list.setSelectionBackground(Color.RED);
}
}
return l;
}
return c;
}
});
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(box);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
box.setSelectedIndex(1);
}
});
start();
}
private void start() {
timer = new javax.swing.Timer(2250, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (box.getSelectedItem() == (Boolean) false) {
box.setSelectedItem((Boolean) true);
} else {
box.setSelectedItem((Boolean) false);
}
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboBoxBooleanModel comboBoxModel = new ComboBoxBooleanModel();
}
});
}
}
Here is a short demo of 2 JCombos, one of which will not change its background color when selected :
public static void main(String[] args){
JFrame frame = new JFrame("Combos BG Color test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.getContentPane().setPreferredSize(new Dimension(400, 40));
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(1,2));
frame.add(mainPanel);
JComboBox<String> aCombo = new JComboBox<>(new String[]{"A","B","C"});
mainPanel.add(aCombo);
JComboBox<String> bCombo = new JComboBox<>(new String[]{"1","2","3"});
Color bgColor = bCombo.getBackground();
bCombo.setRenderer(new DefaultListCellRenderer() {
#Override
public void paint(Graphics g) {
setBackground(bgColor);
super.paint(g);
}
});
mainPanel.add(bCombo);
frame.pack();
frame.setVisible(true);
}
(Most of the credit goes to this answer)
I am dynamically adding items to my JPanel through an ArrayList<Items>. Basically the items object looks like that:
public class Item {
private JComponent component;
private String functionality;
public Item(JComponent component, String functionality) {
super();
this.component = component;
this.functionality = functionality;
}
public JComponent getComponent() {
return component;
}
public void setComponent(JComponent component) {
this.component = component;
}
public String getFunctionality() {
return functionality;
}
public void setFunctionality(String functionality) {
this.functionality = functionality;
}
}
Here I am adding my buttons dynamically: (try the example out if you want)
public class minimumExample extends JFrame {
private JButton addItem;
private JComboBox itemBox;
private String[] itemSelect = { "test1", "test2" };
private JPanel addUpperPane;
private JPanel addLowerPane;
private ArrayList<Item> displayedItems = new ArrayList<Item>();
private JButton upButton;
private JButton downButton;
private JButton deleteButton;
public void createControlPane() {
addUpperPane = new JPanel();
addLowerPane = new JPanel(new GridLayout(0, 1));
addItem = new JButton("Add item");
upButton = new JButton("Up");
downButton = new JButton("Down");
deleteButton = new JButton("Delete");
itemBox = new JComboBox(itemSelect);
addItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(itemBox.getSelectedItem().toString().equals("test1")) {
displayedItems.add(new Item( new ButtonComp().butt(), "test1"));
validate();
repaint();
}
if(itemBox.getSelectedItem().toString().equals("test2")) {
displayedItems.add(new Item( new LabelComp().label(), "test2"));
validate();
repaint();
}
for (int i = 0; i < displayedItems.size(); i++) {
addLowerPane.add(displayedItems.get(i).getComponent());
validate();
repaint();
}
}
});
addUpperPane.add(itemBox, BorderLayout.EAST);
addUpperPane.add(addItem, BorderLayout.WEST);
addUpperPane.add(new JLabel(" | "), BorderLayout.WEST);
addUpperPane.add(upButton, BorderLayout.WEST);
addUpperPane.add(downButton, BorderLayout.WEST);
addUpperPane.add(deleteButton, BorderLayout.WEST);
addUpperPane.add(new JSeparator(JSeparator.HORIZONTAL));
//put everything together
add(addUpperPane, BorderLayout.NORTH);
add(addLowerPane, BorderLayout.SOUTH);
repaint();
}
private void makeLayout() {
setTitle("Test App");
setLayout(new BorderLayout());
setPreferredSize(new Dimension(1000, 500));
createControlPane();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
/**
* starts the GUI
*/
public void start() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
makeLayout();
}
});
}
public static void main(String[] args) throws IOException {
minimumExample ex = new minimumExample();
ex.start();
}
public class ButtonComp extends Component {
public JPanel butt() {
JPanel panel = new JPanel();
JButton button = new JButton("Test1");
JCheckBox check = new JCheckBox();
panel.add(button);
panel.add(check);
return panel;
}
}
public class LabelComp extends Component {
public JPanel label() {
JPanel panel = new JPanel();
JLabel label = new JLabel("Test2");
JCheckBox check = new JCheckBox();
panel.add(label);
panel.add(check);
return panel;
}
}
}
The program basically looks like that:
My problem is that the buttons Up, Down and Delete do not work, because I do not know how to get the selected element from the pane to delete it from the list where all components are in. Any recommendations on how to make this work?
I really appreciate your answer!
UPDATE
I changed my code your specifications #cghislai but it does not work. Try it out yourself:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
public class minimumExample extends JFrame {
private JButton addItem;
private JComboBox itemBox;
private String[] itemSelect = { "test1", "test2" };
private JPanel addUpperPane;
private JPanel addLowerPane;
private List<CheckableItem> displayedItems = new ArrayList<CheckableItem>();
private JButton upButton;
private JButton downButton;
private JButton deleteButton;
public void createControlPane() {
addUpperPane = new JPanel();
addLowerPane = new JPanel(new GridLayout(0, 1));
addItem = new JButton("Add item");
upButton = new JButton("Up");
downButton = new JButton("Down");
deleteButton = new JButton("Delete");
itemBox = new JComboBox(itemSelect);
addItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(itemBox.getSelectedItem().toString().equals("test1")) {
ButtonComp butt = new ButtonComp();
butt.init();
displayedItems.add(butt);
validate();
repaint();
}
if(itemBox.getSelectedItem().toString().equals("test2")) {
// displayedItems.add(new CopyOfItem( new LabelComp(), "test2"));
validate();
repaint();
}
for (int i = 0; i < displayedItems.size(); i++) {
addLowerPane.add(displayedItems.get(i).getComponent());
validate();
repaint();
}
}
});
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Iterator<CheckableItem> it = displayedItems.iterator();
while (it.hasNext()) {
CheckableItem next = it.next();
if (next.isSelected()) {
addLowerPane.remove(next.getComponent());
it.remove();
continue;
}
}
}
});
addUpperPane.add(itemBox, BorderLayout.EAST);
addUpperPane.add(addItem, BorderLayout.WEST);
addUpperPane.add(new JLabel(" | "), BorderLayout.WEST);
addUpperPane.add(upButton, BorderLayout.WEST);
addUpperPane.add(downButton, BorderLayout.WEST);
addUpperPane.add(deleteButton, BorderLayout.WEST);
addUpperPane.add(new JSeparator(JSeparator.HORIZONTAL));
//put everything together
add(addUpperPane, BorderLayout.NORTH);
add(addLowerPane, BorderLayout.SOUTH);
repaint();
}
private void makeLayout() {
setTitle("Test App");
setLayout(new BorderLayout());
setPreferredSize(new Dimension(1000, 500));
createControlPane();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
/**
* starts the GUI
*/
public void start() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
makeLayout();
}
});
}
public static void main(String[] args) throws IOException {
minimumExample ex = new minimumExample();
ex.start();
}
public abstract class CheckableItem {
protected JCheckBox check;
public boolean isSelected() {
return check.isSelected();
}
public abstract Component getComponent();
}
public class ButtonComp extends CheckableItem {
JPanel panel = new JPanel();
public void init() {
JButton button = new JButton("Test1");
check = new JCheckBox();
panel.add(button);
panel.add(check);
}
#Override
public Component getComponent() {
return panel;
}
}
public class LabelComp extends JPanel {
public void label() {
// JPanel panel = new JPanel();
JLabel label = new JLabel("Test2");
JCheckBox check = new JCheckBox();
add(label);
add(check);
}
}
}
You need to traverse all your items, check if the item checkbox is selected, if this is the case, remove your item from the panel. I would make an abstract CheckableItem class with a getter to the JCheckbox and the Component. Then, for each of you item, if the checkbox is selected, remove the component from the parent.
public abstract class CheckableItem {
protected JCheckbox checkbox;
public boolean isSelected() {
return checkbox.isSelected();
}
public abstract Component getComponent();
}
public class ButtonComp extends CheckableItem {
private Panel panel;
public void init() {
checkbox = new JCheckbox;
panel = new JPanel();
panel.add(new JButton());
panel.add(checkbox);
}
public Component getComponent() {
return panel;
}
}
Then to keep track of your items:
private List<CheckableItem> items = new ArrayList<>();
// ...
ButtonComp comp = new ButtonComp();
comp.init();
items.add(comp);
Then to remove all checked:
Iterator<CheckbleItem> it = items.iterator();
while (it.hasNext()) {
CheckableItem next = it.next();
if (next.isSelected()) {
mainPanel.remove(next.getComponent());
it.remove();
continue;
}
}
Why don't you just have your ButtomComp and LabelComp extend from JPanel? This would solve a lot of your problems I think. For example :
public class ButtonComp extends JPanel {
JButton button;
JCheckBox check = new JCheckBox();
public ButtonComp() {
button = new JButton("Test1");
this.add(button);
this.add(check);
}
}
Then all you would need to do is iterate over your items and look at the checkbox in the components :
for (int i = 0; i < displayedItems.size(); i++) {
if (displayedItems.get(i).check.isSelected()) {
displayedItems.remove(i);
}
}
Note: haven't tested this code. But you should get the idea.
I am coding a little game in which,in one class(named Brick) which extends JPannel,i have a JButton working as a "Brick" and in another class which extends JFrame i have an ArrayList of Brick named Grid which holds the Bricks.But i don't know how to represent the Bricks of ArrayList of Bricks in the serial form,i.e,one after the anoher,on the JFrame of Grid class.Please give me some suggestions.
EDIT : I also want no space between the two buttons.How can i stick two buttons,sharing boundaries?
You may use the following code snippet to add and array of customized classes of JButton.
You may edit it as per your needs.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* A JList of JButtons.
*/
public class JButtonListDemo implements Runnable
{
private JList jlist;
public static void main(String args[])
{
SwingUtilities.invokeLater(new JButtonListDemo());
}
public void run()
{
Object[] items = new ButtonItem[] {
new ButtonItem("Apple"),
new ButtonItem("Banana"),
new ButtonItem("Carrot"),
new ButtonItem("Date"),
new ButtonItem("Eggplant"),
new ButtonItem("Fig"),
new ButtonItem("Guava"),
};
jlist = new JList(items);
jlist.setCellRenderer(new ButtonListRenderer());
jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jlist.setVisibleRowCount(5);
jlist.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent event)
{
clickButtonAt(event.getPoint());
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(jlist));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void clickButtonAt(Point point)
{
int index = jlist.locationToIndex(point);
ButtonItem item = (ButtonItem) jlist.getModel().getElementAt(index);
item.getButton().doClick();
// jlist.repaint(jlist.getCellBounds(index, index));
}
public class ButtonItem
{
private JButton button;
public ButtonItem(String name)
{
this.button = new JButton(name);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println(button.getText() + " was clicked.");
}
});
}
public JButton getButton()
{
return button;
}
#Override
public String toString()
{
return button.getText();
}
}
class ButtonListRenderer extends JButton implements ListCellRenderer
{
public Component getListCellRendererComponent(JList comp, Object value, int index,
boolean isSelected, boolean hasFocus)
{
setEnabled(comp.isEnabled());
setFont(comp.getFont());
setText(value.toString());
if (isSelected)
{
setBackground(comp.getSelectionBackground());
setForeground(comp.getSelectionForeground());
}
else
{
setBackground(comp.getBackground());
setForeground(comp.getForeground());
}
return this;
}
}
}
Alternatively, you could always layout your JButtons vertically on a JPanel (using a new GridLayout(0,1) perhaps) and then put your JPanel in a JScrollPane, thus mocking a JList of JButtons.
I have a problem with making JComboBox transparent. I tried setting opaque to false and alpha of background 0 but it doesnt work. I guess that i need to change some class that does rendering or something similar.And here is the code..
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.plaf.basic.BasicComboBoxUI;
import java.awt.Color;
public class App {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App window = new App();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public App() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.GREEN);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JComboBox comboBox = new JComboBox(petStrings);
comboBox.setBounds(149, 99, 155, 20);
comboBox.setOpaque(false);
//comboBox.setBackground(new Color(0,0,0,0));
((JTextField)comboBox.getEditor().getEditorComponent()).setOpaque(false);
comboBox.setUI(new BasicComboBoxUI(){
public void paintCurrentValueBackground(Graphics g,Rectangle bounds,boolean hasFocus){}});
frame.getContentPane().add(comboBox);
}
}
Assuming you just want the ComboBox's text field transparent (not the popup as well), using the following code should work. You need to mess with the ComboBox renderer instead of the editor. The editor is used for if you can type into the ComboBox; The renderer is used if the ComboBox is a list of values only.
comboBox.setOpaque(false);
comboBox.setRenderer(new DefaultListCellRenderer(){
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JComponent result = (JComponent)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
result.setOpaque(false);
return result;
}});
JComboBox myComboBox = new JComboBox(array);
myComboBox .setOpaque(false);
myComboBox .setEditable(true);
JTextField boxField = (JTextField)myComboBox .getEditor().getEditorComponent();
boxField.setBorder(BorderFactory.createEmptyBorder());
boxField.setBackground(new Color(0, 0, 0, 0));
boxField.setFocusable(false);
The answer is in http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6687960
You need to preset this few things
jcombo.setOpaque(false);
jcombo.setContentAreaFilled(false);
jcombo.setBorderPainted(false);
try this.
yourComboBox.setOpaque(false);
((JTextField)yourComboBox.getEditor().getEditorComponent()).setOpaque(false);
setUI(new BasicComboBoxUI() {
#Override
public void paintCurrentValueBackground(
Graphics g, Rectangle bounds, boolean hasFocus) {
}
});
I try to attach action Events on the JCombobox arrow JButton.
So I make a custom ComboBoxUI:
public class CustomBasicComboBoxUI extends BasicComboBoxUI {
public static CustomBasicComboBoxUI createUI(JComponent c) {
return new CustomBasicComboBoxUI ();
}
#Override
protected JButton createArrowButton() {
JButton button=super.createArrowButton();
if(button!=null) {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// arrow button clicked
}
});
}
return button;
}
}
The problem with this is that the look of combobox is different, seem to be an old look.
Why? I only add a listener to the same arrow button...
Thank.
Perhaps the problem is due to your expecting a JComboBox isn't a BasicComboBoxUI but one of another look and feel, perhaps a MetalComboBoxUI.
Rather than create a new CustomBasicComboBoxUI object, could you extract the JButton component from an existing JComboBox object? i.e.,
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ComboBoxArrowListener {
private static void createAndShowUI() {
String[] data = {"One", "Two", "Three"};
JComboBox combo = new JComboBox(data);
JPanel panel = new JPanel();
panel.add(combo);
JButton arrowBtn = getButtonSubComponent(combo);
if (arrowBtn != null) {
arrowBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("arrow button pressed");
}
});
}
JFrame frame = new JFrame("ComboBoxArrowListener");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static JButton getButtonSubComponent(Container container) {
if (container instanceof JButton) {
return (JButton) container;
} else {
Component[] components = container.getComponents();
for (Component component : components) {
if (component instanceof Container) {
return getButtonSubComponent((Container)component);
}
}
}
return null;
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}