I am developing a custom search component. When clicked on the button(search image icon) inside the text field, a table is displayed. The code is in very nascent stage so lots of things is not there.
As of now, I am stuck because I am not able to navigate the table with the arrow keys. Neither am I able to move to the next text field with "tab" key, once I select a row in the table.
The objective of the component is to select a row from the table and then with the help of the supporting methods(yet to be written) values from other labels and text fields would be defaulted while defaulting 1 st column value in the text field it is attached to.
Would really appreciate your help. Thanks !!
package myTableCombo;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JWindow;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class SearchBox extends JPanel {
private static final long serialVersionUID = 1L;
private JTextField editor;
private JButton arrowButton;
private JWindow jWindow;
private Component userComponent;
public SearchBox() {
super(new FlowLayout(FlowLayout.LEFT, 0, 0));
editor = new JTextField();
editor.setPreferredSize(new Dimension(250, 25));
initialize();
addListeners();
setBorders();
}
private void addListeners() {
arrowButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showWindow();
}
});
}
protected void showWindow() {
if (null != getWindowComponent()) {
jWindow = new JWindow();
jWindow.getContentPane().add(getWindowComponent());
jWindow.setLocation(new Point(SearchBox.this.getLocationOnScreen().x, SearchBox.this.getLocationOnScreen().y + 25));
jWindow.pack();
jWindow.setVisible(true);
}
}
private Component getWindowComponent() {
return userComponent;
}
public void setWindowComponent(Component component) {
userComponent = component;
}
private void initialize() {
arrowButton = new BasicArrowButton(SwingConstants.SOUTH);//In my code there is an icon here
arrowButton.setBorder(null);
arrowButton.setContentAreaFilled(false);
}
private void setBorders() {
add(editor);
add(arrowButton);
setBackground(editor.getBackground());
setBorder(editor.getBorder());
editor.setBorder(null);
}
public JTextField getTextComponent() {
return editor;
}
public JButton getActionButton() {
return arrowButton;
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
protected static void createAndShowGUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setPreferredSize(new Dimension(500, 400));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
panel.add(new JLabel("Test Table Combo"));
SearchBox searchBox = new SearchBox();
searchBox.userComponent = searchBox.new SearchBoxTable();
panel.add(searchBox);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class SearchBoxTable extends JScrollPane implements DocumentListener {
private static final long serialVersionUID = 1L;
private JTable table;
private Object[] columnNames;
private DefaultTableModel tableModel;
private Object[][] sheetDataInString;
private TableRowSorter<DefaultTableModel> rowSorter;
public SearchBoxTable() {
columnNames = new Object[]{"Column 1", "Column 2", "Column 3", "Column 4", "Column 5", "Column 6"};
sheetDataInString = new Object[21][6];
for(int i =0; i < sheetDataInString.length; i++) {
for(int j = 0; j< 6; j++) {
sheetDataInString[i][j] = "Row Value : " + i + ", Column Value : " + j;
}
}
tableModel = new DefaultTableModel(sheetDataInString, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
rowSorter = new TableRowSorter<DefaultTableModel>(tableModel);
table = new JTable(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setFillsViewportHeight(true);
table.getTableHeader().setFont(new Font(null, Font.PLAIN, 13));
setPreferredSize(new Dimension(500, 225));
setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
getViewport().add(table);
}
#Override
public void changedUpdate(DocumentEvent e) {
newFilter(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
newFilter(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
newFilter(e);
}
/**
* Update the row filter regular expression from the expression/string/data in the text box.
*
* #param documentEvent
*/
private void newFilter(DocumentEvent documentEvent) {
RowFilter<DefaultTableModel, Object> rowFilter = null;
Document document = documentEvent.getDocument();
String filterText;
try {
filterText = document.getText(0, document.getLength()).trim();
rowFilter = RowFilter.regexFilter("(?i)" + filterText);
} catch (java.util.regex.PatternSyntaxException e) {
return;
} catch (BadLocationException badLocationException) {
return;
}
rowSorter.setRowFilter(rowFilter);
table.setRowSorter(rowSorter);
}
}
}
do you meaning
use undecorated JDialog instead of JWindow, otherwise JTextComponets aren't editable
JDialog has better support for AlwaysOnTop and ModalityTypes (only hardcoded to the setAlwaysOnTop)
don't to recreate basic setting again and again, don't to recreate a popup windod, use lolac variable, remove all contents and add a new ony, define all setting for JDialog once time, see exception (The dialog is displayable.) in the case that popup is hidden and value in JTextField isn't empty
missed action for hide JDialog on ESC key event, hide JDialog, if is JFrame minimalized
missed moving with JDialog if JFrame is resized, moved over screen on another Point,
attach Document to the JTextField directly, not lost somwhere in to the JScrollPane definitions
your code missing a few good practicies, then everything is possible but not with this code (after my edit too)
search for JCalendar by Kay Toedter (best popup workaround as I saw for popup window)
only removed uselles methods, moved from- to, notice non_optimized_code, simple put to the recyclebin and wrote that again
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class SearchBox extends JPanel {
private static final long serialVersionUID = 1L;
private static JFrame frame = new JFrame();
private JTextField editor;
private JButton arrowButton;
//private JToggleButton arrowButton;
private JDialog popupWindow = new JDialog(frame);
private Component userComponent;
private JTable table;
private TableRowSorter<DefaultTableModel> rowSorter;
private Object[] columnNames;
private DefaultTableModel tableModel;
private Object[][] sheetDataInString;
public SearchBox() {
super(new FlowLayout(FlowLayout.LEFT, 0, 0));
editor = new JTextField();
editor.setPreferredSize(new Dimension(250, 25));
editor.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
newFilter();
}
#Override
public void insertUpdate(DocumentEvent e) {
newFilter();
}
#Override
public void removeUpdate(DocumentEvent e) {
newFilter();
}
private void newFilter() {
RowFilter<DefaultTableModel, Object> rowFilter = null;
Document document = editor.getDocument();
String filterText;
try {
filterText = document.getText(0, document.getLength()).trim();
rowFilter = RowFilter.regexFilter("(?i)" + filterText);
} catch (java.util.regex.PatternSyntaxException e) {
return;
} catch (BadLocationException badLocationException) {
return;
}
rowSorter.setRowFilter(rowFilter);
table.setRowSorter(rowSorter);
}
});
initialize();
addListeners();
setBorders();
}
private void addListeners() {
arrowButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!popupWindow.isVisible()) {
showWindow();
} else {
hideWindow();
}
}
});
}
protected void showWindow() {
if (null != getWindowComponent()) {
popupWindow.getContentPane().add(getWindowComponent());
popupWindow.setLocation(new Point(SearchBox.this.getLocationOnScreen().x, SearchBox.this.getLocationOnScreen().y + 25));
popupWindow.setUndecorated(true);
popupWindow.setAlwaysOnTop(true);
popupWindow.pack();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
popupWindow.setVisible(true);
}
});
}
}
protected void hideWindow() {
popupWindow.setVisible(false);
}
private Component getWindowComponent() {
return userComponent;
}
public void setWindowComponent(Component component) {
userComponent = component;
}
private void initialize() {
arrowButton = new BasicArrowButton(SwingConstants.SOUTH);//In my code there is an icon here
arrowButton.setBorder(null);
arrowButton.setContentAreaFilled(false);
}
private void setBorders() {
add(editor);
add(arrowButton);
setBackground(editor.getBackground());
setBorder(editor.getBorder());
editor.setBorder(null);
}
public JTextField getTextComponent() {
return editor;
}
public JButton getActionButton() {
return arrowButton;
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
protected static void createAndShowGUI() {
JPanel panel = new JPanel();
frame.setPreferredSize(new Dimension(500, 400));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
panel.add(new JLabel("Test Table Combo"));
SearchBox searchBox = new SearchBox();
searchBox.userComponent = searchBox.new SearchBoxTable();
panel.add(searchBox);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class SearchBoxTable extends JScrollPane {
private static final long serialVersionUID = 1L;
public SearchBoxTable() {
columnNames = new Object[]{"Column 1", "Column 2", "Column 3", "Column 4", "Column 5", "Column 6"};
sheetDataInString = new Object[21][6];
for (int i = 0; i < sheetDataInString.length; i++) {
for (int j = 0; j < 6; j++) {
sheetDataInString[i][j] = "Row Value : " + i + ", Column Value : " + j;
}
}
tableModel = new DefaultTableModel(sheetDataInString, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
};
rowSorter = new TableRowSorter<DefaultTableModel>(tableModel);
table = new JTable(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setFillsViewportHeight(true);
table.getTableHeader().setFont(new Font(null, Font.PLAIN, 13));
table.setPreferredScrollableViewportSize(table.getPreferredSize());
setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
getViewport().add(table);
}
}
}
Related
I am trying to create a JList with a small arrow next to it. When clicked, I want some content associated with the list item shown in the same List/Panel. The picture, I hope, gives a clear idea of what I am trying to achieve.
How do I do this ? Also, what is the small triangle feature to the left known as (for future search tags) ?
I hope this is what you meant. The arrowButton is a JToggleButton which, when activated, displays a JWindow containing information about the selected value of the JList. This JWindow will remain visible until the JToggleButtons state is set back to unselected again. The ListPanel class should be reusable in your code.
Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Example {
public Example() {
JFrame frame = new JFrame();
ArrayList<Object> elements = new ArrayList<Object>();
ArrayList<String> texts = new ArrayList<String>();
ListPanel listPanel = new ListPanel(elements, texts);
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JTextField elementField = new JTextField(5);
JTextArea textArea = new JTextArea(5, 10);
JPanel panel = new JPanel();
panel.add(new JLabel("Element:"));
panel.add(elementField);
panel.add(Box.createHorizontalStrut(15));
panel.add(new JLabel("Text:"));
panel.add(new JScrollPane(textArea));
int result = JOptionPane.showConfirmDialog(frame, panel, "Element & Text",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
listPanel.addElementToList(elementField.getText(), textArea.getText());
}
}
});
JButton deleteButton = new JButton("Remove");
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (listPanel.getList().getSelectedValue() != null) {
listPanel.removeElementFromList(listPanel.getList().getSelectedValue());
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
frame.add(listPanel);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
}
class ListPanel extends JPanel {
private JList<Object> list;
private JToggleButton arrowButton;
private ArrayList<String> texts;
private JWindow popup;
public ListPanel(ArrayList<Object> elements, ArrayList<String> texts) {
this.texts = texts;
popup = new JWindow();
arrowButton = new JToggleButton("\u25B6");
arrowButton.setMargin(new Insets(0, 0, 0, 0));
arrowButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (arrowButton.isSelected()) {
Object value = list.getSelectedValue();
if (value != null) {
JLabel titleLabel = new JLabel(value.toString());
titleLabel.setBackground(Color.WHITE);
titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
titleLabel.setHorizontalAlignment(JLabel.LEFT);
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
titlePanel.setBackground(Color.WHITE);
titlePanel.add(titleLabel);
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setText(texts.get(list.getSelectedIndex()));
JPanel contentPanel = new JPanel(new BorderLayout());
contentPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
contentPanel.add(titlePanel, BorderLayout.NORTH);
contentPanel.add(textPane);
popup.setLocation(arrowButton.getLocationOnScreen().x + arrowButton.getWidth(),
arrowButton.getLocationOnScreen().y);
popup.setContentPane(contentPanel);
popup.revalidate();
popup.pack();
popup.setVisible(true);
}
} else {
if (popup.isVisible()) {
popup.setVisible(false);
}
}
}
});
Timer timer = new Timer(100, null);
timer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (((JFrame) SwingUtilities.getWindowAncestor(ListPanel.this)) != null) {
activateComponentListener();
timer.stop();
}
}
});
timer.start();
list = new JList<Object>(new DefaultListModel<Object>());
for (Object element : elements) {
((DefaultListModel<Object>) list.getModel()).addElement(element);
}
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(Color.WHITE);
buttonPanel.add(arrowButton, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setBorder(null);
setLayout(new BorderLayout());
setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(scrollPane);
add(buttonPanel, BorderLayout.WEST);
}
private void activateComponentListener() {
((JFrame) SwingUtilities.getWindowAncestor(this)).addComponentListener(new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent arg0) {
if (popup.isVisible()) {
popup.setLocation(arrowButton.getLocationOnScreen().x + arrowButton.getWidth(),
arrowButton.getLocationOnScreen().y);
}
}
});
}
public void removeElementFromList(Object element) {
int index = getElementIndex(element);
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(getElementIndex(element)) != null) {
((DefaultListModel<Object>) getList().getModel()).removeElementAt(index);
getTexts().remove(index);
}
}
public void removeElementFromList(int index) {
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(index) != null) {
((DefaultListModel<Object>) getList().getModel()).removeElementAt(index);
getTexts().remove(index);
}
}
private Integer getElementIndex(Object element) {
for (int i = 0; i < ((DefaultListModel<Object>) getList().getModel()).getSize(); i++) {
if (((DefaultListModel<Object>) getList().getModel()).getElementAt(i).equals(element)) {
return i;
}
}
return null;
}
public void addElementToList(Object element, String text) {
((DefaultListModel<Object>) list.getModel()).addElement(element);
getTexts().add(text);
}
public JList<Object> getList() {
return list;
}
public JToggleButton getArrowButton() {
return arrowButton;
}
public ArrayList<String> getTexts() {
return texts;
}
}
http://prntscr.com/9jhrwa "How the GUI looks"
public class Okno1 extends javax.swing.JFrame {
static Konto[]konto;
static DefaultListModel listModel;
static int indexKonta;
public Okno1() {
initComponents();
napolniKonto();
jScrollPane1.setVisible(false);
button_potrdiKonto.setVisible(false);
}
here I fill my array with Objects and add them to DefaultListModel, also I create a new list with the mentioned DefaultListModel
listModel=new DefaultListModel();
list_konto.setModel(listModel);
konto=new Konto[4];
konto[0]=new Konto("10000/20000", "Test konto primer1");
konto[1]=new Konto("20000/30000", "Test konto primer2");
konto[2]=new Konto("50000/60000", "Test konto primer3");
konto[3]=new Konto("30000/50000", "Test konto primer4");
for (int i = 0; i < konto.length; i++) {
listModel.addElement(konto[i].getID()+" | "+konto[i].getOpis());
}
list_konto=new JList(listModel);
jScrollPane1.repaint();
}
Here I show the jScrollPanel when this button is pressed, I also show the button which must be pressed if I want to get the index of the selected element in the JList displayed
private void button_prikaziKontoActionPerformed(java.awt.event.ActionEvent evt) {
jScrollPane1.setVisible(true);
button_potrdiKonto.setVisible(true);
//revalidate();
//repaint();
}
Here I press a button and it should get me the index of the selected item, but it keeps giving me -1 and it doesn't matter if an item on the JList is selected or is not
private void button_potrdiKontoActionPerformed(java.awt.event.ActionEvent evt) {
//indexKonta=list_konto.getSelectedIndex();
text_opisKonta.setText(Integer.toString(list_konto.getSelectedIndex()));
}
It's not clear where your code is going awry. This compete example may allow you to study the problem in isolation. Also consider adding a ListSelectionListener to see the effect.
myList.addListSelectionListener((ListSelectionEvent e) -> {
myLabel.setText(getSelectionIndex());
});
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
/** #see http://stackoverflow.com/a/34497773/230513 */
public class Test extends JPanel {
private final String[] values = {"Value1", "Value2", "Value3", "Value4"};
private final JList myList = new JList(values);
private final JLabel myLabel = new JLabel();
public Test() {
myList.setSelectedIndex(values.length - 1);
myLabel.setText(getSelectionIndex());
this.add(myList);
this.add(myLabel);
this.add(new JButton(new AbstractAction("Show Selected Index") {
#Override
public void actionPerformed(ActionEvent e) {
myLabel.setText(getSelectionIndex());
}
}));
}
private String getSelectionIndex() {
return String.valueOf(myList.getSelectedIndex());
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Test());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
});
}
}
don't use static variables
always to test if (list.getSelectedIndex() > -1) {
use ListSelectionListener for JList, by always testing if (list.getSelectedIndex() > -1) {
for example (without using ListSelectionListener)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class JListAndSelection {
private JFrame frame = new JFrame();
private DefaultListModel listModel = new DefaultListModel();
private JList list = new JList(listModel);
private JScrollPane scrollPane = new JScrollPane(list);
private JLabel label = new JLabel("nothing is selected");
private JButton button1 = new JButton("print me selected value");
public JListAndSelection() {
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (list.getSelectedIndex() > -1) {
label.setText((String) list.getSelectedValue());
} else {
label.setText("nothing is selected");
}
}
});
listModel.addElement("10000/20000 - Test konto primer1");
listModel.addElement("20000/30000 - Test konto primer2");
listModel.addElement("50000/60000 - Test konto primer3");
listModel.addElement("30000/50000 - Test konto primer4");
list.setVisibleRowCount(5);
frame.setTitle("JFrame");
frame.add(label, BorderLayout.NORTH);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(button1, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new JListAndSelection();
});
}
}
In this GUI there are four images which place on array of DefaultComboBoxModel and label which helps to display the image. The default image is 1.png which appear on the frame. But when I select the other image from the combo list then it doesn't appear.
Code
public class Combo extends JFrame {
public Combo() {
super("Combo 2 GUI");
setSize(400, 300);
MethodG();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private void MethodG() {
JLabel l1;
JComboBox box;
JPanel p;
Container pane = getContentPane();
p = new JPanel();
box = new JComboBox();
box.setModel(new DefaultComboBoxModel(new String[] { "1.png", "2.png", "3.png", "4.png" }));
box.setMaximumRowCount(3);
String boxoption = (String) box.getSelectedItem();
Icon[] icons = { new ImageIcon(getClass().getResource(boxoption)) };
// Default display
l1 = new JLabel(icons[0]);
box.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
l1.setIcon(icons[box.getSelectedIndex()]);
}
}
});
pane.add(p);
p.add(box);
p.add(l1);
}
}
Main method
public class Main {
public static void main(String[] args) {
Combo obj = new Combo();
}
}
And the second problem what does these two lines do and how to write in if syntax.
JComboBox schemaBox;
String schema = (schemaBox.isEnabled() ? schemaBox.getSelectedItem().toString() : null);
String selectTable = (schema == null ? "" : schema + ".") + tableName;
To the first question: You have (easiest or ways) to get the icon or image icon directly from DefaultComboBoxModel, for example,
.
.
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class ComboBoxModels {
private JComboBox comboBoxDouble;
private JComboBox comboBoxInteger;
private JComboBox comboBoxBoolean;
private JComboBox comboBoxIcon;
private JComboBox comboBoxDate;
private JLabel label = new JLabel();
private Vector<Double> doubleVector = new Vector<Double>();
private Vector<Integer> integerVector = new Vector<Integer>();
private Vector<Boolean> booleanVector = new Vector<Boolean>();
private Vector<Icon> iconVector = new Vector<Icon>();
private Vector<Date> dateVector = new Vector<Date>();
private Icon icon1 = ((UIManager.getIcon("OptionPane.errorIcon")));
private Icon icon2 = (UIManager.getIcon("OptionPane.informationIcon"));
private Icon icon3 = (UIManager.getIcon("OptionPane.warningIcon"));
private Icon icon4 = (UIManager.getIcon("OptionPane.questionIcon"));
private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
public ComboBoxModels() {
doubleVector.addElement(1.001);
doubleVector.addElement(10.00);
doubleVector.addElement(0.95);
doubleVector.addElement(4.2);
comboBoxDouble = new JComboBox(doubleVector);
integerVector.addElement(1);
integerVector.addElement(2);
integerVector.addElement(3);
integerVector.addElement(4);
comboBoxInteger = new JComboBox(integerVector);
booleanVector.add(Boolean.TRUE);
booleanVector.add(Boolean.FALSE);
comboBoxBoolean = new JComboBox(booleanVector);
iconVector.addElement(icon1);
iconVector.addElement(icon2);
iconVector.addElement(icon3);
iconVector.addElement(icon4);
comboBoxIcon = new JComboBox(iconVector);
comboBoxIcon.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
Icon icon = (Icon) comboBoxIcon.getModel().getSelectedItem();
label.setIcon(icon);
}
}
});
dateVector.addElement(parseDate("25.01.2013"));
dateVector.addElement(parseDate("01.02.2013"));
dateVector.addElement(parseDate("03.03.2013"));
dateVector.addElement(parseDate("18.04.2013"));
comboBoxDate = new JComboBox(dateVector);
comboBoxDate.setRenderer(new ComboBoxRenderer());
JFrame frame = new JFrame("");
frame.setLayout(new GridLayout(2, 2, 5, 5));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(comboBoxDouble);
frame.add(comboBoxInteger);
frame.add(comboBoxBoolean);
frame.add(comboBoxIcon);
frame.add(comboBoxDate);
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private Date parseDate(String str) {
Date date = new Date();
try {
date = sdf.parse(str);
} catch (ParseException ex) {
}
return date;
}
private class ComboBoxRenderer extends JLabel implements ListCellRenderer {
private static final long serialVersionUID = 1L;
public ComboBoxRenderer() {
setOpaque(true);
setBorder(new EmptyBorder(1, 1, 1, 1));
}
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (!(value instanceof Date)) {
return this;
}
setText(sdf.format((Date) value));
return this;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ComboBoxModels comboBoxModel = new ComboBoxModels();
}
});
}
}
Your icons array isn't being initialized as you expect. The code you have is creating an array with only one entry - 1.png. You'll need to initialize your array to contain all the images. Something like this:
Icon[] icons = { new ImageIcon(getClass().getResource("1.png")),
new ImageIcon(getClass().getResource("2.png")),
new ImageIcon(getClass().getResource("3.png")),
new ImageIcon(getClass().getResource("4.png"))};
What is the best way to add a background image to a JPanel/JLabel when a JButton is called? I know how to get the JButton action and such. I just can't figure out or find a way to get the background image to change when that button is pressed.
Here is an example:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class ModifiableBackgroundFrame extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private ImageIcon image;
private JPanel pan;
private JButton btn;
private int count = 0;
private static final String[] images =
{"http://www.dvd-ppt-slideshow.com/images/ppt-background/background-3.jpg",
"http://www.psdgraphics.com/wp-content/uploads/2009/02/abstract-background.jpg",
"http://hdwallpaperpics.com/wallpaper/picture/image/background.jpg",
"http://www.highresolutionpics.info/wp-content/uploads/images/beautiful-on-green-backgrounds-for-powerpoint.jpg"};
public ModifiableBackgroundFrame()
{
super("The title");
image = new ImageIcon();
btn = new JButton("Change background");
btn.setFocusPainted(false);
btn.addActionListener(this);
pan = new JPanel()
{
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g)
{
g.drawImage(image.getImage(), 0, 0, null);
}
};
pan.setPreferredSize(new Dimension(400, 400));
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(pan, BorderLayout.CENTER);
contentPane.add(btn, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new ModifiableBackgroundFrame();
}
});
}
#Override
public void actionPerformed(ActionEvent e)
{
btn.setEnabled(false);
btn.setText("Loading...");
new SwingWorker<Image, Void>()
{
#Override
protected Image doInBackground() throws Exception
{
return ImageIO.read(new URL(images[count++ % 4]));
}
#Override
protected void done()
{
try
{
image.setImage(get());
pan.repaint();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
catch(ExecutionException e)
{
e.printStackTrace();
}
btn.setText("Change background");
btn.setEnabled(true);
}
}.execute();
}
}
In your JButton's actionPerformed, you can call JLabel.setIcon(Icon) to set a background image.
final JLabel label = new JLabel();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(SOME_IMAGE));
}
}
I am trying to make one column from JTable, invisible by setting width to zero but it could not happen and it remain visible to width = 15. Here is code -
public void restoreColumnWithWidth(int column, int width) {
try {
TableColumn tableColumn = table.getColumnModel().getColumn(column);
table.getTableHeader().setResizingColumn(tableColumn);
tableColumn.setWidth(width);
tableColumn.setMaxWidth(width);
tableColumn.setMinWidth(width);
tableColumn.setPreferredWidth(width);
} catch (Exception ex) {
}
}
What is wrong with the code ?
not, never to remove TableColumn from TableModel, this is wrong suggestion, instead of to use built-in method JTable#removeColumn(TableColumn aColumn),
notice, this method remove column only from View, in the model is removed column still presents, and you can revert that, visible the removed column by using JTable#addColumn(TableColumn aColumn)
EDIT
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class TableRowHeight {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame("p*s*s*s*s*t*t");
private String[] columnNames = {"one", "two", "Playing with", "four", "five",};
private String[][] data = {
{"aaaaaa", "bbbbbb", "cccccc", "dddddd", "eeeeeee",},
{"bbbbbb", "cccccc", "dddddd", "eeeeeee", "aaaaaa",},
{"cccccc", "dddddd", "eeeeeee", "aaaaaa", "bbbbbb",},
{"dddddd", "eeeeeee", "aaaaaa", "bbbbbb", "cccccc",},
{"eeeeeee", "aaaaaa", "bbbbbb", "cccccc", "dddddd",}};
private JTable table = new JTable(new DefaultTableModel(data, columnNames));
private TableColumnModel tcm = table.getColumnModel();
private Stack<TableColumn> colDeleted = new Stack<TableColumn>();
private JButton restoreButton = new JButton("Restore Column Size");
private JButton hideButton = new JButton("Set Column Size to Zero");
private JButton deleteButton = new JButton("Delete Column");
private JButton addButton = new JButton("Restore Column");
public TableRowHeight() {
table.setRowMargin(4);
table.setRowHeight(30);
table.setFont(new Font("SansSerif", Font.BOLD + Font.PLAIN, 20));
JScrollPane scrollPane = new JScrollPane(table);
for (int i = 0; i < (tcm.getColumnCount()); i++) {
tcm.getColumn(i).setPreferredWidth(100);
}
table.setPreferredScrollableViewportSize(table.getPreferredSize());
restoreButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tcm.getColumn(2).setPreferredWidth(100);
}
});
hideButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tcm.getColumn(2).setPreferredWidth(000);
}
});
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.getColumnCount() > 0) {
TableColumn colToDelete = table.getColumnModel().getColumn(table.getColumnCount() - 1);
table.removeColumn(colToDelete);
table.validate();
colDeleted.push(colToDelete);
addButton.setEnabled(true);
} else {
deleteButton.setEnabled(false);
}
}
});
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (colDeleted.size() > 0) {
table.addColumn(colDeleted.pop());
table.validate();
deleteButton.setEnabled(true);
} else {
addButton.setEnabled(false);
}
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(hideButton);
btnPanel.add(restoreButton);
btnPanel.add(deleteButton);
btnPanel.add(addButton);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(btnPanel, BorderLayout.SOUTH);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
TableRowHeight frame = new TableRowHeight();
}
});
}
}
EDIT2
you have to check too
JTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JTable.getTableHeader().setReorderingAllowed(false);
If it should be removed, and not just hidden: Remove it from the table-model.
If it only should be hidden and later shown, you can remove the TableColumn from the TableColumnModel
Making the column height 0 is a bit bogus.