How to get the selected RadioButton from JTable - java

i'm workin on programe and i need to get the selected radio buttom from a Jtable
I found an exemple that i'm workin on
there is to class
the 1st :
import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
class RadioButtonRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value == null)
return null;
return (Component) value;
}
}
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private JRadioButton button;
public RadioButtonEditor(JCheckBox checkBox) {
super(checkBox);
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (value == null)
return null;
button = (JRadioButton) value;
button.addItemListener(this);
return (Component) value;
}
public Object getCellEditorValue() {
button.removeItemListener(this);
return button;
}
public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
}
}
and the 2nd class is :
package TP2;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToggleButton;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
public class tablesDesEtudiants extends JFrame {
public tablesDesEtudiants(Object[][] objt) {
super("List des etudiants");
// UIDefaults ui = UIManager.getLookAndFeel().getDefaults();
// UIManager.put("RadioButton.focus", ui.getColor("control"));
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(objt , new Object[] {"Nom","Prénom","Année","Succs","Type","Select"});
JTable table = new JTable(dm) {
public void tableChanged(TableModelEvent e) {
super.tableChanged(e);
repaint();
}
};
final ButtonGroup group1 = new ButtonGroup();
for(int i =0 ; i<objt.length;i++){
if(objt[i][1]!=null)
group1.add((JRadioButton) dm.getValueAt(i, 5));
}
// System.out.println(objt.length);
table.getColumn("Select").setCellRenderer(new RadioButtonRenderer());
table.getColumn("Select").setCellRenderer(new RadioButtonRenderer());
table.getColumn("Select").setCellRenderer(new RadioButtonRenderer());
table.getColumn("Select").setCellRenderer(new RadioButtonRenderer());
table.getColumn("Select").setCellRenderer(new RadioButtonRenderer());
table.getColumn("Select").setCellEditor(new RadioButtonEditor(new JCheckBox()));
JScrollPane scroll = new JScrollPane(table);
JButton bView = new JButton("View");
bView.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel choix = group1.getSelection();
if (choix != null) {
System.out.println( choix.getActionCommand());
}
else System.out.println("nullll");
}
});
JPanel pp =new JPanel();
MigLayout layout = new MigLayout(
"", // Layout Constraints
"[][]20[]", // Column constraints
"[]20[]"); // Row constraint
pp.setLayout(layout);
pp.add(scroll,"cell 1 2");
pp.add(bView,"cell 2 3");
getContentPane().add(pp);
setSize(600, 400);
setVisible(true);
}
/* public static void main(String[] args) {
JRadioButtonTableExample frame = new JRadioButtonTableExample();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}*/
}
in the 2nd class i'm trying to add all the radio button on ButtonGroup
like this :
final ButtonGroup group1 = new ButtonGroup();
for(int i =0 ; i<objt.length;i++){
if(objt[i][1]!=null)
group1.add((JRadioButton) dm.getValueAt(i, 5));
}
and my problem is that i can't get selected RadioButton :
ButtonModel choix = group1.getSelection();
if (choix != null) {
System.out.println( choix.getActionCommand());
}
else System.out.println("nullll");
}
i alwayse get nullll
any help plz !!

Read my answer to this question. You shouldn't store components in a table. Store booleans. You should then configure a renderer to display the boolean as a radio button, and an editor to change the value of the checked cell as well as the value of the previously checked one. And understand that the same instance of renderer is used to render/edit all the cells of the same class.

I think that not easy job, TableCellEditor for JRadioButtons in the ButtonGroup
use JCheckBox if is possible
use JComboBox as TableCellEditor instead of JRadioButtons in the ButtonGroup if is possible, for TableCellRenderer you can use JRadioButtons in the ButtonGroup

Related

How to take value of JComboBox value that is inside JTable?

I have tried this part of code to get values from a JComboBox that is inside of a JTable, but it doesn't work!
I want to get the value of selected cell in order to insert into DB.
package fx;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class ComboInTable extends JFrame {
private static JFrame jFrame;
public ComboInTable() throws HeadlessException {
jFrame=this;
JTable table=new JTable();
DefaultTableModel model= (DefaultTableModel) table.getModel();
model.addColumn("A",new Object[]{"item1"});
model.addColumn("B",new Object[]{"item2"});
JScrollPane scrollPane=new JScrollPane(table);
String[] value1=new String[]{"1","2","3"};
String[] value2=new String[]{"a","b","c"};
TableColumn col0=table.getColumnModel().getColumn(0);
TableColumn col1=table.getColumnModel().getColumn(1);
col0.setCellEditor(new MyComboBoxEditor(value1));
col0.setCellRenderer(new MyComboBoxRenderer(value1));
col1.setCellEditor(new MyComboBoxEditor(value2));
col1.setCellRenderer(new MyComboBoxRenderer(value2));
JComboBox comboBox=new JComboBox(value1);
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED)
{
System.out.println(e.getItem());
}
}
});
jFrame.setLayout(new FlowLayout());
jFrame.add(scrollPane);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setSize(400, 400);
jFrame.setVisible(true);
}
public static void main(String[] args) {
ComboInTable comboInTable=new ComboInTable();
}
}
I have MyComboBoxEditor and MyComboBoxRenderer classes.
package fx;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
public MyComboBoxRenderer(String[] items) {
super( items);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(isSelected){
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
}
else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelectedItem(value);
return this;
}
}
package fx;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
public class MyComboBoxEditor extends DefaultCellEditor {
public MyComboBoxEditor(String[] items) {
super(new JComboBox(items));
}
}
I have tried this part of code to get values from a JComboBox that is inside of a JTable,
You don't get the value from the combo box.
You get the value from the JTable using the getValueAt(...) method.
I also have no idea why you are creating a custom renderer and editor. Just use the default renderer/editor provided by the table.
Start by reading the section from the Swing tutorial on How to Use Tables. You will find an example that shows how to use a combo box as an editor.

JComboBox on cell of JTable

I have a JTable object and i would add 5 different JComboBox on a single column.
I've so tried:
table.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(jcombo));
but this add the same JComboBox to all cells of that column. How can i do to add different ones on the same column?
Thank you!
Basically, you need to modify the model which the combobox is using depending on the row.
The following example allows you to specify a ComboBoxModel for a given row and provide a default ComboBoxModel to be used when one is not specified for the row.
Generally speaking though, each column should be of the same type...
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TestCombo {
public static void main(String[] args) {
new TestCombo();
}
public TestCombo() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultTableModel model = new DefaultTableModel(new Object[]{"Stuff"}, 5);
JTable table = new JTable(model);
table.setGridColor(Color.LIGHT_GRAY);
MyComboBoxCellEditor editor = new MyComboBoxCellEditor();
editor.setModelForRow(0, new DefaultComboBoxModel(new Object[]{"Banana", "Peach", "Pear"}));
editor.setModelForRow(1, new DefaultComboBoxModel(new Object[]{"Dog", "Cat", "T-Rex"}));
editor.setModelForRow(2, new DefaultComboBoxModel(new Object[]{"Car", "Truck", "Hovercraft"}));
editor.setModelForRow(3, new DefaultComboBoxModel(new Object[]{"Helicopter", "Plane", "Rocket"}));
editor.setModelForRow(4, new DefaultComboBoxModel(new Object[]{"PC", "Mac", "Linux"}));
table.getColumnModel().getColumn(0).setCellEditor(editor);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyComboBoxCellEditor extends DefaultCellEditor {
private ComboBoxModel defaultModel;
private Map<Integer, ComboBoxModel> mapModels;
public MyComboBoxCellEditor() {
super(new JComboBox());
mapModels = new HashMap<>(25);
defaultModel = new DefaultComboBoxModel();
}
public void setDefaultModel(ComboBoxModel model) {
defaultModel = model;
}
public void setModelForRow(int row, ComboBoxModel model) {
mapModels.put(row, model);
}
public ComboBoxModel getDefaultModel() {
return defaultModel;
}
public ComboBoxModel getModelForRow(int row) {
return mapModels.get(row);
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JComboBox comboBox = (JComboBox) getComponent();
ComboBoxModel model = getModelForRow(row);
if (model == null) {
model = getDefaultModel();
}
comboBox.setModel(model);
return super.getTableCellEditorComponent(table, value, isSelected, row, column); //To change body of generated methods, choose Tools | Templates.
}
}
}

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);
}
}

JTable component access before row selection

I'm using a jtable and i need to access a component locate in a row different from the selected one.
The problem i have is that when i click the component the row selection change come before the component click event.
This is a SSCE that explain the problem.
package test;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
public class Main extends JFrame {
public static void main(String[] args) {
new Main();
}
public Main() {
JButton btnTest = new JButton("test");
btnTest.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.err.println("btnTest clicked!");
}
});
JButton btnTest2 = new JButton("test2");
btnTest2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.err.println("btnTest2 clicked!");
}
});
JTable table = new JTable(new Object[][] {
{ btnTest, "test"},
{ btnTest2, "test2"},
}, new Object[] {"btn", "desc"});
table.setDefaultEditor(Object.class, new Editor());
table.setDefaultRenderer(JComponent.class, new TableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
return (JComponent)(value);
}
});
ListSelectionModel rowSM = table.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
System.err.println("new Selection!");
}
});
table.setSelectionModel(rowSM);
add(table);
setSize(300, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
class Editor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = 1L;
private JComponent item;
#Override
public Object getCellEditorValue() {
return item;
}
#Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
item = (JComponent)value;
item.setBackground(table.getSelectionBackground());
return item;
}
}
}
When i click the button the row unselected this is the console result:
new Selection!
btnTest clicked!
new Selection!
Is possible to fire the "btnTest clicked!" first?
Thanks

java.net BalloonTip is not showing up

I saw the BallonTip at java.net and I tried to integrate it into my application to be displayed when a user clicks a table cell. When a table cell is clicked, the BalloonTip is showing up as intended, but when you scroll it out of the current viewport, you can click another cell without the BalloonTip showing up. When you scroll the table, the BallonTip is shown again.
Here is an example:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.java.balloontip.BalloonTip;
import net.java.balloontip.TablecellBalloonTip;
import net.java.balloontip.styles.EdgedBalloonStyle;
public class TableTest2 extends JFrame {
static final int LENGTH = 40;
TablecellBalloonTip tip;
JTable mainTable;
JPanel main;
JLayeredPane layeredPane;
JScrollPane mainScroll;
TableTest2() {
mainTable = new JTable(LENGTH, LENGTH);
CustomListSelectionListener clsl = new CustomListSelectionListener(mainTable);
mainTable.getColumnModel().getSelectionModel().addListSelectionListener(clsl);
mainTable.getSelectionModel().addListSelectionListener(clsl);
mainTable.setTableHeader(null);
mainTable.setColumnSelectionAllowed(true);
mainScroll = new JScrollPane(mainTable);
add(mainScroll);
tip = new TablecellBalloonTip(mainTable, new JLabel("Hello World!"), -1, -1, new EdgedBalloonStyle(Color.WHITE,
Color.BLUE), BalloonTip.Orientation.LEFT_ABOVE, BalloonTip.AttachLocation.ALIGNED, 5, 5, false);
setPreferredSize(new Dimension(500, 400));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public static void main(String[] args) {
new TableTest2();
}
protected class CustomListSelectionListener implements ListSelectionListener {
private int row, column, lead, anchor;
private JTable table;
public CustomListSelectionListener(JTable table) {
this.table = table;
}
#Override
public void valueChanged(ListSelectionEvent evt) {
if (evt.getSource() == table.getSelectionModel() && table.getRowSelectionAllowed()) {
// row selection changed
row = table.getSelectedRow();
column = table.getSelectedColumn();
tip.setCellPosition(row, column);
tip.refreshLocation();
} else if (evt.getSource() == table.getColumnModel().getSelectionModel()
&& table.getColumnSelectionAllowed()) {
// column selection changed
lead = table.getColumnModel().getSelectionModel().getLeadSelectionIndex();
anchor = table.getColumnModel().getSelectionModel().getAnchorSelectionIndex();
if (lead <= anchor) {
column = anchor;
} else {
column = lead;
}
row = table.getSelectedRow();
tip.setCellPosition(row, column);
tip.refreshLocation();
}
}
}
}
How can I force the BalloonTip to be shown after I click a cell in the table? I think there is a listener, which is listening for the scrolling event and manages the painting of the BallonTip, but I do not have a clue which one it is.
best regards
htz
According to this mailing list, there was a bug in the BallonTip version 1.2.1. Now, with version 1.2.3, this is fixed.

Categories

Resources