i have a jtable where i can put some records but now i want to insert jbutton in place of that records
my code is given below
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public class ScrollableJTable {
public static void main(String[] args) {
new ScrollableJTable();
}
public ScrollableJTable() {
JFrame frame = new JFrame("Creating a Scrollable JTable!");
JPanel panel = new JPanel();
String data[][] = {
{
"001", "vinod", "Bihar", "India", "Biology", "65", "First"
},
};
panel.setLayout(new BorderLayout());
String col[] = {
"Roll", "Name", "State", "country", "Math", "Marks", "Grade"
};
JTable table = new JTable(data, col);
JTableHeader header = table.getTableHeader();
header.setBackground(Color.yellow);
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
JScrollPane pane = new JScrollPane(table);
panel.add(pane);
frame.add(pane);
frame.setSize(xSize, ySize);
table.setSize(xSize, ySize);
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
If you want to display a button is a column then you need to create a custom renderer and editor for the column. Read the section from the Swing tutorial on - Concepts: Editors and Renderers for some basic information.
Then check out Table Button Column for one approach.
Related
Example:
I have problem with table header. How can i remove this white border or change color of it?
My code:
JTableHeader header = table.getTableHeader();
header.setBackground(new Color(21, 25, 28));
header.setForeground(new Color(255, 117, 0));
header.setPreferredSize(new Dimension(10,30));
header.setBorder(new LineBorder(new Color(21,25,28),2));
Well you were almost there...
For the header you can do:
final DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setBorder(null);
header.setDefaultRenderer(renderer);
If you also want to remove the borders from the data cells also (practically removing the grid), then call:
table.setShowGrid(false);
Here is an assembled example of a JTable without any borders (except when the user selects a cell, then a border will appear around it temporarily):
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
public class Main {
private static void createAndShowGUI() {
final JFrame frame = new JFrame("Table without borders");
final JTable table = new JTable(new Object[][]{
new Object[]{"user", "user", "user"},
new Object[]{"user", "user", "user"},
new Object[]{"user", "user", "user"},
new Object[]{"user", "user", "user"},
new Object[]{"user", "user", "user"},
new Object[]{"user", "user", "user"}
}, new Object[]{"A", "B", "C"});
JTableHeader header = table.getTableHeader();
final Color dark = new Color(21, 25, 28),
orange = new Color(255, 117, 0);
table.setForeground(orange);
table.setBackground(dark);
header.setBackground(dark);
header.setForeground(orange);
final DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setBorder(null); //Remove border from the renderer (which is just a JLabel)...
//Apply the renderer to all header cells and all data cells:
header.setDefaultRenderer(renderer);
table.setDefaultRenderer(Object.class, renderer);
/*The follwing lines simply remove the border from the cell editor
(ie the component which draws each cell when the user edits its value):*/
//final JTextField editor = new JTextField();
//editor.setBorder(null);
//table.setCellEditor(new DefaultCellEditor(editor));
//header.setBorder(null); //Not needed.
table.setShowGrid(false); //Hide the grid (which is some extra border between cells).
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(Main::createAndShowGUI);
}
}
I've looked everywhere but can't seem to figure this out. I just want to pull out a cell's value from my JTable when a user clicks on it.
However at the moment I am getting -1 so I suppose double clicking results in no row being detected. Here is the code:
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.*;
import javax.swing.table.TableColumn;
public class CardLayoutExample {
private static JScrollPane scrollPane;
public static void main(String[] arguments) throws SQLException {
// main window
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame window = new JFrame("CardLayout Example");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(1500,800);
window.getContentPane().setLayout(new BorderLayout());
final CardLayout cardLayout = new CardLayout();
final JPanel cardPanel = new JPanel(cardLayout);
JPanel card3 = new JPanel();
cardPanel.add(card3,"All Patients");
String AllPatients="select * from tblPtDetails";
JTable tablePatientDt = new JTable(Bquery.buildTableModel(Bquery.resultQuery(AllPatients)));
tablePatientDt.setEnabled(false);
tablePatientDt.setPreferredScrollableViewportSize(new Dimension(1200, 400));
tablePatientDt.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
tablePatientDt.setRowHeight(30);
tablePatientDt.setAutoCreateRowSorter(true);
card3.add(tablePatientDt);
card3.add(new JScrollPane(tablePatientDt), BorderLayout.CENTER);
for (int i = 0; i < (tablePatientDt.getColumnCount()); i++) {
TableColumn columnPatients = null;
columnPatients = tablePatientDt.getColumnModel().getColumn(i);
columnPatients.setPreferredWidth(70); //sport column is bigger
}
tablePatientDt.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int row = tablePatientDt.getSelectedRow();
int column = tablePatientDt.getSelectedColumn();
//Object val= tablePatientDt.getModel().getValueAt(row, column);
//tablePatientDt.getModel().getValueAt(row, column);
//return tablePatientDt.getModel().getValueAt(row, column);
System.out.println(row);
JFrame newFrame = new JFrame();
newFrame.setTitle("Detail Screen");
newFrame.setVisible(true);
}
}
});
Your main problem is here:
tablePatientDt.setEnabled(false);
Because the table is not enabled, no cell or row can ever be selected, and so the selected row will always be -1. Solution: get rid of that line. Instead, if you don't want a cell to be editable on double click, override the JTable or its model and override the isCellEditable method:
e.g.,
// create your JTable model here:
DefaultTableModel model = ......
JTable tablePatientDt = new JTable(model){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
Other issues: don't add the JTable to more than one component as you're doing. That spells great risk for trouble since Swing components can be added to only one component at a time.
A side recommendation: in your future questions post only small compilable and runnable programs. Your code above cannot run since it has database dependencies that we don't have access to, and is also incomplete. In order to find your problem, I had to take your code and create a small runnable program with it, an mcve (please read the link):
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class CardLayoutExample {
private static JScrollPane scrollPane;
public static void main(String[] arguments) throws SQLException {
// main window
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame window = new JFrame("CardLayout Example");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// !! window.setSize(1500, 800);
window.getContentPane().setLayout(new BorderLayout());
final CardLayout cardLayout = new CardLayout();
final JPanel cardPanel = new JPanel(cardLayout);
JPanel card3 = new JPanel();
cardPanel.add(card3, "All Patients");
String AllPatients = "select * from tblPtDetails";
//!!
String[][] data = {{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}};
String[] columnNames = {"One", "Two", "Three"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
// !! JTable tablePatientDt = new JTable(Bquery.buildTableModel(Bquery.resultQuery(AllPatients)));
JTable tablePatientDt = new JTable(model){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// !! tablePatientDt.setEnabled(false);
tablePatientDt.setPreferredScrollableViewportSize(new Dimension(1200, 400));
tablePatientDt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tablePatientDt.setRowHeight(30);
tablePatientDt.setAutoCreateRowSorter(true);
// !! card3.add(tablePatientDt);
card3.add(new JScrollPane(tablePatientDt), BorderLayout.CENTER);
for (int i = 0; i < (tablePatientDt.getColumnCount()); i++) {
TableColumn columnPatients = null;
columnPatients = tablePatientDt.getColumnModel().getColumn(i);
columnPatients.setPreferredWidth(70); // sport column is bigger
}
tablePatientDt.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int row = tablePatientDt.getSelectedRow();
int column = tablePatientDt.getSelectedColumn();
// Object val= tablePatientDt.getModel().getValueAt(row,
// column);
// tablePatientDt.getModel().getValueAt(row, column);
// return tablePatientDt.getModel().getValueAt(row, column);
System.out.println(row);
JFrame newFrame = new JFrame();
newFrame.setTitle("Detail Screen");
newFrame.setVisible(true);
}
}
});
//!!
window.add(cardPanel);
window.pack();
window.setVisible(true);
}
}
But really this effort should be yours not mine, since we're all volunteers, and you're the one asking for volunteer help in solving a problem. So in the future we ask that you create your own mcve to go with your questions.
Also that detail window shouldn't be a JFrame but rather a JDialog.
i want a scrollpane on my GUI. The area, i want to have "scrollable" is a JPanel without any LayoutManager, because the content is something between static and dynamic... but maybe a part of my code will help
Here it is:
pane = getContentPane();
jpane = new JPanel();
// jpane.setBounds(0, 75, 680, 255);
jpane.setLayout(null);
jsp = new JScrollPane(jpane, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setBounds(0, 75, 680, 255);
jsp.setPreferredSize(new Dimension(680,255));
pane.add(jsp);
My JPanel will be filled with this piece of code...
for(int i = 0; i < Integer.parseInt(spaltenzahl.getText()); i++) {
JTextField spaltennamen_feld = new JTextField();
spaltennamen_feld.setBounds(10, 10+35*i, 150, 25);
spaltennamen_arraylist.add(spaltennamen_feld);
JComboBox<String> datentypen_box = new JComboBox<String>(types);
datentypen_box.setBounds(170, 10+35*i, 150, 25);
datentypen_arraylist.add(datentypen_box);
JComboBox<String> datenzusatz_box = new JComboBox<String>(comb);
datenzusatz_box.setBounds(330, 10+35*i, 100, 25);
datenzusatz_arraylist.add(datenzusatz_box);
jpane.add(spaltennamen_feld);
jpane.add(datentypen_box);
jpane.add(datenzusatz_box);
}
Problem: i can't add a screenshot of my GUI, cause of missing ehr... i forgot the name of this required things here ^_^
But i the real problem is: overflowing content won't be displayed on my JPanel and my ScrollPane does not scroll. Any idea?
Thanks alot :)
Your solution is none of the above. I think that you want to use a JTable, one with three columns, the last two whose editor is a JComboBox.
Edit
For example:
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Foo2 {
private static void createAndShowGui() {
String[] columns = {"Spaltennamen", " Datentypen", "Datenzusatz"};
String[] dataStrings1 = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
String[] dataStrings2 = {"One", "Two", "Three", "Four", "Five"};
Random random = new Random();
DefaultTableModel model = new DefaultTableModel(columns, 0);
int spaltenzahl = 10; // this can change
for (int i = 0; i < spaltenzahl; i++) {
Vector<String> rowData = new Vector<>();
rowData.add("Row Number " + (i + 1));
rowData.add(dataStrings1[random.nextInt(dataStrings1.length)]);
rowData.add(dataStrings2[random.nextInt(dataStrings2.length)]);
model.addRow(rowData);
}
JTable table = new JTable(model);
table.getColumn(columns[1]).setCellEditor(new DefaultCellEditor(new JComboBox<>(dataStrings1)));
table.getColumn(columns[2]).setCellEditor(new DefaultCellEditor(new JComboBox<>(dataStrings2)));
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I have written this simple program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class JcomboboxJtableDemo extends JPanel
implements ActionListener {
private DefaultTableModel tableModel;
JTable table = new JTable (tableModel);
private JScrollPane scrollpaneTable = new JScrollPane( table );
private JPanel PaneBottoniTabella = new JPanel( );
public JcomboboxJtableDemo() {
super(new BorderLayout());
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
JComboBox comboBox = new JComboBox(petStrings);
comboBox.setSelectedIndex(4);
tableModel = CreateTableModel();
tableModel.insertRow( 0, new Object[] {"Header col1", ""} );
tableModel.insertRow( 0, new Object[] {petStrings[0], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[1], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[2], ""} );
tableModel.insertRow( 0, new Object[] {petStrings[3], ""} );
tableModel.setValueAt("Header col2", 0, 1);
DefaultCellEditor editor = new DefaultCellEditor(comboBox);
table.getColumnModel().getColumn(0).setCellEditor(editor);
table.getColumnModel().getColumn(1).setCellEditor(editor);
//Lay out the demo.
add(comboBox, BorderLayout.PAGE_START);
add(table, BorderLayout.PAGE_END);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
private final DefaultTableModel CreateTableModel () {
DefaultTableModel modello = new DefaultTableModel( new Object[] { "Col1","Col2" }, 0 ) {
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
};
table.setModel(modello);
return modello;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ComboBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new JcomboboxJtableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I you try to run it you will see that there is a problem in showing correctly the JComboBox components in the second column, in the first column the are correctly shown and you can see each selected item as set in the code, instead in the second column there are some problems: none on the relative cell.
Could you tell me why? How can I solve the problem?
Thanks
You're using the same JComboBox component for both ColumnModel columns which in turn share the same ComboBoxModel. Any change in the selected item from one column will be reflected in the other column. Create a second combobox
JComboBox comboBox2 = new JComboBox(petStrings);
...
table.getColumnModel().getColumn(1).setCellEditor(editor2);
so that any changes can occur independently in either column.
I have a set of panels across a layered pane. I need a separator between to separate the sideBar from the topBar and the tabbedPanel. I left a buffer of 10 pixels for it to be placed. unfortunately, possibly due to it being a JLayeredPane, I canot get it to view.
Is there a way to define the separator's X location? as this should solve it. Either way, here's a sample of the code, which I've removed most information from.
Alternatively, offer a different solution entirely, so long as I can get a defined split from the sideBar and other two panels. I've already tried to apply the BorderLayout.WEST to the sideBar, but due to it being a JLayeredPane, it gives me errors.
lPane = new JLayeredPane();
lPane.setBounds(0, 0, 1024, 768);
calendarFrame = new JFrame ("Calendar Frame");
calendarFrame.setPreferredSize(new Dimension(1024, 768));
calendarFrame.setLayout(null);
//Prepare side bar
sideBar = new JPanel ();
sideBar.setLayout(null);
sideBar.setBounds(0, 0, 210, 768);
//Prepare top bar
topBar = new JPanel ();
topBar.setLayout(null);
topBar.setBounds(220, 0, 774, 50);
//Create tabbed pane
tabbedPane = new JTabbedPane();
tabbedPane.setBounds(220, 50, 774, 700);
//Tab code here, but not needed for questuion
calendarFrame.add(lPane, BorderLayout.CENTER);
lPane.add(sideBar, new Integer(0), 0);
lPane.add(Box.createHorizontalStrut(5));
lPane.add(new JSeparator(SwingConstants.VERTICAL));
lPane.add(Box.createHorizontalStrut(5));
lPane.add(topBar, new Integer(1), 0);
lPane.add(tabbedPane, new Integer(2), 0);
EDIT:
if you want to create fixed 10pixels gap,
you can use
EmptyBorder (or CompoundBorder)
BorderLayout(int horizontalGap, int verticalGap) or GridLayout(int rows, int cols, int hgap, int vgap)
just my curiosity are you ...
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class EditableListExample extends JFrame {
private static final long serialVersionUID = 1L;
public EditableListExample() {
super("Editable List Example");
String[] data = {"a", "b", "c", "d", "e", "f", "g"};
JList list = new JList(data);
JScrollPane scrollList = new JScrollPane(list);
scrollList.setMinimumSize(new Dimension(100, 80));
Box listBox = new Box(BoxLayout.Y_AXIS);
listBox.add(scrollList);
listBox.add(new JLabel("JList"));
DefaultTableModel dm = new DefaultTableModel();
Vector<String> dummyHeader = new Vector<String>();
dummyHeader.addElement("");
dm.setDataVector(strArray2Vector(data), dummyHeader);
JTable table = new JTable(dm);
table.setShowGrid(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollTable = new JScrollPane(table);
scrollTable.setColumnHeader(null);
scrollTable.setMinimumSize(new Dimension(100, 80));
Box tableBox = new Box(BoxLayout.Y_AXIS);
tableBox.add(scrollTable);
tableBox.add(new JLabel("JTable"));
Container c = getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.X_AXIS));
c.add(listBox);
c.add(new JSeparator(SwingConstants.VERTICAL));
//c.add(new JLabel("test"));
//c.add(new JSeparator(SwingConstants.HORIZONTAL));
c.add(tableBox);
pack();
setVisible(true);
}
private Vector<Object> strArray2Vector(String[] str) {
Vector<Object> vector = new Vector<Object>();
for (int i = 0; i < str.length; i++) {
Vector<Object> v = new Vector<Object>();
v.addElement(str[i]);
vector.addElement(v);
}
return vector;
}
public static void main(String[] args) {
final EditableListExample frame = new EditableListExample();
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}