JCheckBox inside JTableCell appear and disappear on click - java

I have a table in which a column needs to be a 'checkbox-column". And I wrote the code like this.
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Test0 {
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test0 test = new Test0();
test.launch();
}
});
}
private void launch() {
JFrame frame = new JFrame();
Object[][] data = {{Boolean.TRUE}};
String[] columnName = {"Checkbox here!"};
#SuppressWarnings("serial")
JTable table = new JTable(new DefaultTableModel(data,columnName) {
#Override
public Class<?> getColumnClass(int columnIndex){
return Boolean.class;
}
});
JCheckBox checkBox = new JCheckBox("HI");
table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(checkBox));
JScrollPane tableScrollPane = new JScrollPane(table);
frame.add(tableScrollPane);
frame.pack();
frame.setVisible(true);
}
}
When I run this, the checkbox with a "HI" label was not there as I want to be.
Instead, a normal checkbox appeared and when I clicked that, my checkbox appeared and disappeared quickly.
I don't understand what caused that. Please help me. Thank you.

Related

Small Gap between Table and ScrollPane Border Java Swing

I'm trying To insert a JTable into a JScrollPane and I see a small gap between the borders of the table and the scroll Pane.And on the left side the table looks to be aligned to extreme left.Can someone please help me fix this.?
Removing setAutoResizeMode(JTable.AUTO_RESIZE_OFF) is fixing that.But I Need to turn that off.
this.dataTable = new SortableTable(this);
this.dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
this.dataTable.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
scrollPane = new JScrollPane(dataTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(900,250));
scrollPane.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
You simply need to set the resize mode in a listener, when the component is resized. Here is an example:
import java.awt.Window;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.TableColumn;
public class TableTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new TableTest());
}
#Override
public void run() {
JTable table = new JTable(10, 3);
final JScrollPane scroller = new JScrollPane(table);
// update the resize mode when scroller is resized and window is shown
scroller.addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
Window win = SwingUtilities.windowForComponent(scroller);
if (win != null && win.isVisible()) {
updateColumns(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
}
});
JFrame frm = new JFrame("Table");
frm.add(scroller);
frm.setSize(600, 400);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
// Transfer column widths from autoresize mode
private void updateColumns(JTable table) {
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumn col = table.getColumnModel().getColumn(i);
col.setPreferredWidth(col.getWidth());
}
}
}

Adding values to Jtable when button is clicked in java [duplicate]

In my application everything is distributed.
On a action, application retrieves data from DB and saves in ArrayList<T>.
I create an object of RelativeTableModel where I pass the ArrayList<T>.
public void RelationsClicked() {
ArrayList<Relation> data = myParent.dbOperation.getRelations();
RelativeTableModel tModel = new RelativeTableModel(data); // subclass of AbstractTableModel
myParent.SetBrowsePanelData(tModel);
myParent.SetMainPanel(CashAccountingView.BROWSEPANEL);
}
I have a BrowseListPanel class that has a JTable in JScrollPane. Its instance is already created in the main application.
I pass the model to BrowseListPanel and finally show the panel.
Code:
public void SetBrowsePanelData(AbstractTableModel tModel) {
browsePanel.setTModel(tModel);
}
// BrowseListPanel's Code
public void setTModel(AbstractTableModel tModel) {
this.tModel = tModel; // tModel = AbstractTableModel
}
// Show the Panel
public void SetMainPanel(String panel) {
activePanel = panel;
SetFontSize();
cards.show(mainPanel, panel);
mainPanel.revalidate();
mainPanel.repaint();
}
But I don't see the Table. I believe as the object of BrowseListPanel (containing the JTable) is already created & later the TableModel is added. So some sort of event should be fired in setTModel().
Am I right? If so, what event should be thrown and what should be its implementation.
Invoking setModel() on the table should be sufficient, but you might call fireTableStructureChanged() on the model explicitly as a way to help sort things out.
Also, verify that you are working on the event dispatch thread.
Addendum: Here's an sscce that shows the basic approach.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/** #see http://stackoverflow.com/questions/8257148 */
public class SwapTableModel extends JPanel {
public SwapTableModel() {
final JTable table = new JTable(Model.Alpha.model);
table.setPreferredScrollableViewportSize(new Dimension(128, 32));
this.add(new JScrollPane(table));
final JComboBox combo = new JComboBox();
for (Model model : Model.values()) {
combo.addItem(model);
}
this.add(combo);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Model model = (Model) combo.getSelectedItem();
table.setModel(model.model);
}
});
}
private enum Model {
Alpha(), Beta();
private DefaultTableModel model;
private Model() {
Object[] data = {this.toString()};
this.model = new DefaultTableModel(data, 1);
model.addRow(data);
}
}
private void display() {
JFrame f = new JFrame("SwapTableModel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new SwapTableModel().display();
}
});
}
}

JComboBox how to show the right end of the item?

I have the following Java code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class EnumsRightVisible {
public void show() {
JFrame frame = new JFrame("Combo box");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] items = {"aaaaaaaaa__________zzzzzzzzz",
"aaaaaaaaa__________zzzzzzzzz",
"aaaaaaaaa__________zzzzzzzzz"};
JComboBox combo = new JComboBox(items);
combo.setPreferredSize(new Dimension(100,20));
frame.add(combo, BorderLayout.CENTER);
frame.setLocation(600, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
EnumsRightVisible enumsRightVisible = new EnumsRightVisible();
enumsRightVisible.show();
}
}
Running it you can see that the visible text is left oriented.
Please note that this code does not solve my problem (it aligns the text to the right, but only when the combo box is expanded):
((JLabel)comboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);
How can I display the right end of the text in the same window (...__zzzzzz)?
Thanks in advance!
Use a custom renderer that uses FontMetrics to measure the String's width and does the ellipsis (...) manually. More info here: http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer
Method 1
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ComboBoxDemo extends JFrame {
public ComboBoxDemo() {
JComboBox comboBox = new JComboBox();
((JLabel)comboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);
comboBox.addItem("Apple");
comboBox.addItem("Orange");
comboBox.addItem("Mango");
getContentPane().add(comboBox, "North");
setSize(200, 100);
this.setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ComboBoxDemo().setVisible(true);
}
}
Method 2 (Oviously, First is better)
import java.awt.Component;
import java.awt.ComponentOrientation;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class ComboBoxDemo extends JFrame {
public ComboBoxDemo() {
JComboBox comboBox = new JComboBox();
setListCellRendererOf(comboBox);
comboBox.addItem("Apple");
comboBox.addItem("Orange");
comboBox.addItem("Mango");
getContentPane().add(comboBox, "North");
setSize(200, 100);
this.setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void setListCellRendererOf(JComboBox comboBox) {
comboBox.setRenderer(new ListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component component = new DefaultListCellRenderer()
.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
component.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
return component;
}
});
}
public static void main(String[] args) {
new ComboBoxDemo().setVisible(true);
}
}

Enable and Disable Sorting of JTable dynamically

I'm new to Java Swing and I'm working with JTable.
Actually, I have difficulty in sorting of this component.
I want to enable and disable this function programatically.
I use JTable.setAutoCreateSorter(true) to initialize it, I change to false, nothing happen.
Also, I had use JTable.setRowSorter(null), it works, but I do not know how to enable it again.
Sorry for my poor English!
You can use setSortable(int index, boolean sortable) method of DefaultRowSorter.
for (int i=0 ; i<table.getColumnCount() ; i++) {
sorter.setSortable(i, false);
}
This worked for me. See also JTable sorting programatically only
Inspecting at JTable.setAutoCreateRowSorter(boolean autoCreateRowSorter) source code:
public void setAutoCreateRowSorter(boolean autoCreateRowSorter) {
boolean oldValue = this.autoCreateRowSorter;
this.autoCreateRowSorter = autoCreateRowSorter;
if (autoCreateRowSorter) {
setRowSorter(new TableRowSorter<TableModel>(getModel()));
}
firePropertyChange("autoCreateRowSorter", oldValue,
autoCreateRowSorter);
}
So, you have two options:
Keep a reference to the row sorter to restore it later, as #nachokk suggested.
Set a new TableRowSorter instance:
table.setRowSorter(new TableRowSorter(table.getModel()));
Edit
But now the table's rows are not selectable
That's weird, I didn't have any problem with row selection. Here is the code I've used to test my answer:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class Demo {
private void createAndShowGUI() {
DefaultTableModel model = new DefaultTableModel(new Object[]{"Column # 1", "Column # 2"}, 0){
#Override
public Class<?> getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0: return String.class;
case 1: return Integer.class;
default: return super.getColumnClass(columnIndex);
}
}
};
for (int i = 0; i < 20; i++) {
model.addRow(new Object[]{"Property # " + i, Integer.valueOf(i)});
}
final JTable table = new JTable(model);
table.setAutoCreateRowSorter(true);
JToggleButton toggleButton = new JToggleButton("Disable", true);
toggleButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JToggleButton toggleButton = (JToggleButton)e.getSource();
String text = toggleButton.isSelected() ? "Disable" : "Enable";
TableRowSorter sorter = toggleButton.isSelected() ? new TableRowSorter(table.getModel()) : null;
toggleButton.setText(text);
table.setRowSorter(sorter);
}
});
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.add(toggleButton, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Demo().createAndShowGUI();
}
});
}
}

Java JCheckBox ItemListener makes program work incorrectly

I minimized my program to include only the problem and I tried to code exactly as I understood from many examples. When I used the ActionListener, I get problem solved. But I wonder why using ItemListener, checkbox does not operate correctly.
If I run my program without ItemListener, it works correctly. With this ItemListener, checkBox doesn't change state.
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class omaJFrame extends JFrame{
private JCheckBox checkBox1;
public omaJFrame() {
super("Window Title");
TheHandler handler = new TheHandler();
setLayout(new FlowLayout());
checkBox1 = new JCheckBox("Checkbox 1");
add(checkBox1);
checkBox1.addItemListener(handler);
}
private class TheHandler implements ItemListener {
String output = "";
public void itemStateChanged(ItemEvent event) {
if (event.getItem()==checkBox1)
output = String.format("%s", checkBox1.isSelected());
JOptionPane.showMessageDialog(null, output);
}
}
}
import javax.swing.JFrame;
public class EventHandlerMain {
public static void main(String[] args) {
omaJFrame window = new omaJFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(350,200);
window.setVisible(true);
}
}
Works for me. Note also that Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class OmaJFrame extends JFrame {
private JCheckBox checkBox1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
OmaJFrame f = new OmaJFrame();
}
});
}
public OmaJFrame() {
super("Window Title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
TheHandler handler = new TheHandler();
setLayout(new FlowLayout());
checkBox1 = new JCheckBox("Checkbox 1");
add(checkBox1);
checkBox1.addItemListener(handler);
pack();
setLocationByPlatform(true);
setVisible(true);
}
private class TheHandler implements ItemListener {
String output = "";
#Override
public void itemStateChanged(ItemEvent event) {
if (event.getItem() == checkBox1) {
output = String.format("%s", checkBox1.isSelected());
}
JOptionPane.showMessageDialog(null, output);
}
}
}

Categories

Resources