Adding horizontal scroll bar in JComboBox not working - java

I am trying to add horizontal scroll bar in a JComboBox using reference with thread - Horizontal scrollbar for JComboBox across multiple look and feel at the OTN, but it's not working in my case.
How to add a horizontal scroll bar to JComboBox correctly?
Code -
public class TestJComboBoxWithScrollBar {
TestJComboBoxWithScrollBar() {
JDialog jDialog = new JDialog();
jDialog.setTitle("Test JComboBox With ScrollBar");
JPanel jPanel_Sort = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints bagConstraints = new GridBagConstraints();
jPanel_Sort.setLayout(gbl);
bagConstraints.gridwidth = 1;
bagConstraints.gridheight = 1;
bagConstraints.fill = GridBagConstraints.NONE;
bagConstraints.anchor = GridBagConstraints.WEST;
bagConstraints.weightx = 0;
bagConstraints.weighty = 0;
bagConstraints.insets = new Insets(5, 5, 5, 5);
bagConstraints.gridx = 0;
bagConstraints.gridy = 0;
SampleJComboBoxWithScrollBar cmbHeaders = new SampleJComboBoxWithScrollBar();
cmbHeaders.addItem("aaaaaaaaaaaaa");
cmbHeaders.addItem("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
cmbHeaders.setPreferredSize(new Dimension(190, 50));
cmbHeaders.setMinimumSize(new Dimension(190, 50));
cmbHeaders.setMaximumSize(new Dimension(190, 50));
jPanel_Sort.add(cmbHeaders, bagConstraints);
JCheckBox chkOrderBy = new JCheckBox("Asc");
bagConstraints.gridx = 1;
bagConstraints.gridy = 0;
jPanel_Sort.add(chkOrderBy, bagConstraints);
jPanel_Sort.setPreferredSize(new Dimension(220, 70));
jPanel_Sort.setMinimumSize(new Dimension(220, 70));
jPanel_Sort.setMaximumSize(new Dimension(220, 70));
jDialog.add(jPanel_Sort, BorderLayout.CENTER);
jDialog.setPreferredSize(new Dimension(300, 100));
jDialog.pack();
jDialog.setResizable(false);
jDialog.setModal(true);
jDialog.setVisible(true);
}
public static void main(String[] argu) {
new TestJComboBoxWithScrollBar();
}
class SampleJComboBoxWithScrollBar extends JComboBox {
SampleJComboBoxWithScrollBar() {
super();
this.addPopupMenuListener(this.getPopupMenuListener());
this.adjustScrollBar();
}
private void adjustPopupWidth() {
if (getItemCount() == 0) {
return;
}
Object comp = getUI().getAccessibleChild(this, 0);
if (!(comp instanceof JPopupMenu)) {
return;
}
JPopupMenu popup = (JPopupMenu) comp;
JScrollPane scrollPane = (JScrollPane) popup.getComponent(0);
Object value = getItemAt(0);
Component rendererComp = getRenderer().getListCellRendererComponent(new JList(), value, 0, false, false);
if (rendererComp instanceof JXTable) {
scrollPane.setColumnHeaderView(((JTable) rendererComp).getTableHeader());
}
Dimension prefSize = rendererComp.getPreferredSize();
Dimension size = scrollPane.getPreferredSize();
size.width = Math.max(size.width, prefSize.width);
scrollPane.setPreferredSize(size);
scrollPane.setMaximumSize(size);
scrollPane.revalidate();
}
private void adjustScrollBar() {
if (getItemCount() == 0) {
return;
}
Object comp = getUI().getAccessibleChild(this, 0);
if (!(comp instanceof JPopupMenu)) {
return;
}
JPopupMenu popup = (JPopupMenu) comp;
JScrollPane scrollPane = (JScrollPane) popup.getComponent(0);
scrollPane.setHorizontalScrollBar(new JScrollBar(JScrollBar.HORIZONTAL));
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
private PopupMenuListener getPopupMenuListener() {
return new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
adjustPopupWidth();
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
};
}
}
}

if you meaning code posted by #Kleopatra then void adjustScrollBar() never will be called from PopupMenuListener
private PopupMenuListener getPopupMenuListener() {
return new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
//adjustPopupWidth();
adjustScrollBar();
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
};
}

Related

JPanel is SOMETIMES not responding to mouse clicks

I have some custom JPanels that are used as buttons. This works well 90% of the time, however, sometimes the GUI doesn't respond to a mouse click - the mouseClicked event is not triggered and you have to click again (sometimes even more than once) to actually trigger it.
This behavior appears to be random, though I have the feeling that it occurs more frequently after having moved the frame to another monitor.
Here is the code:
public class EatingMouse extends JFrame implements MouseListener {
JPanel contentPane;
int contentPanelWidth, contentPanelHeight;
int mainTabMarginHeight, mainTabMarginWidth;
int subTabMarginHeight, subTabMarginWidth;
Color fontColor = Color.WHITE;
Color tabBackgroundColor = Color.BLACK;
Color tabBackgroundHighlightColor = Color.GRAY;
Color tabBackgroundSelectedColor = Color.LIGHT_GRAY;
TabPanel firstMainTab;
TabPanel secondMainTab;
ArrayList<TabPanel> firstSubTabs;
ArrayList<TabPanel> secondSubTabs;
ArrayList<TabPanel> currentSubTabs;
int clickCounter;
public EatingMouse() {
super("Why do you eat mouse clicks?");
JLayeredPane layeredPane = new JLayeredPane();
firstMainTab = new TabPanel("First Tab", 18);
firstMainTab.addMouseListener(this);
layeredPane.add(firstMainTab, new Integer(100));
secondMainTab = new TabPanel("Second Tab", 18);
secondMainTab.addMouseListener(this);
layeredPane.add(secondMainTab, new Integer(100));
firstSubTabs = new ArrayList<>();
secondSubTabs = new ArrayList<>();
currentSubTabs = new ArrayList<>();
TabPanel tp = new TabPanel("First First Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
firstSubTabs.add(tp);
tp = new TabPanel("Second First Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
firstSubTabs.add(tp);
tp = new TabPanel("First Second Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
secondSubTabs.add(tp);
tp = new TabPanel("Second Second Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
secondSubTabs.add(tp);
contentPane = new JPanel(new BorderLayout());
setContentPane(contentPane);
contentPane.add(layeredPane);
mainTabMarginWidth = 40;
mainTabMarginHeight = 8;
subTabMarginWidth = 20;
subTabMarginHeight = 10;
selectTabs(0, 1);
clickCounter = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(800, 600));
setVisible(true);
}
public void selectTabs(int mainTab, int subTab) {
boolean hasChanged = false;
if((mainTab == 0) && !firstMainTab.isSelected) {
hasChanged = true;
firstMainTab.setSelected(true);
secondMainTab.setSelected(false);
for(TabPanel tp : currentSubTabs) {
tp.setSelected(false);
tp.setVisible(false);
}
currentSubTabs = firstSubTabs;
for(TabPanel tp : currentSubTabs) {
tp.setVisible(true);
}
currentSubTabs.get(subTab).setSelected(true);
}
else if((mainTab == 1) && !secondMainTab.isSelected) {
hasChanged = true;
firstMainTab.setSelected(false);
secondMainTab.setSelected(true);
for(TabPanel tp : currentSubTabs) {
tp.setSelected(false);
tp.setVisible(false);
}
currentSubTabs = secondSubTabs;
for(TabPanel tp : currentSubTabs) {
tp.setVisible(true);
}
currentSubTabs.get(subTab).setSelected(true);
}
else if((mainTab == 0) && firstMainTab.isSelected) {
hasChanged = true;
for(TabPanel tp : currentSubTabs) {
if(tp != currentSubTabs.get(subTab)) { tp.setSelected(false); }
else { tp.setSelected(true); }
}
}
else if((mainTab == 1) && secondMainTab.isSelected) {
hasChanged = true;
for(TabPanel tp : currentSubTabs) {
if(tp != currentSubTabs.get(subTab)) { tp.setSelected(false); }
else { tp.setSelected(true); }
}
}
if(hasChanged) {
revalidate();
repaint();
}
}
#Override
public void paint(Graphics graphics) {
super.paint(graphics);
contentPanelWidth = getContentPane().getWidth();
contentPanelHeight = getContentPane().getHeight();
int xOffset = 100;
int yOffset = 100;
FontMetrics mainTabMetrics = graphics.getFontMetrics(firstMainTab.label.getFont());
firstMainTab.setBounds(xOffset, yOffset, (mainTabMetrics.stringWidth(firstMainTab.text) + mainTabMarginWidth), (mainTabMetrics.getHeight() + mainTabMarginHeight));
xOffset += firstMainTab.getBounds().width;
secondMainTab.setBounds(xOffset, yOffset, (mainTabMetrics.stringWidth(secondMainTab.text) + mainTabMarginWidth), (mainTabMetrics.getHeight() + mainTabMarginHeight));
FontMetrics subTabMetrics = graphics.getFontMetrics(currentSubTabs.get(0).label.getFont());
xOffset = 100;
yOffset += firstMainTab.getBounds().height;
for(TabPanel tp : currentSubTabs) {
tp.setBounds(xOffset, yOffset, (subTabMetrics.stringWidth(tp.text) + subTabMarginWidth), (subTabMetrics.getHeight() + subTabMarginHeight));
tp.revalidate();
tp.repaint();
xOffset += tp.getBounds().width;
}
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("click " + clickCounter++);
Object source = e.getSource();
if(source == firstMainTab && !firstMainTab.isSelected) {
secondMainTab.setSelected(false);
if(currentSubTabs.get(1).isSelected) { selectTabs(0, 1); }
else { selectTabs(0, 0); }
}
else if(source == secondMainTab && !secondMainTab.isSelected) {
if(currentSubTabs.get(1).isSelected) { selectTabs(1, 1); }
else { selectTabs(1, 0); }
}
}
#Override
public void mouseEntered(MouseEvent e) {
Object source = e.getSource();
if(source == firstMainTab && !firstMainTab.isSelected) { firstMainTab.setBackground(tabBackgroundHighlightColor); }
else if(source == secondMainTab && !secondMainTab.isSelected) { secondMainTab.setBackground(tabBackgroundHighlightColor); }
else if(currentSubTabs.contains(source) && !((TabPanel) source).isSelected) {
((TabPanel)source).setBackground(tabBackgroundHighlightColor);
}
}
#Override
public void mouseExited(MouseEvent e) {
Object source = e.getSource();
if(source == firstMainTab && !firstMainTab.isSelected) { firstMainTab.setBackground(tabBackgroundColor); }
else if(source == secondMainTab && !secondMainTab.isSelected) { secondMainTab.setBackground(tabBackgroundColor); }
else if(currentSubTabs.contains(source) && !((TabPanel) source).isSelected) {
((TabPanel)source).setBackground(tabBackgroundColor);
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
public class TabPanel extends JPanel {
JLabel label;
String text;
boolean isSelected;
public TabPanel(String labelText, int fontSize) {
super();
text = labelText;
isSelected = false;
setLayout(new GridBagLayout());
setBackground(tabBackgroundColor);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0.1;
gbc.weightx = 0.1;
gbc.insets = new Insets(0,0,0,0);
label = new JLabel("<html><div style=\"text-align:center\"> " + text + "</div></html>", SwingConstants.CENTER);
label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
label.setForeground(fontColor);
label.setFont(new Font("Arial", Font.BOLD, fontSize));
add(label, gbc);
}
public void setSelected(boolean selected) {
isSelected = selected;
if(selected) { setBackground(tabBackgroundSelectedColor); }
else { setBackground(tabBackgroundColor); }
}
public boolean isSelected() { return isSelected; }
#Override
public String toString() {
return text + " - " + label.getFont().getSize();
}
}
public static void main(String[] args) {
new EatingMouse();
}
}
Please note that I have chosen JPanels as buttons because I want to heavily customize them later, which I didn't get to work with extending JButton.
Thank you for your time reading this and of course I would appreciate any leads on why this is happening and what I can do to improve this code.

Changing LookAndFeel of JTable of Custom Component

I was changing the LookAndFeel of a JTable populated of Custom Class extended of JPanel , But I can't to do it.
I edited to simply my code, but still it's long.
public class LAF_TableCustomContainer extends JFrame {
public LAF_TableCustomContainer() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
setLocationRelativeTo(null);
}
public static void changeLAF(Container container, String laf) {
try {
UIManager.setLookAndFeel(laf);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
}
SwingUtilities.updateComponentTreeUI(container);
}
static final JFrame frame = new JFrame();
public JComponent makeUI() {
String[] hdrsObjects = {"PanelSpinnerRadioButton Class Column"};
Object[][] objectMatrix = new Object[3][1];
objectMatrix[0][0] = new PanelSpinnerRadioButtonData(false, 10, 40);
objectMatrix[1][0] = new PanelSpinnerRadioButtonData(true, 20, 40);
objectMatrix[2][0] = new PanelSpinnerRadioButtonData(false, 30, 40);
JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
table.setRowHeight(30);
TableColumn tc = table.getColumn("PanelSpinnerRadioButton Class Column");
tc.setCellRenderer(new PSRBTableCellRenderer());
tc.setCellEditor(new PSRBTableCellEditor());
JPanel pH = new JPanel();
pH.setLayout(new BoxLayout(pH, BoxLayout.LINE_AXIS));
JButton bMetal = new JButton("Metal");
bMetal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(LAF_TableCustomContainer.this, "javax.swing.plaf.metal.MetalLookAndFeel");
changeLAF(table, "javax.swing.plaf.metal.MetalLookAndFeel");
changeLAF(scrollPane, "javax.swing.plaf.metal.MetalLookAndFeel");
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "javax.swing.plaf.metal.MetalLookAndFeel");
}
});
JButton bMotif = new JButton("Motif");
bMotif.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(LAF_TableCustomContainer.this, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
changeLAF(table, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
changeLAF(scrollPane, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
});
JButton bNimbus = new JButton("Nimbus");
bNimbus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(LAF_TableCustomContainer.this, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
changeLAF(table, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
changeLAF(scrollPane, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
});
pH.add(bMetal);
pH.add(bMotif);
pH.add(bNimbus);
JPanel pV = new JPanel();
pV.setLayout(new BoxLayout(pV, BoxLayout.PAGE_AXIS));
pV.add(pH);
pV.add(scrollPane);
return pV;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
LAF_TableCustomContainer f = new LAF_TableCustomContainer();
f.getContentPane().add(f.makeUI());
});
}
}
class PanelSpinnerRadioButtonData {
private boolean opt02 = false;
private Integer from = 0;
private Integer size = 1;
PanelSpinnerRadioButtonData() {
this(false, 5, 10);
}
PanelSpinnerRadioButtonData(boolean opt02, Integer from, Integer size) {
this.opt02 = opt02;
this.from = from;
this.size = size;
}
public boolean getOption() {
return opt02;
}
public Integer getFrom() {
return from;
}
public Integer getSize() {
return size;
}
}
class PanelSpinnerRadioButton extends JPanel {
public final JRadioButton jrbOption01 = new JRadioButton("01");
public final JRadioButton jrbOption02 = new JRadioButton("12");
public final JSpinner jspnValues = new JSpinner(new SpinnerNumberModel(5, 0, 10, 1));
private final JPanel panel = new JPanel();
PanelSpinnerRadioButton() {
this(new PanelSpinnerRadioButtonData(false, 20, 40));
}
PanelSpinnerRadioButton(PanelSpinnerRadioButtonData data) {
super();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(jrbOption01);
panel.add(jrbOption02);
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(new JSeparator(JSeparator.VERTICAL));
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(jspnValues);
ButtonGroup bg = new ButtonGroup();
bg.add(jrbOption01);
bg.add(jrbOption02);
((SpinnerNumberModel) jspnValues.getModel()).setMaximum(data.getSize());
setData(data);
init();
}
private void init() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
setBackground(new Color(0, 0, 0, 0));
add(panel);
}
public void setData(PanelSpinnerRadioButtonData data) {
if (data.getOption()) {
jrbOption02.setSelected(true);
} else {
jrbOption01.setSelected(true);
}
((SpinnerNumberModel) jspnValues.getModel()).setValue(data.getFrom());
}
// Used in PSRBTableCellEditor.getCellEditorValue()
public PanelSpinnerRadioButtonData getData() {
return new PanelSpinnerRadioButtonData(
jrbOption02.isSelected(),
(Integer) ((SpinnerNumberModel) jspnValues.getModel()).getValue(),
(Integer) ((SpinnerNumberModel) jspnValues.getModel()).getMaximum());
}
}
class PSRBTableCellRenderer implements TableCellRenderer {
private final PanelSpinnerRadioButton renderer = new PanelSpinnerRadioButton();
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
renderer.setData((PanelSpinnerRadioButtonData) value);
}
return renderer;
}
}
class PSRBTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private final PanelSpinnerRadioButton editor = new PanelSpinnerRadioButton();
#Override public Object getCellEditorValue() {
return editor.getData();
}
#Override public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
editor.setData((PanelSpinnerRadioButtonData) value);
}
return editor;
}
}
When I press some button all JFrame changes except the cells of JTable, containing my custom JPanel.
I tried forcing only the first cell...
changeLAF((JPanel)table.getModel().getValueAt(0, 0), "javax.swing.plaf.metal.MetalLookAndFeel");
But I got Exception:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: PanelSpinnerRadioButtonData cannot be cast to javax.swing.JPanel
The limitation of the SwingUtilities#updateComponentTreeUI(...) method is that the cell renderer LookAndFeel can not change
Since PSRBTableCellRenderer does not extends JComponent, it is not subject to LookAndFeel update in the SwingUtilities # updateComponentTreeUI (...) method
// #see javax/swing/SwingUtilities.java
public static void updateComponentTreeUI(Component c) {
updateComponentTreeUI0(c);
c.invalidate();
c.validate();
c.repaint();
}
private static void updateComponentTreeUI0(Component c) {
if (c instanceof JComponent) {
JComponent jc = (JComponent) c;
jc.updateUI();
JPopupMenu jpm =jc.getComponentPopupMenu();
if(jpm != null) {
updateComponentTreeUI(jpm);
}
}
Component[] children = null;
if (c instanceof JMenu) {
children = ((JMenu)c).getMenuComponents();
}
else if (c instanceof Container) {
children = ((Container)c).getComponents();
}
if (children != null) {
for (Component child : children) {
updateComponentTreeUI0(child);
}
}
}
You can avoid this by overriding the JTable#updateUI() method and recreating the cell renderer and editor.
JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects)) {
#Override public void updateUI() {
super.updateUI();
setRowHeight(30);
TableColumn tc = getColumn("PanelSpinnerRadioButton Class Column");
tc.setCellRenderer(new PSRBTableCellRenderer());
tc.setCellEditor(new PSRBTableCellEditor());
}
};
LAF_TableCustomContainer2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class LAF_TableCustomContainer2 extends JFrame {
public LAF_TableCustomContainer2() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(300, 300);
setVisible(true);
setLocationRelativeTo(null);
}
public static void changeLAF(Container container, String laf) {
try {
UIManager.setLookAndFeel(laf);
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
}
SwingUtilities.updateComponentTreeUI(container);
}
static final JFrame frame = new JFrame();
public JComponent makeUI() {
JPanel pV = new JPanel();
pV.setLayout(new BoxLayout(pV, BoxLayout.PAGE_AXIS));
String[] hdrsObjects = {"PanelSpinnerRadioButton Class Column"};
Object[][] objectMatrix = new Object[3][1];
objectMatrix[0][0] = new PanelSpinnerRadioButtonData(false, 10, 40);
objectMatrix[1][0] = new PanelSpinnerRadioButtonData(true, 20, 40);
objectMatrix[2][0] = new PanelSpinnerRadioButtonData(false, 30, 40);
JTable table = new JTable(new DefaultTableModel(objectMatrix, hdrsObjects)) {
#Override public void updateUI() {
super.updateUI();
setRowHeight(30);
TableColumn tc = getColumn("PanelSpinnerRadioButton Class Column");
tc.setCellRenderer(new PSRBTableCellRenderer());
tc.setCellEditor(new PSRBTableCellEditor());
}
};
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
// table.setRowHeight(30);
// TableColumn tc = table.getColumn("PanelSpinnerRadioButton Class Column");
// tc.setCellRenderer(new PSRBTableCellRenderer());
// tc.setCellEditor(new PSRBTableCellEditor());
JPanel pH = new JPanel();
pH.setLayout(new BoxLayout(pH, BoxLayout.LINE_AXIS));
JButton bMetal = new JButton("Metal");
bMetal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(pV, "javax.swing.plaf.metal.MetalLookAndFeel");
}
});
JButton bMotif = new JButton("Motif");
bMotif.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(pV, "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
});
JButton bNimbus = new JButton("Nimbus");
bNimbus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
changeLAF(pV, "javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
});
pH.add(bMetal);
pH.add(bMotif);
pH.add(bNimbus);
pV.add(pH);
pV.add(scrollPane);
return pV;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
LAF_TableCustomContainer2 f = new LAF_TableCustomContainer2();
f.getContentPane().add(f.makeUI());
});
}
}
class PanelSpinnerRadioButtonData {
private boolean opt02 = false;
private Integer from = 0;
private Integer size = 1;
PanelSpinnerRadioButtonData() {
this(false, 5, 10);
}
PanelSpinnerRadioButtonData(boolean opt02, Integer from, Integer size) {
this.opt02 = opt02;
this.from = from;
this.size = size;
}
public boolean getOption() {
return opt02;
}
public Integer getFrom() {
return from;
}
public Integer getSize() {
return size;
}
}
class PanelSpinnerRadioButton extends JPanel {
public final JRadioButton jrbOption01 = new JRadioButton("01");
public final JRadioButton jrbOption02 = new JRadioButton("12");
public final JSpinner jspnValues = new JSpinner(new SpinnerNumberModel(5, 0, 10, 1));
private final JPanel panel = new JPanel();
PanelSpinnerRadioButton() {
this(new PanelSpinnerRadioButtonData(false, 20, 40));
}
PanelSpinnerRadioButton(PanelSpinnerRadioButtonData data) {
super();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.add(jrbOption01);
panel.add(jrbOption02);
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(new JSeparator(JSeparator.VERTICAL));
panel.add(Box.createRigidArea(new Dimension(5, 0)));
panel.add(jspnValues);
ButtonGroup bg = new ButtonGroup();
bg.add(jrbOption01);
bg.add(jrbOption02);
((SpinnerNumberModel) jspnValues.getModel()).setMaximum(data.getSize());
setData(data);
init();
}
private void init() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
setBackground(new Color(0, 0, 0, 0));
add(panel);
}
public void setData(PanelSpinnerRadioButtonData data) {
if (data.getOption()) {
jrbOption02.setSelected(true);
} else {
jrbOption01.setSelected(true);
}
((SpinnerNumberModel) jspnValues.getModel()).setValue(data.getFrom());
}
// Used in PSRBTableCellEditor.getCellEditorValue()
public PanelSpinnerRadioButtonData getData() {
return new PanelSpinnerRadioButtonData(
jrbOption02.isSelected(),
(Integer)((SpinnerNumberModel) jspnValues.getModel()).getValue(),
(Integer)((SpinnerNumberModel) jspnValues.getModel()).getMaximum());
}
}
class PSRBTableCellRenderer implements TableCellRenderer {
private final PanelSpinnerRadioButton renderer = new PanelSpinnerRadioButton();
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
renderer.setData((PanelSpinnerRadioButtonData) value);
}
return renderer;
}
}
class PSRBTableCellEditor extends AbstractCellEditor implements TableCellEditor {
private final PanelSpinnerRadioButton editor = new PanelSpinnerRadioButton();
#Override public Object getCellEditorValue() {
return editor.getData();
}
#Override public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column) {
if (value instanceof PanelSpinnerRadioButtonData) {
editor.setData((PanelSpinnerRadioButtonData) value);
}
return editor;
}
}

Delete checkboxes in swings

i am doing one project related to swings in this i am facing one problem like some 5 check boxes are there in this if i delete two non immediate check boxes (or) single check box i am able to delete but if i delete two immediate check boxes i am not able to delete i.e i have check boxes like 1,2,3,4,5 if i delete 1 and 3 , 1 and 4 , or 3 and 5 etc... (or) 1,2,3 etc.. if i delete using this combination i am able to delete but if i delete 1 and 2 or 2 and 3 or
4 and 5 like immediate check boxes i am not able to delete i am new to swings i don't no what's happening wrong and where. when i am searching for the answer i found this link
Deleting check boxes
The same program i am using the different approach, Here i am creating my own custom classes here my program:
import java.awt.*;
import java.util.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class ListModels extends JDialog {
#SuppressWarnings("rawtypes")
private JList list;
private JPanel rightPanel;
JButton cancel = new JButton("Cancel");
JButton delbtn = new JButton("Delete");
public ListModels() {
createList();
createButtons();
initUI();
}
public ListModels(List<String> values) {
}
#SuppressWarnings({ "unchecked", "rawtypes" })
private void createList() {
myModel mModel = new myModel(new CheckListItem[] {
new CheckListItem("78"), new CheckListItem("79"),
new CheckListItem("80"), new CheckListItem("81"),
new CheckListItem("82") });
list = new JList(mModel);
list.setCellRenderer(new CheckListRenderer());
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
JList list = (JList) event.getSource();
// Get index of item clicked
int index = list.locationToIndex(event.getPoint());
CheckListItem item = (CheckListItem) list.getModel()
.getElementAt(index);
if (item.isSelected) {
System.out.println("i am selected ");
}
// Toggle selected state
item.setSelected(!item.isSelected());
// Repaint cell
list.repaint(list.getCellBounds(index, index));
}
});
}
private void createButtons() {
rightPanel = new JPanel();
// JButton cancel = new JButton("Cancel");
cancel.setMaximumSize(cancel.getMaximumSize());
// JButton delbtn = new JButton("Delete");
delbtn.setMaximumSize(cancel.getMaximumSize());
// Cancel button
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
// Cancel
delbtn.addActionListener(new ActionListener() {
#SuppressWarnings("rawtypes")
public void actionPerformed(ActionEvent event) {
// CheckListItem item = (CheckListItem)
// list.getModel().getElementAt(index);
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null,
"Are you sure you want to delete the selected map",
"Delete", dialogButton);
myModel mModel = (myModel) list.getModel();
ListModel currentModel = list.getModel();
for (int i = 0; i < mModel.getSize(); i++) {
CheckListItem item = (CheckListItem) mModel.getElementAt(i);
if(!item.isSelected)
{
System.out.println("i am in not selected item "+item);
}
else if (item.isSelected()) {
System.out.println("i am selected item "+item);
if (dialogResult == JOptionPane.YES_OPTION) {
// Location loc=(Location) mModel.getElementAt(i);
mModel.removeAt(i);
mModel.fireIntervalRemoved(this, i,mModel.getSize());
}
}
}
}
});
// JPanel buttonPane = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.LINE_AXIS));
rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 4, 4, 4));
rightPanel.add(Box.createHorizontalStrut(60));
rightPanel.add(delbtn);
rightPanel.add(Box.createRigidArea(new Dimension(10, 0)));
rightPanel.add(cancel);
}
private void initUI() {
// JScroll Panel
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(250, 80));
listScroller.setAlignmentX(LEFT_ALIGNMENT);
// Lay out the label and scroll pane from top to bottom.
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
// Add all to the panel
listPane.add(Box.createRigidArea(new Dimension(0, 5)));
listPane.add(listScroller);
listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// Lay out the buttons from left to right.
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPane.add(Box.createHorizontalStrut(60));
buttonPane.add(delbtn);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPane.add(cancel);
listPane.add(buttonPane);
// Put everything together, using the content pane's BorderLayout.
Container contentPane = getContentPane();
contentPane.add(listPane, BorderLayout.CENTER);
contentPane.add(buttonPane, BorderLayout.PAGE_END);
add(listPane);
add(listPane);
setTitle("Delete Map");
setSize(300, 250);
setLocationRelativeTo(null);
}
class CheckListItem {
private String label;
private boolean isSelected = false;
public CheckListItem(String label) {
this.label = label;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public String toString() {
return label;
}
}
#SuppressWarnings({ "rawtypes" })
class CheckListRenderer extends JCheckBox implements ListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean hasFocus) {
setEnabled(list.isEnabled());
setSelected(((CheckListItem) value).isSelected());
setFont(list.getFont());
setBackground(list.getBackground());
setForeground(list.getForeground());
setText(value.toString());
return this;
}
}
class myModel extends AbstractListModel<CheckListItem> {
private List<CheckListItem> items;
public myModel(CheckListItem[] items) {
super();
this.items = new ArrayList<ListModels.CheckListItem>();
for (CheckListItem item : items) {
this.items.add(item);
}
}
/*
* #Override protected void fireContentsChanged(Object Source, int
* index0, int index1) { super.fireContentsChanged(Source, index0,
* index1); }
*/
#Override
public CheckListItem getElementAt(int index) {
return items.get(index);
}
#Override
protected void fireIntervalRemoved(Object Source, int index0, int index1) {
// TODO Auto-generated method stub
super.fireIntervalRemoved(Source, index0, index1);
}
#Override
public int getSize() {
return items.size();
}
public void removeAt(int item) {
items.remove(item);
}
public void addAt(int index, CheckListItem item) {
items.set(index, item);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
List<String> values = new ArrayList<String>();
values.addAll(newList);
ListModels ex = new ListModels();
ex.setVisible(true);
}
});
}
}
Finally in this program i am loading the check boxes through my custom class directly giving numbers ,I want to call this class from my main method and pass the numbers through Array list or array. Any HELP IS WELCOME and THANKS.
for (int i = 0; i < mModel.getSize(); i++)
You need to start at the end of the list and work backwards:
for (int i = mModel.getSize() - 1; i >=0; i--)
because if you start at 0, all the rows will shift down by one when the row is removed.

Java JCombobox do not change the image in JPanel

I have a problem.
I have an element that would JPanel.
In this JPanel would be four JButtons and image.
This image is 'green LED lights' that would change depending on which JButton would be pressed.
It works very well.
But also I want the JComboBox to change this paramter.
And here's the problem.
Although the parameter (from 1 to 4) is changing,(this shows JLabel near LEDs),
but the picture (LED lights) do not want to change it to the right one.
screenshot
The program is divided into 3 classes.
MyFrame.class This main class.
public class MyFrame extends JFrame {
int ctrlTriggers = 1;
private JLabel label = new JLabel();
private Triggers triggers;
private String[] typeTrig = {"1", "2", "3", "4"};
public MyFrame() {
JFrame frame = new JFrame("JComboBox Problem");
frame.setBounds(50, 0, 800, 240);
frame.setLayout(new BorderLayout());
int tvalue = 1;
String tstr = Integer.toString(tvalue);
JPanel panelTrig = new JPanel(new BorderLayout());
label = new JLabel(tstr, 4);
panelTrig.add(label);
final JLabel et = label;
triggers = new Triggers(typeTrig, "trigger " + Integer.toString(1));
triggers.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Triggers tr = (Triggers) e.getSource();
int vol;
vol = (int) tr.getValue();
et.setText(Integer.toString(vol));
}
});
panelTrig.add(triggers, BorderLayout.LINE_START);
// JCOMBOBOX
JPanel pCombo = new JPanel();
pCombo.setLayout(new FlowLayout());
Presets combo = new Presets();
combo.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Presets presetcombo = (Presets) e.getSource();
int tval;
tval = (int) presetcombo.getValue(ctrlTriggers);
label.setText(Integer.toString(tval));
triggers.setValue(tval);
}
});
pCombo.add(combo, BorderLayout.CENTER);
frame.add(pCombo, BorderLayout.CENTER);
frame.add(panelTrig, BorderLayout.LINE_START);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.show();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyFrame();
}
});
}
}
Triggers.class This class is JPanel where is 4 JButton and 'LED like image'
public class Triggers extends JPanel
implements ActionListener, ItemListener {
public Triggers(String s[], String name) {
JPanel panel = new JPanel(new BorderLayout());
this.value = Integer.parseInt(s[selected]);
for (int i = 0; i < s.length; i++) {
ImageIcon cup = new ImageIcon();
button[i] = new JButton(z[i], cup);
button[i].setPreferredSize(new Dimension(70, 25));
Font font = button[i].getFont();
button[i].setFont(new Font(font.getFontName(), font.getStyle(), 10));
button[i].setActionCommand(s[i]);
if (i == selected) {
button[i].setSelected(true);
} else {
button[i].setSelected(false);
}
}
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < s.length; i++) {
group.add(button[i]);
button[i].addActionListener(this);
button[i].addItemListener(this);
}
diody = new JLabel(createImageIcon("/resources/diody/"
+ this.value
+ ".png"));
diody.setPreferredSize(new Dimension(20, 100));
JPanel triggs = new JPanel(new FlowLayout());
triggs.setPreferredSize(new Dimension(80, 120));
for (int i = 0; i < s.length; i++) {
triggs.add(button[i]);
}
panel.add(triggs, BorderLayout.LINE_START);
panel.add(diody, BorderLayout.LINE_END);
add(panel);
}
public void actionPerformed(ActionEvent e) {
cmd = e.getActionCommand();
diody.setIcon(createImageIcon("/resources/diody/"
+ cmd
+ ".png"));
if (cmd.equals("1")) {
setValue(1);
} else if (cmd.equals("2")) {
setValue(2);
} else if (cmd.equals("3")) {
setValue(3);
} else if (cmd.equals("4")) {
setValue(4);
}
}
public static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Triggers.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public int setController() {
return value;
}
public void setValue(int k) {
this.value = k;
cmd = Integer.toString(this.value);
repaint();
fireChangeEvent();
}
public int getValue() {
return this.value;
}
public void setSel(int k) {
selected = k;
repaint();
fireChangeEvent();
}
public void itemStateChanged(ItemEvent ie) {
String s = (String) ie.getItem();
}
public void addChangeListener(ChangeListener cl) {
listenerList.add(ChangeListener.class, cl);
}
public void removeChangeListener(ChangeListener cl) {
listenerList.remove(ChangeListener.class, cl);
}
protected void fireChangeEvent() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener) listeners[i + 1]).stateChanged(changeEvent);
}
}
}
private ChangeEvent changeEvent = null;
private EventListenerList listenerList = new EventListenerList();
private JLabel diody;
private int x = 1;
private int y = 4;
private JButton button[] = new JButton[y];
double border = 4;
double vborder = 1;
int controller[] = new int[4];
String z[] = {"1", "2", "3", "4"};
private int selected;
private int value;
private String cmd;
}
class Presets Here is JCombobox.
public class Presets extends JPanel
implements ActionListener {
private int value;
private int[] ctrlIdx = new int[27];
private int controller;
private ChangeEvent changeEvent = null;
private EventListenerList listenerList = new EventListenerList();
private JLabel label;
private String[][] presets = {
{"0", "3"},
{"1", "2"},
{"2", "3"},
{"3", "1"},
{"4", "4"},
{"5", "2"},};
String[] ctrlName = {"preset 1 (value 3)", "preset 2 (value 2)", "preset 3 (value 3)", "preset 4 (value 1)", "preset 5 (value 4)", "preset 5 (value 2)"};
public Presets() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setPreferredSize(new Dimension(600, 30));
JComboBox combolist = new JComboBox(ctrlName);
combolist.setSelectedIndex(2);
combolist.addActionListener(this);
combolist.setPreferredSize(new Dimension(300, 30));
label = new JLabel();
label.setFont(label.getFont().deriveFont(Font.ITALIC));
label.setHorizontalAlignment(JLabel.CENTER);
int indeks = combolist.getSelectedIndex();
updateLabel(ctrlName[combolist.getSelectedIndex()], indeks);
label.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
label.setPreferredSize(new Dimension(300, 30));
panel.add(combolist, "East");
add(panel);
setPreferredSize(new Dimension(600, 40));
}
public void setSelectedItem(int a) {
}
public void setValue(int c, int v) {
controller = c;
value = v;
ctrlIdx[controller] = value;
repaint();
fireChangeEvent();
}
public int getController() {
return controller;
}
public int getValue(int c) {
int w = (int) ctrlIdx[c];
return (int) w;
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String pres = (String) cb.getSelectedItem();
int indeks = cb.getSelectedIndex();
updateLabel(pres, indeks);
for (int i = 0; i < ctrlName.length; i++) {
for (int j = 0; j < 2; j++) {
setValue(j, Integer.parseInt(presets[indeks][j]));
}
}
}
protected void updateLabel(String name, int ii) {
label.setToolTipText("A drawing of a " + name.toLowerCase());
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Presets.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public void addChangeListener(ChangeListener cl) {
listenerList.add(ChangeListener.class, cl);
}
public void removeChangeListener(ChangeListener cl) {
listenerList.remove(ChangeListener.class, cl);
}
protected void fireChangeEvent() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener) listeners[i + 1]).stateChanged(changeEvent);
}
}
}
}
Could someone help me, what am I doing wrong?
Your image is only begin loaded in the actionPerformed method of your Triggers class, which means when you call setValue in response to the stateChanged event thrown by the Presets class, no new image is begin loaded.
Move your image loading logic so it is either in the setValue method or triggered by the setValue method

JList very slow adding first element

I'm adding a string to a JList with DefaultListModel and it takes seconds to appear. Sometimes, I may have to click on the JList to have the list appear.
I'm using Eclipse Indigo. When I set a breakpoint after adding the element to JList, execution is fast.
I searched the web and SO for JList slow and they all talk about adding many items to the list. I'm adding the first element to the list.
Here's my code fragments:
private DefaultListModel function_list_model = new DefaultListModel();
private JList list_functions = new JList(function_list_model);
//...
// Initialization code:
JPanel panel_function_list = new JPanel();
panel_function_list.setBounds(10, 53, 541, 220);
panel_functions.add(panel_function_list);
panel_function_list.setLayout(null);
JLabel lblFunctions = new JLabel("Functions");
lblFunctions.setHorizontalAlignment(SwingConstants.CENTER);
lblFunctions.setBounds(235, 11, 99, 14);
panel_function_list.add(lblFunctions);
list_functions.setBorder(new LineBorder(new Color(0, 0, 0)));
list_functions.setBounds(10, 42, 492, 177);
list_functions.setFont(new Font("Courier New", Font.PLAIN, 12));
list_functions.setPreferredSize(new Dimension(0, 150));
list_functions.setMinimumSize(new Dimension(32767, 100));
list_functions.setMaximumSize(new Dimension(32767, 100));
JScrollPane scrollPane_functions = new JScrollPane(list_functions);
scrollPane_functions.setBounds(10, 79, 541, 183);
panel_functions.add(scrollPane_functions);
// Code to add a string:
String burger = new String("burger");
function_list_model.addElement(burger);
I'm also using WindowBuilder with Eclipse.
So how do I improve the performance of JList?
if you want I can to generating new Item from Char[] and to call doClick() for JButton("Fire")
import java.awt.*;
import java.awt.event.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.*;
public class ListDemo extends JPanel implements ListSelectionListener {
private JList list;
private DefaultListModel listModel;
private static final String hireString = "Hire";
private static final String fireString = "Fire";
private JButton fireButton;
private JTextField employeeName;
private javax.swing.Timer timer = null;
private int delay = 3;
private int count = 0;
public ListDemo() {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.addListSelectionListener(this);
list.setVisibleRowCount(5);
JScrollPane listScrollPane = new JScrollPane(list);
JButton hireButton = new JButton(hireString);
HireListener hireListener = new HireListener(hireButton);
hireButton.setActionCommand(hireString);
hireButton.addActionListener(hireListener);
hireButton.setEnabled(false);
fireButton = new JButton(fireString);
fireButton.setActionCommand(fireString);
fireButton.addActionListener(new FireListener());
employeeName = new JTextField(10);
employeeName.addActionListener(hireListener);
employeeName.getDocument().addDocumentListener(hireListener);
String name = listModel.getElementAt(list.getSelectedIndex()).toString();
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(fireButton);
buttonPane.add(Box.createHorizontalStrut(5));
buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
buttonPane.add(Box.createHorizontalStrut(5));
buttonPane.add(employeeName);
buttonPane.add(hireButton);
buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
add(listScrollPane, BorderLayout.CENTER);
add(buttonPane, BorderLayout.PAGE_END);
start();
System.out.println(new Date());
}
private void start() {
timer = new javax.swing.Timer(delay * 10, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");
list.ensureIndexIsVisible(listModel.getSize()-1);
count++;
if (count >= 500) {
timer.stop();
System.out.println("update cycle completed");
System.out.println(new Date());
}
}
};
}
class FireListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int index = list.getSelectedIndex();
listModel.remove(index);
int size = listModel.getSize();
if (size == 0) { //Nobody's left, disable firing.
fireButton.setEnabled(false);
} else { //Select an index.
if (index == listModel.getSize()) {
index--;
}
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
}
}
}
class HireListener implements ActionListener, DocumentListener {
private boolean alreadyEnabled = false;
private JButton button;
HireListener(JButton button) {
this.button = button;
}
#Override
public void actionPerformed(ActionEvent e) {
String name = employeeName.getText();
if (name.isEmpty() || alreadyInList(name)) {
Toolkit.getDefaultToolkit().beep();
employeeName.requestFocusInWindow();
employeeName.selectAll();
return;
}
int index = list.getSelectedIndex(); //get selected index
if (index == -1) { //no selection, so insert at beginning
index = 0;
} else { //add after the selected item
index++;
}
listModel.insertElementAt(employeeName.getText(), index);
//listModel.addElement(employeeName.getText());
employeeName.requestFocusInWindow();
employeeName.setText("");
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
}
protected boolean alreadyInList(String name) {
return listModel.contains(name);
}
#Override
public void insertUpdate(DocumentEvent e) {
enableButton();
}
#Override
public void removeUpdate(DocumentEvent e) {
handleEmptyTextField(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
if (!handleEmptyTextField(e)) {
enableButton();
}
}
private void enableButton() {
if (!alreadyEnabled) {
button.setEnabled(true);
}
}
private boolean handleEmptyTextField(DocumentEvent e) {
if (e.getDocument().getLength() <= 0) {
button.setEnabled(false);
alreadyEnabled = false;
return true;
}
return false;
}
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
if (list.getSelectedIndex() == -1) {
fireButton.setEnabled(false);
} else {
fireButton.setEnabled(true);
}
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("ListDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new ListDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}

Categories