import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import net.java.dev.designgridlayout.DesignGridLayout;
import java.io.*;
import net.java.dev.designgridlayout.Tag;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
class table1
{
JFrame JF;
Container C;
JPanel JP;
JLabel creditLabel;
JComboBox credit;
String[] Credit = {"Vasan Phalke", "Pansare", "Anil Kg", "Suresh"};
String[] Names = {"Name", "Qty", "Rate/ Kg", "Rate/Dzn.", "Total Amt."};
JTable table;
DefaultTableModel model;
JScrollPane scrollPane;
public table1()
{
JF = new JFrame();
JP = new JPanel();
C= JF.getContentPane();
JF.pack();
JF.setLocationRelativeTo(null);
JF.setVisible(true);
DesignGridLayout layout = new DesignGridLayout(C);
creditLabel = new JLabel("Credit");
credit = new JComboBox<String>(Credit);
model = new DefaultTableModel(Names,5);
table =new JTable(model){#Override
public boolean isCellEditable(int arg0, int arg1)
{
return true;
}
};
scrollPane= new JScrollPane(table);
layout.row().grid(creditLabel).add(credit);
layout.emptyRow();
layout.row().grid().add(table);
C.add(JP);
}
public static void main(String args[])
{
new table1();
}
}
By clicking on the value of combobox, it should appear in the name column of the table, and what changes should be made to the table for automatic calculation, ie, when i enter qty and rate, total amount should automatically be calculated.
How all these things can be done, please help.
Thanks in advance.
Read the section from the Swing tutorial on How to Use Tables
The tutorial shows you how to use a combo box as an editor for a column in a table. This is what you should be doing instead of having a separate combo box.
To calculate the amount, you need to create a custom TableModel and override the setValueAt() method. Whenever the quantity or rate changes you recalculate the amount.
Related
I am making a project that uses a box and a JComboBox and want to use GridBagLayout. I want the combo box at the top center of the screen, then the Box with a JTextArea inside at the center. This is my code so far:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
/**comboBoxFrame Constructor
* Takes Mouse Event Input From User
* Based On Option Chosen By User From Dropdown, Displays Corresponding information, Taken From birtdayCaclulator.java
*/
#SuppressWarnings("serial")
public class comboBoxFrame extends JFrame {
private final JComboBox<String> classComboBox;
private JTextArea outputBox;
private static final String[] names = {
"-Select-",
"Age Summary",
"Zodiac Sign",
"Birth Stone",
"Generation",
"Day of Week",
"Lucky Number",
"Milestones",
"First Presidential Election Vote",
"Days Since Last Birthday",
"Days Until Next Birthday",
"Animal Years Summary",
"Other Planet Age Summary",
"Days After Milestones Summary",
"Birthday Summary",
"Help"
};
private static final String[] output = {
"Output will appear here",
CreateDriver.bday.ageSummary(),
CreateDriver.bday.getZodiacSign(),
CreateDriver.bday.getBirthStone(),
CreateDriver.bday.getGeneration(),
CreateDriver.bday.getDayOfWeek(),
CreateDriver.bday.getLuckyNum(),
CreateDriver.bday.getMileStones(),
CreateDriver.bday.getFirstPresElectionVote(),
CreateDriver.bday.getDaysSinceLastBday(),
CreateDriver.bday.getDaysTillNextBday(),
CreateDriver.bday.animalYearsSummary(),
CreateDriver.bday.otherPlanetAgeSummary(),
CreateDriver.bday.getDaysAfterMilestonesSummary(),
CreateDriver.bday.toString(),
CreateDriver.bday.getHelp()
};
public comboBoxFrame() {
super("Birthday Calculator");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Box box = new Box(BoxLayout.Y_AXIS);
outputBox = new JTextArea("Output will appear here", 20, 50);
box.add(outputBox, gbc);
classComboBox = new JComboBox<String>(names);
classComboBox.setMaximumRowCount(5);
classComboBox.addItemListener(
new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
outputBox.setText(output[classComboBox.getSelectedIndex()]);
}
}
}
);
add(classComboBox, gbc);
outputBox = new JTextArea("Output will appear here");
add(outputBox, gbc);
}
}
It currently prints the ComboBox and Box next to each other at the center Y Axis. Does anyone know what I should change to fix this?
I have a ComboBox which contains checkbox inside it, placed in a table. Whenever I select the row, the color render is applying only to remaining cells of the table. How to render the "checkedcombobox", so that it can also get selection color matching with other cells in the row of a table.
Here is an example for you:
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicComboBoxUI;
public class TableEditorExample {
private static final String[] COLS = {"Number", "Type", "Name"};
private static final Object[][] DATA = {{"1", "Book", "Brave new world"}, {"2", "Music", "Smells like a teen spirit"},
{"3", "Film", "Star Wars"}};
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// Nothing
}
JFrame frm = new JFrame("Test combo renderer");
JTable tbl = new JTable(DATA, COLS);
tbl.setRowHeight(20);
JComboBox<String> combo = new JComboBox<>(new String[] {"Book", "Music", "Film"});
combo.setUI(new BasicComboBoxUI());
combo.setBackground(tbl.getSelectionBackground());
combo.setForeground(tbl.getSelectionForeground());
tbl.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(combo));
frm.add(new JScrollPane(tbl));
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
}
So, what you need to do is:
combo.setUI(new BasicComboBoxUI());
combo.setBackground(tbl.getSelectionBackground());
combo.setForeground(tbl.getSelectionForeground());
Here is the screenshot of the corresponded program (for Windows):
This question already has an answer here:
JPopupMenu is not displayed on right click
(1 answer)
Closed 8 years ago.
I have written this code to add and delete a row in my table using popup menu, but this code neither delete nor add a row to the table when I click respective options (ADD and DELETE) on popup menu, please help.
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class B extends MouseAdapter {
JFrame frame = new JFrame();
Object rows[][] = new Object[5][3];
String colums[] = {"A","B","C"};
DefaultTableModel model = new DefaultTableModel(rows,colums);
JTable table = new JTable(model);
JScrollPane scroll = new JScrollPane(table);
JPopupMenu popup = new JPopupMenu();
JMenuItem item1 = new JMenuItem("ADD");
JMenuItem item2 = new JMenuItem("DELETE");
Object[] row = {"Column 1", "Column 2", "Column 3"};
public static void main(String arg[]) {
new B();
}
B() {
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
table.addMouseListener(this);
item1.addMouseListener(this);
item2.addMouseListener(this);
popup.add(item1);
popup.add(item2);
table.add(popup);
frame.add(scroll);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent click) {
if(click.getSource()==table && click.getButton()==3)
popup.show(table,click.getX(),click.getY());
else if(click.getSource()==item1)
model.addRow(row);
else if(click.getSource()==item2)
model.removeRow( table.rowAtPoint(click.getPoint()) );
}
}
Instead of comparing objects using == (to compare references of two components) you should use equals method . So change the following from:
click.getSource()==table
To
click.getSource().equals(table)
For my project i just want to show a dialogue box with JTable. On that i want to show a JCombobox with available staff based on row index. I tried the following coding,
for(int i=0;i<n;i++)
{
Object obj[] = new Object[4];
obj[0]=2,
obj[1]=3;
obj[2]=""; //Here combo appear.
obj[3]=3;
JComboBox aa = new JComboBox();
for(int j=0;j<m;j++)
{
aa.addItem(rs.getString(1));
aa.addItem(rs.getString(2));
}
table.getcolumnModel.getcolumn(2).setcellEditor(new DefaultCellEditor(aa));
model.addRow(obj);
}
if i use this output generated. But last rows combo value is present in all previous rows combo. Those different values are not in that. its totally same. But all other text fields are correctly displayed. What should i do here. thanking you...
Note: Here
aa.addItem(rs.getString(1));
aa.addItem(rs.getString(2));
is just for example. Actually it will return many number of values based on id.
You try to set editor to each row, but it's wrong, editor can be set to whole column. Read Concepts: Editors and Renderers. Instead of that implement your logic in getTableCellEditorComponent() method of TableCellEditor.
Simple example with different values for each row:
import java.awt.Component;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
public class TestFrame extends JFrame {
private DefaultComboBoxModel<String> model;
private Map<String, List<String>> keyVal;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
keyVal = new HashMap<>();
keyVal.put("1", Arrays.asList(new String[]{"a","b"}));
keyVal.put("0", Arrays.asList(new String[]{"c","d"}));
keyVal.put("2", Arrays.asList(new String[]{"e","f","g"}));
JTable t = new JTable(3,3);
t.getColumnModel().getColumn(0).setCellEditor(getEditor());
add(new JScrollPane(t));
}
private TableCellEditor getEditor() {
return new DefaultCellEditor(new JComboBox<String>(model = new DefaultComboBoxModel<String>())){
#Override
public Component getTableCellEditorComponent(JTable table,Object value, boolean isSelected, int row, int column) {
model.removeAllElements();
if(keyVal.containsKey(row+"")){
List<String> list = keyVal.get(row+"");
for(String s : list)
model.addElement(s);
}
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
};
}
public static void main(String args[]) {
new TestFrame();
}
}
Here's the idea: Let's say I have a class extending TableModel, with something like a List<List<String>> collection field. On an event, I want to clear out a JTable and re-add rows where one specific column is a combo box; the items in combo box n are the items in the List<String> from collection.get(n) in my list. So I'm iterating over collection adding rows, and I'm iterating over each collection.get(n) adding combo box items.
There are no event listeners. When a separate button is clicked I can work out what needs to happen as long as I can getSelectedIndex on each combo box.
I have spent two and a half hours turning my GUI into code spaghetti where I've extended virtually everything and I have maximum coupling on practically everything. I think I might even have two disjoint collections of JComboBox instances. I say this to stress that it would do absolutely no good for me to post any code I currently have.
I have read the oracle tutorial on JTable, all of these that strangely don't have an explanation I can understand.
So basically I just need an idea of what I need, because I'm not getting anywhere with the resources I've found.
So, basically, you need a TableCelLEditor that is capable of seeding a JComboBox with the rows from the available list, for example...
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.ArrayList;
import java.util.List;
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 TableCellEditor {
public static void main(String[] args) {
new TableCellEditor();
}
public TableCellEditor() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
List<List<String>> values = new ArrayList<>(25);
for (int row = 0; row < 10; row++) {
List<String> rowValues = new ArrayList<>(25);
for (int index = 0; index < 10; index++) {
rowValues.add("Value " + index + " for row " + row);
}
values.add(rowValues);
}
DefaultTableModel model = new DefaultTableModel(new Object[]{"Data"}, 10);
JTable table = new JTable(model);
table.setShowGrid(true);
table.setGridColor(Color.GRAY);
table.getColumnModel().getColumn(0).setCellEditor(new MyEditor(values));
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 MyEditor extends DefaultCellEditor {
private List<List<String>> rowValues;
public MyEditor(List<List<String>> rowValues) {
super(new JComboBox());
this.rowValues = rowValues;
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JComboBox cb = (JComboBox) getComponent();
List<String> values = rowValues.get(row);
DefaultComboBoxModel model = new DefaultComboBoxModel(values.toArray(new String[values.size()]));
cb.setModel(model);
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
}