How can add image and text both in combo box in java - java

Actually I want to add image and text both in combo box . I have use JLabel for that but it doesn't work so how can I achieve this.
Here is my code :
package swing;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ComboBox {
public ComboBox() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("ComboBOx");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = frame.getContentPane();
JLabel ar[] = new JLabel[5];
ar[0] = new JLabel("ganesh",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[1] = new JLabel("ganes",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[2] = new JLabel("gane",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[3] = new JLabel("gan",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
ar[4] = new JLabel("ga",new ImageIcon("/images/g.jpg"),JLabel.HORIZONTAL);
JComboBox<JLabel> box = new JComboBox<JLabel>(ar);
con.add(box);
con.setBackground(Color.white);
con.setLayout(new FlowLayout());
frame.setVisible(true);
frame.pack();
}
public static void main(String args[]) {
new ComboBox();
}
}

#MadProgrammer Thanks, I find my answer
package swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class ComboBox {
ImageIcon imageIcon[] = { new ImageIcon("/images/g.jpg"), new ImageIcon("/images/g.jpg"),
new ImageIcon("/images/g.jpg"), new ImageIcon("/images/g.jpg"), new ImageIcon("/images/g.jpg") };
Integer array[] = {1,2,3,4,5};
String names[] = {"img1","img2","img3","img4","img5"};
public ComboBox() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("ComboBOx");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = frame.getContentPane();
ComboBoxRenderar rendrar = new ComboBoxRenderar();
JComboBox box = new JComboBox(array);
box.setRenderer(rendrar);
con.add(box);
con.setLayout(new FlowLayout());
frame.setVisible(true);
frame.pack();
}
public class ComboBoxRenderar extends JLabel implements ListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
int offset = ((Integer)value).intValue() - 1 ;
ImageIcon icon = imageIcon[offset];
String name = names[offset];
setIcon(icon);
setText(name);
return this;
}
}
public static void main(String args[]) {
new ComboBox();
}
}

Related

JPanel removeAll not working like it should

Problem: the buttons aren't being removed with lPanel.bListPanel.removeAll() included in the code.
My goal: when the button is clicked, I need the old buttons to disappear and a new list of buttons to populate.
Note: this button listener is in a separate class from the lPanel.
Thanks!
RoPanel class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class RoPanel extends JPanel {
public LPanel lPanel;
public RPanel rPanel;
private Ly l;
private ArrayList<JButton> bButtonList;
private JTextField newLoadField;
private JButton theButton;
public String bText;
private Border simpleBorder;
public RoPanel() {
this.setLayout(new BorderLayout());
simpleBorder = BorderFactory.createLineBorder(Color.GRAY);
l = new Ly();
lPanel = new LPanel();
rPanel = new RPanel();
this.setBorder(simpleBorder);
this.add(lPanel, BorderLayout.WEST);
this.add(rPanel, BorderLayout.EAST);
titleBooks = new ArrayList();
lPanel.getLoadButton();
lPanel.getLoadButton().addActionListener(new LoadButtonListener());
newLoadField = lPanel.getLoadField();
bookButtonList = new ArrayList();
bookText = new String();
}
private class LoadButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String loadStringfile = newLoadField.getText();
l.loadFromCSV(loadStringfile);
lPanel.bListPanel.removeAll();
// for loop that creates buttons
for (int i = 0; i < l.size(); i++) {
BButton b = new BButton();
bButtonList.add(theButton);
lPanel.bListPanel.add(theButton);
}
lPanel.bListPanel.revalidate();
lPanel.bListPanel.repaint();
}
}
}
LPanel class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.*;
public class LPanel extends JPanel {
private JTextField loadField;
private JButton loadButton;
private Border simpleBorder;
private Border lowerBorder;
JPanel bListPanel;
JPanel importPanel;
public LPanel() {
this.setLayout(new BorderLayout());
simpleBorder = BorderFactory.createLineBorder(Color.GRAY);
lowerBorder = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
bListPanel = new JPanel();
bListPanel.setLayout(new BoxLayout(bListPanel, BoxLayout.Y_AXIS));
importPanel = new JPanel();
this.add(importPanel, BorderLayout.SOUTH);
// create a jscrollpane that contains all buttons
JScrollPane scrollPane = new JScrollPane();
scrollPane.setLocation(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.getViewport().add(bListPanel);
this.add(scrollPane);
// loadfield and load button for iPanel
loadField = new JTextField();
loadField.setPreferredSize(new Dimension(170, 25));
importPanel.add(loadField);
loadButton = new JButton();
loadButton.setText("Load");
importPanel.add(loadButton);
}
}

About getting values from JList

I am trying to get values from a database via Jlist; but when I select a value of Jlist, no values return and the "Jtable" becomes empty instead of titles. That's my code for UI.
Thanks for your help...
package ui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import model.Category;
import model.Person;
import service.AddressBookService;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JSplitPane;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.UIManager;
import javax.swing.AbstractListModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
public class UserInterfaceMain extends JFrame {
private JPanel contentPane;
private JPanel panel;
private JButton btnNew;
private JSplitPane splitPane;
private JList list;
private JTable table;
private JScrollPane scrollPane;
private List<Category> categories = new ArrayList<>();
private List<Person> personList = new ArrayList<>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserInterfaceMain frame = new UserInterfaceMain();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public UserInterfaceMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 624, 395);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panel = new JPanel();
contentPane.add(panel, BorderLayout.NORTH);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
btnNew = new JButton("NEW");
panel.add(btnNew);
splitPane = new JSplitPane();
contentPane.add(splitPane, BorderLayout.CENTER);
list = new JList();
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
do_list_valueChanged(arg0);
}
});
splitPane.setLeftComponent(list);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.EAST);
table = new JTable();
splitPane.setRightComponent(table);
scrollPane.setViewportView(table);
loadCategories();
}
public void loadCategories() {
categories = new AddressBookService().getAllCategories();
DefaultListModel<Category> listModel = new DefaultListModel<>();
for (int i = 0; i < categories.size(); i++) {
listModel.addElement(categories.get(i));
//listModel.addElement(categories.get(i).getName());
}
list.setModel(listModel);
}
public void loadPersonList() {
String[] columns = new String[] { "NAME", "LAST NAME", "E-MAIL", "CITY" };
Object[][] personData = new Object[personList.size()][];
for (int i = 0; i < personData.length; i++) {
personData[i] = new Object[] { personList.get(i).getName(), personList.get(i).getLastName(),
personList.get(i).getEmail(), personList.get(i).getCity() };
}
TableModel tableModel = new DefaultTableModel(personData, columns);
table.setModel(tableModel);
}
protected void do_list_valueChanged(ListSelectionEvent arg0) {
personList = new AddressBookService().getPersonsForTable(((Category)list.getSelectedValue()).getId());
loadPersonList();
System.out.println(personList.size());
}
}
I don't understand exactly what you want, but I modified your code to run it in this way:
Obviously I have all hardcoded in order to run your program. If your problem is that in the left side instead of the names of the categories appears the hash code of the object "com.mypackage.Category#12AAAF", you must modify your Category class and override the toString method.
#Override
public String toString() {
return getName();
}
If it isn't your problem, please add a comment describing it.

netbeans does not run javaswing application

The JavaSwing application shows no errors in netbeans. When I try to run it, it takes forever and nothing is happening(JDK 8 + Netbeans 8.1). The same problem in eclipse. A simple hello world program works. The program is divided in 4 classes. Sorry for the long code.
package test2;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class MainWindow extends JFrame {
private Navigator navigator = new Navigator(this);
private Field spielfeld = new Field();
public MainWindow() {
super("GameTest");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.add(spielfeld);
this.setResizable(false);
this.pack();
}
public static void main(String[] args) {
new MainWindow();
}
}
package test2;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
public class Field extends JPanel {
private static int x = 10;
private static int y = 10;
private JLabel[][] fields = new JLabel[10][10];
public Field() {
Dimension dim = new Dimension();
dim.setSize(50, 50);
this.setLayout(new GridLayout(x, y));
for(int i = 0; i < y; i++){
for(int j = 0; j < x; j++){
fields[i][j] = new JLabel();
fields[i][j].setPreferredSize(dim);
fields[i][j].setOpaque(true);
if((i+j)%2 == 0){
fields[i][j].setBackground(Color.BLACK);
}
else {
fields[i][j].setBackground(Color.WHITE);
}
this.add(fields[i][j]);
}
}
}
}
package test2;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JWindow;
public class Navigator extends JWindow {
public Navigator(JFrame parent) {
super(parent);
JPanel frame = new JPanel();
frame.setLayout(new BorderLayout());
frame.setBorder(BorderFactory.createLineBorder(Color.RED));
frame.add(new Keypad(), BorderLayout.NORTH);
this.getContentPane().add(frame);
this.updateLocation();
this.pack();
}
public void updateLocation()
{
this.setLocation((int)this.getParent().getLocation().getX() + this.getParent().getWidth() + 550,
(int)this.getParent().getLocation().getY());
}
public MainWindow getMainWindow()
{
return (MainWindow)this.getParent();
}
}
package test2;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Keypad extends JPanel {
public Keypad() {
Dimension dim = new Dimension(60, 30);
this.setLayout(new GridLayout(3, 3));
this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
for(int i = 9; 0 < i; i--) {
JButton button = new JButton(String.valueOf(i));
button.setPreferredSize(dim);
button.setVisible(true);
if(i != 5) {
this.add(button);
this.add(button);
}
}
this.setVisible(true);
}
}
You are missing setVisible(true) inside your MainWindow constructor.
The code will "run forever" with or without this line. The only difference is that the window will be shown.

My UI is being shown twice in the same window

Here's an example
My Jtextfields and Jbuttons are being duplicated in the same window, and appear to function exactly the same.
This is probably an easy fix, but as you can tell I'm pretty awful at coding.
(oh and some of the names for variables and such are placeholders :p)
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.GridLayout;
import java.awt.Font;
import java.awt.FlowLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
import javax.swing.JLabel;
public class Adding extends JFrame {
public Adding(Heavy_Lifting lifting) {
addUI(lifting);
}
public void addUI(final Heavy_Lifting lifting) {
setLayout(new FlowLayout());
JButton addButton = new JButton("Enter");
JButton backButton = new JButton("Quit");
final JTextField eInput = new JTextField("Enter english name");
final JTextField mInput = new JTextField("Enter maori name");
final JTextField dInput = new JTextField("Enter description");
//add(addButton);
//add(eInput);
//add(mInput);
//add(backButton);
//add(dInput);
Dimension x = new Dimension(500, 50);
//addButton.setText("Enter");
addButton.setPreferredSize(x);
//backButton.setText("Quit");
backButton.setPreferredSize(x);
//eInput.setText("Enter english name");
eInput.setPreferredSize(x);
//mInput.setText("Enter maori name");
mInput.setPreferredSize(x);
//dInput.setText("Enter description");
dInput.setPreferredSize(x);
add(addButton);
add(eInput);
add(mInput);
add(dInput);
add(backButton);
addButton.addActionListener(new ActionListener() {#
Override
public void actionPerformed(ActionEvent e) {
String mname = mInput.getText();
String ename = eInput.getText();
String desc = dInput.getText();
PeePee p = new PeePee(mname);
Description d = new Description(desc);
if (lifting.allChar(ename, p)) {
lifting.insert(ename, p);
lifting.insert(ename, d);
eInput.setText("1");
mInput.setText("2");
dInput.setText("3");
} else {
eInput.setText("4");
mInput.setText("5");
dInput.setText("6");
}
}
});
backButton.addActionListener(new ActionListener() {#
Override
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
setTitle("placeholder");
setSize(550, 300);
setMinimumSize(new Dimension(550, 300));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
}
This looks like your public method addUI is called twice, maybe by another class. Try switch it to private and see if it still runs and produces the same visual output.

How set size of specified String to JTextField?

JTextField in JPanel which in turn in JDialog doesn't take specified size. I tried to use BoxLayout and FlowLayout, but still have not achieved the desired size. I.E. I measure the size of String example and set this size to width of JTextField inputCat, but inputCat doesn't take this size, then I call it. How correctly set size of specified String to JTextField? Here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.util.Calendar;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DemoJDialog {
static private JInternalFrame internal;
public static void main(String[] args) {
new DemoJDialog();
}
public DemoJDialog() {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
internal = new JInternalFrame("Example", true, true, false, true);
internal.setLayout(new BorderLayout());
internal.setVisible(true);
JDesktopPane dp = new JDesktopPane();
dp.add(internal);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(dp);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JTextField inputCat = new JTextField();
String example = new String("Some very-very-very-"
+ "very-very-very-very-very-very long string (really long )");
int heightInputCat = inputCat.getSize().height;
FontMetrics FN = internal.getFontMetrics(internal.getFont());
int widthInputCat = SwingUtilities.computeStringWidth(FN, example);
inputCat.setSize(widthInputCat, heightInputCat);
String[] comboString = { "Telecast", "Radiocast" };
JComboBox comboBox = new JComboBox(comboString);
Calendar now = Calendar.getInstance();
SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(),
null, null, Calendar.MONTH);
final JSpinner spinner = new JSpinner(modelSpinner);
spinner.setEditor(new JSpinner.DefaultEditor(spinner));
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
listPane.add(comboBox);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(inputCat);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(spinner);
Object[] array = {
new JLabel ("Enter a new category:"),
listPane
};
JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = pane.createDialog(internal, "Enter a new category:");
dialog.setVisible(true);
}
});
}
}
This works just fine here:
import java.awt.EventQueue;
import java.util.Calendar;
import javax.swing.*;
public class DemoJDialog {
public static void main(String[] args) {
new DemoJDialog();
}
public DemoJDialog() {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({"rawtypes", "unchecked"})
#Override
public void run() {
String example = new String("Some very-very-very-"
+ "very-very-very-very-very-very "
+ "long string (really long)");
// create a textfield the size of the string!
JTextField inputCat = new JTextField(example);
inputCat.setCaretPosition(0);
String[] comboString = {"Telecast", "Radiocast"};
JComboBox comboBox = new JComboBox(comboString);
Calendar now = Calendar.getInstance();
SpinnerModel modelSpinner = new SpinnerDateModel(now.getTime(),
null, null, Calendar.MONTH);
final JSpinner spinner = new JSpinner(modelSpinner);
spinner.setEditor(new JSpinner.DefaultEditor(spinner));
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
listPane.add(comboBox);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(inputCat);
listPane.add(Box.createHorizontalStrut(10));
listPane.add(spinner);
Object[] array = {
new JLabel("Enter a new category:"),
listPane
};
JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = pane.createDialog(listPane, "Enter a new category:");
dialog.setVisible(true);
}
});
}
}
But JTextField is filled by the example String. And I need empty JTextField with this width
Just use constructor which specifies desired colums Count:
JTextField inputCat = new JTextField(example.length());

Categories

Resources