How do I highlight specific Label when selected from the comboBox? - java

So I have a database of users in my JComboBox and on the left side is a list of these users as well. What I want to do is write a program when this user is selected from the JComboBox, highlight him in the list(JLabel) on the left side. I hope I was specific enough.

public class Test2 extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel panel;
private JComboBox<String> comboBox;
private JList<String> list;
public Test2() {
panel = new JPanel();
getContentPane().add(panel, BorderLayout.NORTH);
GridBagLayout gbl_panel = new GridBagLayout();
panel.setLayout(gbl_panel);
comboBox = new JComboBox<String>();
comboBox.addItem("User1");
comboBox.addItem("User2");
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.weightx = 1.0;
gbc_comboBox.insets = new Insets(0, 0, 5, 0);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 0;
gbc_comboBox.gridy = 0;
panel.add(comboBox, gbc_comboBox);
DefaultListModel<String> listModel = new DefaultListModel<>();
listModel.addElement("User1");
listModel.addElement("User2");
list = new JList<String>(listModel);
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.weightx = 1.0;
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 0;
panel.add(list, gbc_lblNewLabel);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedItem = String.valueOf(comboBox.getSelectedItem());
if (selectedItem.equals("User1"))
list.setSelectedValue("User1", true);
else if (selectedItem.equals("User2"))
list.setSelectedValue("User2", true);
}
});
}
public static void main(String[] args) {
Test2 myFrame = new Test2();
myFrame.setVisible(true);
myFrame.setSize(new Dimension(400, 500));
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Will this work for you?. I don't know why you are using JLabel inside JList. So i have changed the list from JList<JLabel> to JList<String>

Related

How do you get the gui to restart? (JAVA)

For instance, I want the program to run multiple times without stopping after somebody has pressed the "Please hit to finish process". However, when I do run the GUI method again, only the first panel shows up. Unsure of why this is happening.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
public class Hotel {
public static JFrame frame;
public static JPanel pan;
public static JPanel endPanel;
public static JPanel buttonPanel;
public static GridBagConstraints c;
public static GridBagConstraints f;
public static JButton econ;
public static Boolean openA = true;
public Hotel(){
Frame();
GUI();
}
public static void Frame(){
frame = new JFrame ("Kiosk");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(600,400);
}
public static void GUI (){
pan = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
frame.add(pan);
JLabel l2 = new JLabel("Please fill out your name and room number");
l2.setVisible(false);
pan.add(l2);
buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints GB = new GridBagConstraints();
JButton b1 = new JButton("Check in?");
c.gridx=0;
c.gridy=0;
c.insets = new Insets(10,10,10,10);
buttonPanel.add(b1, c);
JButton b2 = new JButton("Check out?");
c.gridx=1;
c.gridy=0;
c.insets = new Insets(10,10,10,10);
buttonPanel.add(b2, c);
frame.add(buttonPanel);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
buttonPanel.setVisible(false);
Checkin();
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
l2.setVisible(true);
b1.setVisible(false);
b2.setVisible(false);
}
});
}
public static void Checkin(){
JLabel name = new JLabel("What is your name?");
c.gridx=0;
c.gridy=0;
pan.add(name,c);
JLabel number = new JLabel("How many people in your party?");
c.gridx=0;
c.gridy=3;
pan.add(number,c);
JTextField namefield = new JTextField(20);
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=0;
pan.add(namefield,c);
JTextField numberfield = new JTextField(2);
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=3;
pan.add(numberfield,c);
JButton confirm = new JButton("Confirm");
c.insets = new Insets(10,10,10,10);
c.gridx=1;
c.gridy=4;
pan.add(confirm,c);
JPanel errorPanel = new JPanel(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
errorPanel.setVisible(false);
frame.add(errorPanel);
JButton econ = new JButton("Confirm");
d.insets = new Insets(10,10,10,10);
d.gridx=1;
d.gridy=4;
errorPanel.add(econ,d);
JLabel error = new JLabel("Sorry you must fill in all the fields");
d.insets = new Insets(10,10,10,10);
d.gridx=1;
d.gridy=0;
errorPanel.add(error,d);
confirm.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if((namefield.getText().equals("")) ||
(numberfield.getText().equals(""))){
pan.setVisible(false);
errorPanel.setVisible(true);
econ.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
errorPanel.setVisible(false);
pan.setVisible(true);
}
});
}
else{
endPanel = new JPanel(new GridBagLayout());
f = new GridBagConstraints();
pan.setVisible(false);
frame.add(endPanel);
String hey = namefield.getText();
Memory(hey);
int people =0;
try {
people = Integer.parseInt(numberfield.getText());
}
catch(NumberFormatException ex)
{
System.out.println("Exception : "+ex);
}
Rooms(people);
}
}
});
}
public static void Memory(String h){
ArrayList<String> Guest = new ArrayList<String>();
for(int x=0;x<Guest.size();x++){
if(Guest.get(x).equals(h)){
JLabel duplicate = new JLabel("Duplicate Name - Please refer
to the manager " + h);
JPanel dupPanel = new JPanel();
pan.setVisible(false);
dupPanel.setVisible(true);
frame.add(dupPanel);
econ.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dupPanel.setVisible(false);
pan.setVisible(true);
}
});
}
else{
JLabel nameLab = new JLabel("Have a nice day " + h);
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=0;
endPanel.add(nameLab);
}
Guest.add(h);
}
}
public static void Rooms(Integer n){
JLabel roomLab = new JLabel("Sorry there are no rooms with that
occupany available");
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=0;
endPanel.add(roomLab,f);
JButton restart = new JButton("Please hit to finish process");
f.insets = new Insets(10,10,10,10);
f.gridx = 0;
f.gridy=4;
endPanel.add(restart,f);
int x=0;
if(openA == true && n<2){
openA = false;
x=1;
}
switch(x){
case 1 : roomLab.setText("You have been assigned room A");
}
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
endPanel.setVisible(false);
GUI();
}
});
}
public static void main(String[] args) {
new Hotel();
}
}
If you want to cleanly restart a GUI, and make sure that the new GUI is 100% independent from the previous one, the best way is to dispose of the previous one, and create a brand new instance.
The biggest problem in your case is that all your fields and methods are static. This is wrong. You should typically have something like:
public class Hotel extends JFrame {
public JPanel pan;
...
public Hotel() {
super("Kiosk");
createGUI();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setSize(600,400);
}
public void createGUI(){
pan = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
add(pan);
...
If you want to restart the GUI, it's then very simple:
restart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
new Hotel();
}
});
If you just want to reset a particular panel within the frame, you can remove it from its container, and add a new instance:
somepanel.remove(somesubpanel);
somepanel.add(createSubpanel());

What is the difference between setSize(), setMaximumSize(),setMinimumSize() when used with GridbagLayout

What is the difference between setSize(), setMaximumSize(),setMinimumSize() when used with GridbagLayout. When I am using setMaximumSize(), it is reducing the height of the panel.If needed I can put SSCCE
Please find the SSCCE:
public class EditUserPanel extends JPanel {
private static final long serialVersionUID = 1L;
private JLabel st_REQ_FIELDS = null;
private JCheckBox ck_ISMANAGER = null;
private JCheckBox ck_ISBPM = null;
private JComboBox cb_LANGUAGE = null;
private JList lb_TEAMS = null;
private JList lb_COUNTRY = null;
private JList lb_BRANDPM = null;
private JTextField ef_NAME = null;
private JTextField ef_USERID = null;
private JScrollPane scr_TEAMS = null;
private JScrollPane scr_COUNTRY = null;
private JScrollPane scr_BRANDPM = null;
private JPanel teamButtonPanel = null;
private JPanel countryButtonPanel = null;
private JPanel brandButtonPanel = null;
private JButton pb_ADD_TEAM = null;
private JButton pb_REMOVE_TEAM = null;
private JButton pb_ADD_COUNTRY = null;
private JButton pb_REMOVE_COUNTRY = null;
private JButton pb_ADD_BRAND = null;
private JButton pb_REMOVE_BRAND = null;
private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
public EditUserPanel() {
initialize();
}
public void initialize() {
ck_ISMANAGER = new JCheckBox("Is a Manager");
ck_ISBPM = new JCheckBox("Brand Program Manager");
cb_LANGUAGE = new JComboBox();
lb_TEAMS = new JList();
lb_COUNTRY = new JList();
lb_BRANDPM = new JList();
ef_NAME = new JTextField();
ef_USERID = new JTextField();
scr_TEAMS = new JScrollPane(lb_TEAMS);
scr_COUNTRY = new JScrollPane(lb_COUNTRY);
scr_BRANDPM = new JScrollPane(lb_BRANDPM);
JPanel contentPane = new JPanel();
pb_ADD_TEAM = new JButton("Add Team");
pb_REMOVE_TEAM = new JButton("Remove Team");
pb_ADD_COUNTRY = new JButton("Add Country");
pb_REMOVE_COUNTRY = new JButton("Remove Country");
pb_ADD_BRAND = new JButton("Add Brand");
pb_REMOVE_BRAND = new JButton("Remove Brand");
st_REQ_FIELDS = new JLabel("* = These fields are required");
st_REQ_FIELDS.setForeground(Color.red);
setLayout(new BorderLayout());
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.LINE_AXIS));
contentPane.add(addBasicElements());
add(st_REQ_FIELDS,BorderLayout.PAGE_START);
add(contentPane, BorderLayout.CENTER);
}
private Component addBasicElements() {
// TODO Auto-generated method stub
JPanel basicPanel = new JPanel();
basicPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc= new GridBagConstraints();
gbc=createGbc(0, 0); basicPanel.add(addFormPanel(new JPanel(), new JLabel("* Name : "),ef_NAME),gbc);
gbc=createGbc(1, 0); basicPanel.add(addFormPanel(new JPanel(), new JLabel("* UserID : "), ef_USERID),gbc);
gbc=createGbc(0, 1); basicPanel.add(addFormPanel(new JPanel(), new JLabel("* Language : "), cb_LANGUAGE),gbc);
gbc=createGbc(1, 1); basicPanel.add(addFormPanel(new JPanel(), new JLabel(" "),ck_ISMANAGER),gbc);
gbc=createGbc(0, 2); basicPanel.add(addFormPanel(new JPanel(),new JLabel("Brand Manager : "),(JPanel)addBrandManagerPanel()),gbc);
gbc=createGbc(1, 2); basicPanel.add(addFormPanel(new JPanel(),new JLabel("* Country : "),(JPanel)addCountryPanel()),gbc);
gbc=createGbc(0, 3); basicPanel.add(addFormPanel(new JPanel(), new JLabel("* Team : "), (JPanel)addTeamPanel()),gbc);
basicPanel.setSize(new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2,
(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()));
basicPanel.setBorder(BorderFactory.createEtchedBorder());
return basicPanel;
}
private GridBagConstraints createGbc(int x, int y) {
// TODO Auto-generated method stub
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = 1; gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
private Component addFormPanel(JComponent jPanel, JComponent label,
JComponent textField) {
// TODO Auto-generated method stub
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.X_AXIS));
jPanel.add(label);
jPanel.add(textField);
// jPanel.setBorder(BorderFactory.createEtchedBorder());
return jPanel;
}
private Component addTeamPanel() {
// TODO Auto-generated method stub
JPanel teamPanel = new JPanel();
teamPanel.setLayout(new BoxLayout(teamPanel, BoxLayout.Y_AXIS));
teamPanel.add(scr_TEAMS);
teamPanel.add(addTeamButtonPanel());
return teamPanel;
}
private Component addTeamButtonPanel() {
// TODO Auto-generated method stub
teamButtonPanel = new JPanel();
teamButtonPanel.setLayout(new BoxLayout(teamButtonPanel,BoxLayout.X_AXIS));
teamButtonPanel.add(pb_ADD_TEAM);
teamButtonPanel.add(pb_REMOVE_TEAM);
return teamButtonPanel;
}
private Component addCountryPanel() {
// TODO Auto-generated method stub
JPanel countryPanel = new JPanel();
countryPanel.setLayout(new BoxLayout(countryPanel, BoxLayout.Y_AXIS));
countryPanel.add(scr_COUNTRY);
countryPanel.add(addCountryButtonPanel());
return countryPanel;
}
private Component addCountryButtonPanel() {
// TODO Auto-generated method stub
countryButtonPanel = new JPanel();
countryButtonPanel.setLayout(new BoxLayout(countryButtonPanel,BoxLayout.X_AXIS));
countryButtonPanel.add(pb_ADD_COUNTRY);
countryButtonPanel.add(pb_REMOVE_COUNTRY);
return countryButtonPanel;
}
private Component addBrandManagerPanel() {
// TODO Auto-generated method stub
JPanel brandmanagerPanel = new JPanel();
brandmanagerPanel.setLayout(new BoxLayout(brandmanagerPanel, BoxLayout.Y_AXIS));
brandmanagerPanel.add(scr_BRANDPM);
brandmanagerPanel.add(addBrandButtonPanel());
return brandmanagerPanel;
}
private Component addBrandButtonPanel() {
// TODO Auto-generated method stub
brandButtonPanel = new JPanel();
brandButtonPanel.setLayout(new BoxLayout(brandButtonPanel,BoxLayout.X_AXIS));
brandButtonPanel.add(ck_ISBPM);
brandButtonPanel.add(pb_ADD_BRAND);
brandButtonPanel.add(pb_REMOVE_BRAND);
return brandButtonPanel;
}
public static void main(String[] args){
EditUserPanel panel = new EditUserPanel();
JFrame frame = new JFrame("SSCCE for stack overflow");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setSize(new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),
(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()));
frame.setVisible(true);
}
} /* EditUserPanel */
I have removed all the unused field. Please also find the image when use setSize() and setMaximumSize() with the panel at this line
basicPanel.setSize(new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2,
(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()));
basicPanel.setBorder(BorderFactory.createEtchedBorder());
return basicPanel;
Result with setSize():
Result with setMaximumSize():
Question:
1.How to display them nicely because I am not able to achieve it either with setSize() or setMaximumSize()
More Information:
I can use pack() on JFrame to make it correct in this above but in my actual code this panel is appearing inside other panel and so far I could not find the place to use pack. If there is anything equivalent to pack for JPanel I would be happy to use that.
With setSize() you define the size of your grid. With setMaximumSize() you tell the grid that if the user enlarges his window, the grid won't increase more than the given size. With setMinimumSize(), it is the equivalent for shrinking the window.

Why does GridBagLayout provide strange result?

I want the various components to spread out and fill the entire window.
Have you tried anything else? Yes, I tried GridLayout but then the buttons look huge. I also tried pack() which made the window small instead. The window should be 750x750 :)
What I was trying is this:
These 4 buttons on the top as a thin strip
The scroll pane with JPanels inside which will contain all the video conversion tasks. This takes up the maximum space
A JPanel at the bottom containing a JProgressBar as a thin strip.
But something seems to have messed up somewhere. Please help me solve this
SSCCE
import java.awt.*;
import javax.swing.*;
import com.explodingpixels.macwidgets.*;
public class HudTest {
public static void main(String[] args) {
HudWindow hud = new HudWindow("Window");
hud.getJDialog().setSize(750, 750);
hud.getJDialog().setLocationRelativeTo(null);
hud.getJDialog().setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addVideo = HudWidgetFactory.createHudButton("Add New Video");
JButton removeVideo = HudWidgetFactory.createHudButton("Remove Video");
JButton startAll = HudWidgetFactory.createHudButton("Start All Tasks");
JButton stopAll = HudWidgetFactory.createHudButton("Stop All Tasks");
buttonPanel.add(addVideo);
buttonPanel.add(startAll);
buttonPanel.add(removeVideo);
buttonPanel.add(stopAll);
JPanel taskPanel = new JPanel(new GridLayout(0,1));
JScrollPane taskScrollPane = new JScrollPane(taskPanel);
IAppWidgetFactory.makeIAppScrollPane(taskScrollPane);
for(int i=0;i<10;i++){
ColorPanel c = new ColorPanel();
c.setPreferredSize(new Dimension(750,100));
taskPanel.add(c);
}
JPanel progressBarPanel = new JPanel();
JComponent component = (JComponent) hud.getContentPane();
component.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Insets in = new Insets(2,2,2,2);
gbc.insets = in;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
component.add(buttonPanel,gbc);
gbc.gridy += 1;
gbc.gridheight = 17;
component.add(taskScrollPane,gbc);
gbc.gridy += 17;
gbc.gridheight = 2;
component.add(progressBarPanel,gbc);
hud.getJDialog().setVisible(true);
}
}
Use this
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridbagConstraints.BOTH
Why not simply place three JPanels on top of one JPanel with BorderLayout as Layout Manager, where the middle JPanel with all custom panels with their respective sizes can be accommodated inside a JScrollPane, as shown in the below example :
import javax.swing.*;
import java.awt.*;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 5/17/13
* Time: 6:09 PM
* To change this template use File | Settings | File Templates.
*/
public class PlayerBase
{
private JPanel contentPane;
private JPanel buttonPanel;
private JPanel centerPanel;
private CustomPanel[] colourPanel;
private JPanel progressPanel;
private JButton addVideoButton;
private JButton removeVideoButton;
private JButton startAllButton;
private JButton stopAllButton;
private JProgressBar progressBar;
private Random random;
public PlayerBase()
{
colourPanel = new CustomPanel[10];
random = new Random();
}
private void displayGUI()
{
JFrame playerWindow = new JFrame("Player Window");
playerWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
addVideoButton = new JButton("Add New Video");
removeVideoButton = new JButton("Remove Video");
startAllButton = new JButton("Start all tasks");
stopAllButton = new JButton("Stop all tasks");
buttonPanel.add(addVideoButton);
buttonPanel.add(removeVideoButton);
buttonPanel.add(startAllButton);
buttonPanel.add(stopAllButton);
contentPane.add(buttonPanel, BorderLayout.PAGE_START);
JScrollPane scroller = new JScrollPane();
centerPanel = new JPanel(new GridLayout(0, 1, 2, 2));
for (int i = 0; i < colourPanel.length; i++)
{
colourPanel[i] = new CustomPanel(new Color(
random.nextInt(255), random.nextInt(255)
, random.nextInt(255)));
centerPanel.add(colourPanel[i]);
}
scroller.setViewportView(centerPanel);
contentPane.add(scroller, BorderLayout.CENTER);
progressPanel = new JPanel(new BorderLayout(5, 5));
progressBar = new JProgressBar(SwingConstants.HORIZONTAL);
progressPanel.add(progressBar);
contentPane.add(progressPanel, BorderLayout.PAGE_END);
playerWindow.setContentPane(contentPane);
playerWindow.pack();
//playerWindow.setSize(750, 750);
playerWindow.setLocationByPlatform(true);
playerWindow.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new PlayerBase().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
public CustomPanel(Color backGroundColour)
{
setOpaque(true);
setBackground(backGroundColour);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(750, 100));
}
}
OUTPUT :

Remove method does not work for custom UI widget

I've put together a small UI widget, but the remove button on it does not work. Whenever I click on it nothing happens. Any ideas?
public class ComboBoxProblem extends JFrame {
static JLabel citiesLabel = new JLabel();
static JList citiesList = new JList();
static JScrollPane citiesScrollPane = new JScrollPane();
static JButton remove = new JButton();
public static void main(String[] args) {
new ComboBoxProblem().show();
}
public ComboBoxProblem() {
// create frame
setTitle("Flight Planner");
setResizable(false);
getContentPane().setLayout(new GridBagLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints gridConstraints;
citiesLabel.setText("Destination City");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(citiesLabel, gridConstraints);
citiesScrollPane.setPreferredSize(new Dimension(150, 100));
citiesScrollPane.setViewportView(citiesList);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 10, 10);
getContentPane().add(citiesScrollPane, gridConstraints);
// Here is my list with my elements, that I want to remove
final DefaultListModel Model = new DefaultListModel();
Model.addElement("San Diego");
Model.addElement("Los Angeles");
Model.addElement("Orange County");
Model.addElement("Ontario");
Model.addElement("Bakersfield");
Model.addElement("Oakland");
Model.addElement("Sacramento");
Model.addElement("San Jose");
citiesList.setModel(Model);
final JList list = new JList(Model);
remove.setText("Remove");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 3;
getContentPane().add(remove, gridConstraints);
// Here is my removing method, I don't know, where the problem is
// and it is showing no error
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int sel = list.getSelectedIndex();
if (sel >= 0) {
Model.removeElementAt(sel);
}
}
});
pack();
}
}
Replace this line :
int sel = list.getSelectedIndex();
By this one:
int sel = citiesList.getSelectedIndex();
list.getSelectedIndex() was always returning -1.
Please use debug in the future in order to get more information about what is going on in your code.

Multi-colored lists

I have to create 5 Jlists in succession to make their backgrounds look in different colors. My existing code creates these 5 lists without the colors (the default JList). I understand that I can only customize the inside/border of a jlist and not the margin/padding around it? Or Am I wrong and is there a way to it?
Btw, The space above the list is a Jlabel (not shown in the pic above) and the layout managers in use are GroupLayout and GridBagLayout.
UPDATE
AT, as per your suggestion, here is a comparison to how the lists look like when surrounded by a jpanel. The lists in the back are the ones with the Jpanel surrounded with a minimal empty border of size 1.
The issue with creating a JPanel with preferredsize overridden is that the jlists are in horizontal jpanel and above them is another jpanel with labels. So, wrapping jlist in a jpanel is not going to do it.
Please do have a look at this code example. Is it closer to what you wanted, else you define the changes that needs to be done. I be on them as soon as I get the reply from your side :-)
Here is the outcome :
import java.awt.*;
import javax.swing.*;
public class JListExample
{
private JList<String> list1;
private JList<String> list2;
private JList<String> list3;
private JList<String> list4;
private JList<String> list5;
private CustomPanel panel1;
private CustomPanel panel2;
private CustomPanel panel3;
private CustomPanel panel4;
private CustomPanel panel5;
private String[] data = {"one", "two", "three", "four"};
private int width = 110;
private int height = 300;
private void displayGUI()
{
JFrame frame = new JFrame("JList Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 5, 2, 2));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
panel1 = new CustomPanel(width, height, Color.GRAY, "List 1");
list1 = new JList<String>(data);
panel1.add(list1, gbc);
panel2 = new CustomPanel(width, height,
Color.GREEN.brighter().brighter(), "List 2");
list2 = new JList<String>(data);
panel2.add(list2, gbc);
panel3 = new CustomPanel(width, height,
Color.ORANGE.brighter(), "List 3");
list3 = new JList<String>(data);
panel3.add(list3, gbc);
panel4 = new CustomPanel(width, height,
Color.BLUE.brighter(), "List 4");
list4 = new JList<String>(data);
panel4.add(list4, gbc);
panel5 = new CustomPanel(width, height, Color.RED, "List 5");
list5 = new JList<String>(data);
panel5.add(list5, gbc);
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
contentPane.add(panel4);
contentPane.add(panel5);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JListExample().displayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
private final int GAP = 5;
private int width;
private int height;
private Color backgroundColour;
private JLabel titleLabel;
public CustomPanel(int w, int h, Color c, String title)
{
width = w;
height = h;
backgroundColour = c;
titleLabel = new JLabel(title, JLabel.CENTER);
setBackground(backgroundColour);
setBorder(
BorderFactory.createEmptyBorder(
GAP, GAP, GAP, GAP));
setLayout(new GridBagLayout());
titleLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 0.1;
add(titleLabel, gbc);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(width, height));
}
}
**LATEST EDIT : **
As rightly pointed by #kleopatra (not something that is new for me :-)), too good judgement call. Done the edit related to that below :
import java.awt.*;
import javax.swing.*;
public class JListExample
{
private final int GAP = 5;
private JList<String> list1;
private JList<String> list2;
private JList<String> list3;
private JList<String> list4;
private JList<String> list5;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
private JPanel panel4;
private JPanel panel5;
private String[] data = {"one", "two", "three", "four"};
private int width = 110;
private int height = 300;
private GridBagConstraints gbc = new GridBagConstraints();
private void displayGUI()
{
JFrame frame = new JFrame("JList Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 5, 2, 2));
panel1 = getPanel(Color.GRAY, "List 1");
list1 = new JList<String>(data);
panel2 = getPanel(Color.GREEN.brighter().brighter(), "List 2");
list2 = new JList<String>(data);
panel3 = getPanel(Color.ORANGE.brighter(), "List 3");
list3 = new JList<String>(data);
panel4 = getPanel(Color.BLUE.brighter(), "List 4");
list4 = new JList<String>(data);
panel5 = getPanel(Color.RED, "List 5");
list5 = new JList<String>(data);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
panel1.add(list1, gbc);
panel2.add(list2, gbc);
panel3.add(list3, gbc);
panel4.add(list4, gbc);
panel5.add(list5, gbc);
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
contentPane.add(panel4);
contentPane.add(panel5);
frame.setContentPane(contentPane);
frame.setSize(610, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getPanel(Color c, String title)
{
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBorder(
BorderFactory.createEmptyBorder(
GAP, GAP, GAP, GAP));
panel.setBackground(c);
panel.setLayout(new GridBagLayout());
JLabel label = new JLabel(title, JLabel.CENTER);
label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 0.1;
panel.add(label, gbc);
return panel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JListExample().displayGUI();
}
});
}
}

Categories