Changing JTable header height - java

Happy new year everyone, i've a problem chaning the height of a JTable header, I appreciate if someone can help. The Method I'am using is changing also the backgroundcolor etc.
Thanks
public static void ChangeJTableBackgroundColor(JTable InTable){
JTable mytable = InTable;
Color mycolor = new Color(248, 201, 171);
mytable.setOpaque(true);
mytable.setFillsViewportHeight(true);
mytable.setBackground(mycolor);
Color mycolorhead = new Color(249, 168, 117);
mytable.getTableHeader().setBackground(mycolorhead);
mytable.getTableHeader().setPreferredSize(new Dimension(1,50));
}

There are lots of ways you "might" increase the height of the header, which you choose will depend on what you want to achieve. One thing to keep in mind though, is trying to find a solution which respects the diverse rendering environments which you program might need to run in.
You could...
Simple change the font size. This might sound silly, but you'd be surprised at how simple it really is, for example...
DefaultTableModel model = new DefaultTableModel(10, 10);
JTable table = new JTable(model);
JTableHeader header = table.getTableHeader();
header.setFont(header.getFont().deriveFont(30f));
You could...
Take advantage of Swing's inbuilt HTML support. This example sets up a HTML table with a defined cell height
DefaultTableModel model = new DefaultTableModel(10, 10);
JTable table = new JTable(model);
TableColumnModel columnModel = table.getColumnModel();
String prefix = "<html><body><table><tr><td height=100>";
String suffix = "</td></tr></table></body><html>";
for (int col = 0; col < columnModel.getColumnCount(); col++) {
TableColumn column = columnModel.getColumn(col);
String text = prefix + Character.toString((char)('A' + col)) + suffix;
System.out.println(text);
column.setHeaderValue(text);
}
You could...
Just supply your own TableCellRenderer as the default cell renderer for the table header. This is a little tricky, as it's difficult to mimic the default renderer used by the current look and feel and the UIManager doesn't help. Instead, you need to consider using a "proxy" approach, where by you apply the changes you need to the existing header renderer instead.
DefaultTableModel model = new DefaultTableModel(10, 10);
JTable table = new JTable(model);
JTableHeader header = table.getTableHeader();
TableCellRenderer proxy = header.getDefaultRenderer();
header.setDefaultRenderer(new TableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component comp = proxy.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (comp instanceof JLabel) {
JLabel label = (JLabel) comp;
label.setBorder(new CompoundBorder(label.getBorder(), new EmptyBorder(50, 0, 50, 0)));
}
return comp;
}
});
As far as solutions go, this is probably my preferred, as it takes into account more of the variables involved in determine the preferred size of the column header itself

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.table.*;
public class TableHeaderHeightTest {
private static int HEADER_HEIGHT = 32;
private JTable makeTable() {
JTable table = new JTable(new DefaultTableModel(2, 20));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
return table;
}
public JComponent makeUI() {
JPanel p = new JPanel(new GridLayout(2,1));
JTable table1 = makeTable();
//Bad: >>>>
JTableHeader header = table1.getTableHeader();
//Dimension d = header.getPreferredSize();
//d.height = HEADER_HEIGHT;
//header.setPreferredSize(d); //addColumn case test
header.setPreferredSize(new Dimension(100, HEADER_HEIGHT));
p.add(makeTitledPanel("Bad: JTableHeader#setPreferredSize(...)", new JScrollPane(table1)));
//<<<<
JTable table2 = makeTable();
JScrollPane scroll = new JScrollPane(table2);
scroll.setColumnHeader(new JViewport() {
#Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
d.height = HEADER_HEIGHT;
return d;
}
});
// //or
// table2.setTableHeader(new JTableHeader(table2.getColumnModel()) {
// #Override public Dimension getPreferredSize() {
// Dimension d = super.getPreferredSize();
// d.height = HEADER_HEIGHT;
// return d;
// }
// });
p.add(makeTitledPanel("Override getPreferredSize()", scroll));
final List<JTable> list = Arrays.asList(table1, table2);
JPanel panel = new JPanel(new BorderLayout());
panel.add(p);
panel.add(new JButton(new AbstractAction("addColumn") {
#Override public void actionPerformed(ActionEvent e) {
for(JTable t: list) {
t.getColumnModel().addColumn(new TableColumn());
JTableHeader h = t.getTableHeader();
Dimension d = h.getPreferredSize();
System.out.println(d);
}
}
}), BorderLayout.SOUTH);
panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
return panel;
}
private static JComponent makeTitledPanel(String title, JComponent c) {
JPanel p = new JPanel(new BorderLayout());
p.add(c);
p.setBorder(BorderFactory.createTitledBorder(title));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TableHeaderHeightTest().makeUI());
f.setSize(320, 320);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
Try this

Related

JScrollPane sizing Issue [duplicate]

I am using the following code to create JTable inside JScrollPane to show column headers
JTable won't show column headers
String[] columnNames = {"header1", "header2", "header2", "header3"};
Object[][] data = new Object[num][4];
//feed values into data using for
JTable chart = new JTable(data, columnNames);
chart.setShowVerticalLines(false);
chart.setEnabled(false);
chart.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane sp = new JScrollPane(chart);
sp.setPreferredSize(new Dimension(width, chart.getHeight() + 5));
panel.add(sp);
The problem is that I need to compute a height for JScrollPane so the whole JTable can be visible and JScrollBars won't appear. How can I do that?
num changes from 2 to 4 and if it is 4 then scroll bars appear. width is fixed.
The basic approach is
JTable is-a Scrollable which unfortunately doesn't do too well in calculating a prefScrollable, so you have to do it yourself
either use a LayoutManager which lays out all at their pref (f.i. FlowLayout), or implement max in JTable (if you use a resizing but max-respecting manager like BoxLayout)
JScrollPane is-a validationRoot, so the revalidate must happen on the parent of the scrollPane
Something like:
final JTable table = new JTable(10, 5) {
#Override
public Dimension getPreferredScrollableViewportSize() {
Dimension dim = super.getPreferredScrollableViewportSize();
// here we return the pref height
dim.height = getPreferredSize().height;
return dim;
}
};
final JComponent content = new JPanel();
content.add(new JScrollPane(table));
Action add = new AbstractAction("add row") {
#Override
public void actionPerformed(ActionEvent e) {
((DefaultTableModel) table.getModel()).addRow(new Object[]{});
content.revalidate();
}
};
converting my comments here to the answer, crazy, crazy, really crazy, everything could be complicating the simple things, by assuming that every rows have got the same size, long methods for columnmodel, expanding methods, have to add column renderer/editor, etc..
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
public class TablePreferredSize {
private String[] head = {"One", "Two", "Three", "Four", "Five", "Six"};
private String[][] data = new String[25][6];
private JTable table = new JTable(data, head);
private DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
private TableColumn column = new TableColumn();
private int rowHeight = 23;
private int rowWidth = 0;
public TablePreferredSize() {
table.setRowHeight(23);
table.setIntercellSpacing(new Dimension(1, 1));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
column = new TableColumn();
column.setModelIndex(0);
column.setHeaderValue("One");
column.setPreferredWidth(250);
columnModel.addColumn(column);
rowWidth += column.getPreferredWidth();
column = new TableColumn();
column.setModelIndex(1);
column.setHeaderValue("Two");
column.setPreferredWidth(120);
columnModel.addColumn(column);
rowWidth += column.getPreferredWidth();
column = new TableColumn();
column.setModelIndex(2);
column.setHeaderValue("Three");
column.setPreferredWidth(80);
columnModel.addColumn(column);
rowWidth += column.getPreferredWidth();
column = new TableColumn();
column.setModelIndex(3);
column.setHeaderValue("Four");
column.setPreferredWidth(120);
columnModel.addColumn(column);
column = new TableColumn();
column.setModelIndex(4);
column.setHeaderValue("Five");
column.setPreferredWidth(70);
columnModel.addColumn(column);
column = new TableColumn();
column.setModelIndex(5);
column.setHeaderValue("Six");
column.setPreferredWidth(30);
columnModel.addColumn(column);
table.setColumnModel(columnModel);
table.setPreferredScrollableViewportSize(new Dimension(rowWidth, 12 * rowHeight));
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("Table PreferredSize");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TablePreferredSize t = new TablePreferredSize();
}
});
}
}
What if you call ?
sp.getColumnHeader().getHeight()

How to create a custom JTable?

I am making a chat application in Java. They can add friends and chat with them.
Here is my add friend JFrame idea:
I tried to google search Multi jpanel in one jscrollpane but I found nothing. I ended up with custom JTable. I want to create a custom JTable which have JLabels in different position in each slot. Users can just select a slot in JTable, then they can use the JButton below to chat with them.
Is it possible to do this in Java. Is yes, please share your idea. Thanks.
Here is a proposal. But it contains some flaws yet
Size propagation is fiexed (may be better client or server based sizing)
No event delegation to underlying Component
Performance, because heavyweight panel instances are created frequently inside paint loop
But here is how it can be done. The code is separated into parts.
A value class
Just a simple class to represent the date inside your panels for each cell.
class Value {
public final String text;
public final boolean flag;
public Value(String text, boolean flag) {
this.text = text;
this.flag = flag;
}
}
My individual panel class
The representation can be modelled within a gui editor like google's window builder. This panel makes use of the value and displays it accordingly.
public class MyPanel extends JPanel {
public MyPanel(Value v) {
JLabel lblNewLabel = new JLabel(v.text);
add(lblNewLabel);
JCheckBox chckbxSomeValue = new JCheckBox("some value");
chckbxSomeValue.setSelected(v.flag);
add(chckbxSomeValue);
}
}
A table cell renderer class
Just returns some panel instance showing up the desired values.
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
class MyPanelCellRenderer implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return new MyPanel((Value)value); // maybe performance problem
}
}
A custom table model
import javax.swing.table.DefaultTableModel;
class MyTableModel extends DefaultTableModel {
public MyTableModel() {
super(new Object[][] {
new Object[] { 1, new Value("asdf", true) },
new Object[] { 2, new Value("qwer", false) } },
new String[] {"Id", "MyPanel" });
}
Class[] columnTypes = new Class[] { Integer.class, Value.class };
MyTableModel(Object[][] data, Object[] columnNames) {
super(data, columnNames);
}
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
}
A frame class
import java.awt.BorderLayout;
public class MyFrame {
JFrame frame;
private JTable table;
public MyFrame() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable();
table.setModel(new MyTableModel());
table.setFillsViewportHeight(true);
table.getColumnModel()
.getColumn(1)
.setCellRenderer(new MyPanelCellRenderer());
table.setRowHeight(40); // static sizing
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(table);
}
}
Main Function
import java.awt.EventQueue;
public class MyApp {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame window = new MyFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
The final result
The panel MyPanel is created using eclipse and google's window builder
This is a completely different approach using neither a table nor a list. It uses panels as items arranged as a list inside of another panel. This solution doesn't requires any further modification to delegate any events to the underlying controls. The events are processed natively. The idea comes from this post. I have separated the logic into two parts for now.
JPanelList class
This class is a JPanel and maintains a list of such. ATM they can be added using the methods addPanel and addPanels.
public class JPanelList extends JPanel {
private static final long serialVersionUID = 1L;
private JPanel mainList;
private List<JPanel> panels = new ArrayList<JPanel>();
public JPanelList() { this(new ArrayList<JPanel>()); }
public JPanelList(List<JPanel> panels) {
setLayout(new BorderLayout());
mainList = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
mainList.add(new JPanel(), gbc);
add(new JScrollPane(mainList));
addPanels(panels);
}
public void addPanels(List<JPanel> panels) {
for (JPanel panel : panels)
addPanel(panel);
}
public void addPanel(JPanel panel) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
mainList.add(panel, gbc, 0);
panels.add(panel);
validate();
repaint();
}
}
JListFrame test class with main function
public class JPanelListFrame {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JPanelListFrame window = new JPanelListFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public JPanelListFrame() {
frame = new JFrame();
frame.setBounds(100, 100, 210, 192);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanelList panelList = new JPanelList();
frame.getContentPane().add(panelList, BorderLayout.CENTER);
JButton btnAddMypanel = new JButton("Add MyPanel");
btnAddMypanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// just add a MyPanel with a Value containing a
// "asdf" and a random boolean
panelList.addPanel(new MyPanel(new Value("asdf",
(int) (2 * Math.random()) % 2 == 0)));
}
});
panelList.add(btnAddMypanel, BorderLayout.SOUTH);
}
}
One drawback with this solution is that the selection mechanics are lost. When selecting elements is a key requirement maybe a JList might be more appropriate. Another thing is that the items are not rendered as they would be rendered inside a JList or JTable e.g. using fancy borders. This can be solved by somehow adding a border decorator before adding the panels into the mainList of the JPanelList.

JTable aren't refreshing when selecting from Combobox

The scrollPane table isn't refreshing for every time I selected something from the combo. Initially it has data but after I selected something, the data is removed successfully but new data isn't populating in
public void ConsultFrame(String id, String name, String ic){
GenerateMed("dp-000"); // to begin the scrollpane filled with Fever's medicine
JButton proc = new JButton("Proceed");
JButton addmed = new JButton(">>");
selected = new JTable(data, columnNames){
#Override
public boolean isCellEditable(int row,int column){
switch(column){
case 0:
return false;
case 1:
return false;
default: return true;
}
}};
selectedPane = new JScrollPane(selected);
//Dispensary's category combobox related
disp = dbDisp.getDispensary();
final JComboBox cBox = new JComboBox();
for(int count=0; count<disp.size(); count++)
cBox.addItem(disp.get(count).getDSP_desc());
cBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
for(int count=0; count<disp.size(); count++){
if(cBox.getSelectedItem().equals(disp.get(count).getDSP_desc())){
System.out.println(disp.get(count).getDSP_ID());
GenerateMed(disp.get(count).getDSP_ID());
break;
}
}
}
});
JTextArea tArea = new JTextArea(5, 30);
JScrollPane desc = new JScrollPane(tArea);
tArea.setLineWrap(true);
desc.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
JPanel info = new JPanel();
info.setLayout(new FlowLayout(FlowLayout.LEFT));
info.add(new JLabel("<html>Patient's ID : " + id + "<br>Patient's Name: " + name + "<br>Patient's IC : " + ic + "<br><br>Medical Description : </html>"));
info.add(desc);
JPanel medSelect = new JPanel();
medSelect.setLayout(new GridLayout(1,2));
medSelect.add(scrollPane);
medSelect.add(selectedPane);
JPanel medic = new JPanel();
medic.setLayout(new BorderLayout());
medic.add(cBox, BorderLayout.NORTH);
medic.add(medSelect, BorderLayout.CENTER);
medic.add(proc, BorderLayout.SOUTH);
JPanel all = new JPanel();
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(Calendar.getInstance().getTime());
title = BorderFactory.createTitledBorder(timeStamp);
title.setTitleJustification(TitledBorder.RIGHT);
all.setBorder(title);
all.setLayout(new GridLayout(2,1));
all.add(info);
all.add(medic);
JFrame consult = new JFrame();
consult.setTitle(name + "'s consultation");
consult.setResizable(false);
consult.setVisible(true);
consult.setSize(500, 460);
consult.setLocationRelativeTo(null);
consult.add(all);
}
This is where my Combobox's is heading as soon as something is selected and I've tried repaint & revalidate
public void GenerateMed(String dps_id){
if (tModel != null) {
for (int i = tModel.getRowCount() - 1; i > -1; i--)
tModel.removeRow(i);
}
tModel = dbMed.getDPSMedicine(dps_id);
tModel.fireTableDataChanged();
table = new JTable(tModel){
#Override
public boolean isCellEditable(int row,int column){
return false;
}};
table.setShowGrid(false);
table.setShowHorizontalLines(false);
table.setShowVerticalLines(false);
//Table customization
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.changeSelection(0, 0, false, false);
scrollPane = new JScrollPane(table);
scrollPane.repaint();
scrollPane.revalidate();
}
scrollPane = new JScrollPane(table);
The above line of code creates a new scrollPane, but doesn't add the scrollPane to the frame.
However, there is no need to even create a new JTable or a new JScrollPane. Get rid of all the code.
Instead you just change the model of your JTable by using:
table.setModel( dbMed.getDPSMedicine(dps_id) );
So basically your method becomes one line of code.
Also, use proper method names. Method names should NOT start with an upper case character.

CellRenderer - making multiple cells bold

I would like to make multiple cells bold, I have arraylist with the cell names that should be bold but doesn't seem to work. My Arraylist with the cells that I want to bold is called bibNumbers, so far tried converting the arralist into array and putting the if statement into a loop and loop results into bolding variable
//edit
added example, so now id want all the 0's and 1's in the column 2 to be bold.
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class as extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
private ArrayList<String> ShadowBibNumber;
/**
* Launch the application.
*/
public static void main(String[] args) {
as frame = new as();
frame.setVisible(true);
}
/**
* Create the frame.
*/
public as() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
ShadowBibNumber = new ArrayList<String>();
ShadowBibNumber.add("0");
ShadowBibNumber.add("1");
JLabel lblNewLabel = new JLabel("New label");
contentPane.add(lblNewLabel, BorderLayout.NORTH);
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("column 0");
tableModel.addColumn("column 1");
tableModel.addColumn("column 2");
tableModel.addColumn("column 3");
tableModel.addColumn("column 4");
new JScrollPane(table);
table = new JTable(tableModel);
table.setEnabled(false);
table.setPreferredScrollableViewportSize(new Dimension(200, 100));
JScrollPane scrollPaneForTable = new JScrollPane(table);
contentPane.add(scrollPaneForTable, BorderLayout.CENTER);
for (int i = 0; i < 20; ++i) {
tableModel
.addRow(new Object[] { i, i, i, i, i });
}
table.getColumn("column 2").setCellRenderer(new boldRenderer());
}
class boldRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
Component cellComponent = super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
for (Object x: ShadowBibNumber) {
if (table.getValueAt(row, 2).equals(x)) {
cellComponent.setFont(cellComponent.getFont().deriveFont(
Font.BOLD));
} else {
cellComponent.setFont(cellComponent.getFont().deriveFont(
Font.PLAIN));
}
}
return cellComponent;
}
} }

How to add JButton after a JTable

I have a JTable with some data like this SSCCE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.*;
import java.awt.Color;
class kanji{
public static void main(String args[]){
JFrame frame = new JFrame("Kanji");
JPanel pane = new JPanel();
JTable table = new JTable();
pane.setLayout(new BorderLayout());
JButton agreg = new JButton("Agregar");
DefaultTableModel model = new DefaultTableModel(get_data(), get_header());
JFrame hk = new JFrame("Historial de Significados");
Image icon = Toolkit.getDefaultToolkit().getImage("JLPT.jpg");
ImageIcon ima = new ImageIcon("JLPT.jpg");
table = new JTable(model){
#Override
public boolean isCellEditable(int row, int col){
switch(col){
case 0:
return false;
case 1:
return false;
case 2:
return true;
default:
return false;
}
}
#Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Boolean.class;
default:
return Boolean.class;
}
}
};
DefaultTableCellRenderer r = new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setForeground(Color.blue);
setHorizontalAlignment(JLabel.CENTER);
setFont(new Font("Microsoft JhengHei", Font.BOLD, 50));
return this;
}
};
DefaultTableCellRenderer r2 = new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setHorizontalAlignment(JLabel.LEFT);
setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
return this;
}
};
table.getColumnModel().getColumn(0).setCellRenderer(r);
table.getColumnModel().getColumn(1).setCellRenderer(r2);
TableColumn column = null;
for (int i = 0; i < 3; i++) {
column = table.getColumnModel().getColumn(i);
if (i==0) {
column.setMaxWidth(80);
column.setMinWidth(80);
}
else{
if(i==1){
column.setPreferredWidth(470);
}
else{
column.setMaxWidth(50);
column.setMinWidth(50);
}
}
}
table.setRowHeight(table.getRowHeight()+70);
table.setModel(model);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane scroll = new JScrollPane(table);
pane.add(scroll, BorderLayout.CENTER);
pane.add(agreg, BorderLayout.SOUTH);
frame.add(pane);
frame.setTitle("Historial de Significados");
frame.setSize(1350, 700);
frame.setIconImage(icon);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scroll.setViewportView(table);
}
public static Object [][]get_data(){
Object data[][] = new Object[][]{
{"\u4e00", "Uno, 1", true},
{"\u4e01", "Uno, 1", true},
{"\u4e02", "Uno, 1", true},
{"\u4e03", "Uno, 1", true},
{"\u4e04", "Uno, 1", true},
{"\u4e05", "Uno, 1", true},
{"\u4e06", "Uno, 1", true},
{"\u4e07", "Uno, 1", true},
{"\u4e08", "Uno, 1", true},
{"\u4e09", "Uno, 1", true}
};
return data;
}
public static String []get_header(){
String header [] = new String[]{"KANJI", "SIGNIFICADO", "Agregar"};
return header;
}
}
But I want to add 3 JButton after JTable is created, I want to have a JTable that don't take all JFrame size, in my code I get a Button but I want to have the possibility to set buttons bounds.
I've tried adding a JPanel and with another try with "setPreferredSize" where JScrollPane don't work, I mean I doesn't appear so I can't see all table content; and I also tried with "setSize" that doesn't work for me.
Maybe I have to make a second panel or something like that, I hope you can help me solving this issue.
I guess an Image says more than 1,000 words, so:
This is what I get and have and what I want to have
So in plain english, all I want to know is how to render table and add button at the bottom after rendered table (but I don't want buttons to have all the frame width, I want them away from table, not together as I have them and with the possibility to change their size and position).
private void createUI() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
final JTable table = new JTable(10, 4);
JPanel btnPnl = new JPanel(new BorderLayout());
JPanel topBtnPnl = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JPanel bottombtnPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
topBtnPnl.add(new JButton("Select All"));
bottombtnPnl.add(new JButton("Cancel"));
bottombtnPnl.add(new JButton("Add Selected"));
btnPnl.add(topBtnPnl, BorderLayout.NORTH);
btnPnl.add(bottombtnPnl, BorderLayout.CENTER);
table.getTableHeader().setReorderingAllowed(false);
frame.add(table.getTableHeader(), BorderLayout.NORTH);
frame.add(table, BorderLayout.CENTER);
frame.add(btnPnl, BorderLayout.SOUTH);
frame.setTitle("JTable Example.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
CheckABunch is an example that shows how to update the TableModel based on the current selection.
You could take a look at GridLayout.
In short I've made some changes to your class, and I've got this:
First group all JButtons into a JPanel, which have a GridLayout inside
Also, your JFrame container must have a BorderLayout
So you need add each button to the auxiliary pane and at the end add both JPanels to the frame.
Here's the code:
//Another import sentences
import java.awt.GridLayout;
class kanji{
public static void main(String args[]){
// More code goes here
JPanel allowedOperations = new JPanel(new GridLayout(2, 2));
pane.setLayout(new BorderLayout());
// More code goes here
// All buttons are grouped here
allowedOperations.add(new JButton()); // Here's a trick
allowedOperations.add(agreg);
allowedOperations.add(new JButton("Save selected"));
allowedOperations.add(new JButton("Cancel"));
// Add the pane object to the frame
frame.add(pane, BorderLayout.CENTER);
// And finally add the allowedOperations object to the frame
frame.add(allowedOperations, BorderLayout.SOUTH);
// More code goes here
} //End class
I've just posted the modifications, so you need to group the whole class.
I know it isn't the best approach, but you can improve your code from here. Also note you can create your buttons before added to the allowedOperations pane, as the agreg button

Categories