Add a title to a JTable - java

I have a JTable which is created using a TableModel JTable t = new JTable(tableModel) I want to add a title to it. I was hoping for something like t.setTitle(graphTitle); but i cant find anything on that lines. I dont mind if the title is on top or below the table.
I was using JLabels but it just looks messy.
Can anyone help?
Cheers in advance

Another option you could consider is enclosing the JTable in a JPanel and setting a TitledBorder to that JPanel.
Like this:
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class TableTitle
{
public TableTitle ()
{
JFrame frame = new JFrame ();
frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel ();
panel.setBorder (BorderFactory.createTitledBorder (BorderFactory.createEtchedBorder (),
"Table Title",
TitledBorder.CENTER,
TitledBorder.TOP));
JTable table = new JTable (3, 3);
panel.add (table);
frame.add (panel);
frame.setLocationRelativeTo (null);
frame.pack ();
frame.setVisible (true);
}
public static void main (String[] args)
{
SwingUtilities.invokeLater (new Runnable ()
{
#Override public void run ()
{
TableTitle t = new TableTitle ();
}
});
}
}
It looks like this:

You would have to add it when you instantiate your DefaultTableModel:
String data[][] = {{"Vinod","MCA","Computer"},
{"Deepak","PGDCA","History"},
{"Ranjan","M.SC.","Biology"},
{"Radha","BCA","Computer"}};
String col[] = {"Name","Course","Subject"};
DefaultTableModel model = new DefaultTableModel(data,col);
table = new JTable(model);
If it already exists, you can do something like this:
ChangeName(table,0,"Stu_name");
ChangeName(table,2,"Paper");
public void ChangeName(JTable table, int col_index, String col_name){
table.getColumnModel().getColumn(col_index).setHeaderValue(col_name);
}
Courtesy of RoseIndia.net
Hope that helps.

You can also add your title the JScrollPane which inscribes jtable in it.
Code:
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(BorderFactory.createTitledBorder ("Table Title"));

I don't think you have much options here. JTable has no functionality to add a titlebar.
So using JLabel or other components is your only option.
Try putting the JTable in a JTabbedPane.

Related

Struggling with the append method for JTextArea

This is the code I am struggling with. It is refusing to amend the JTextArea with the new text. I create the window and set it to visible in the main function of the project.
Thanks ahead.
EDIT:
By refusing, I mean the JTextArea will simply not display the text. It just stays empty. I'm not getting and error or exception. It is all logical.
class Window extends JFrame{
protected JTextArea text;
public Window() {
setTitle("Create a list of names");
setSize(500,400);
Container containerPane = getContentPane();
JPanel jp = new JPanel();
text = new JTextArea(10,50);
text.setPreferredSize(new Dimension(256,256) );
text.setEditable(false);
JScrollPane scrollText = new JScrollPane(text);
scrollText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
jp.add(scrollText);
containerPane.add(jp, BorderLayout.CENTER);
text.append("Test");
}
public static void main(String[] args) {
Window w = new Window();
w.setVisible(true);
}
}
The column width of 50 is greater than the width of the frame so the added text appears offscreen. Reduce its value to fit the parent window
textArea = new JTextArea(10, 35);
Don't use setPrerredSize. Let the layout manager do its job and call pack after all components have been added.

Managing dynamically added JCheckBoxes to JScrollPane

I am working on the functionality of adding JCheckBox to Panel and then adding that Panel to JScrollPane. So far i am done with adding different JCheckBox dynamically to Panel but when i add that same Panel to JScrollPane, it does not shows the JCheckBoxes to JScrollPane
Q.1 What might be the possible reason for same thing not appearing in JScrollPane?
Q.2 Even if i added JCheckBox to Panel and then adding that Panel to JScrollPane how do i manage there setSelected functionality i mean how i can add the ActionListener to that dynamically added JCheckBox?
Note: I am using a AbsoluteLayout for Panel
Use for example GridLayout (1 column and multiple rows).
Keep array (or list) of the checkboxes. Go through the list adding ActionListener or you can get the main panel's children components, iterate through them casting to JCheckBox and add the listener.
The worst way is to define preferred size for the panel with AbsoluteLayout.
AbsoluteLayout is not a good solution but with fixed size it should work.
Are you calling revalidate on your panel object after you added checkbox?
As for Q2 you can store added checkboxes in a Vector or HashMap ( depends what logic is involved ) and then you can create custom ActionListener that implements mentioned interface.
What is more that you can pass reference of your panel to your custom ActionListener and within it's actionPerformed use that reference to call methods on the panel which stores vector of your checkboxes.
Here is my quick example of what I am talking about:
package pkg;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
class AddCheckBoxAction implements ActionListener{
CheckBoxPanel panel;
public AddCheckBoxAction(CheckBoxPanel panel){
this.panel = panel;
}
#Override
public void actionPerformed(ActionEvent arg0) {
panel.addNewCheckBox();
}
}
class CheckBoxAction implements ActionListener{
private int id;
CheckBoxAction(int id){
this.id = id;
}
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("CheckBox "+this.id+" was clicked");
}
}
class CheckBoxPanel extends JPanel{
private JButton addCheckBox = new JButton("Add CheckBox");
private Vector<JCheckBox> checkBoxes = new Vector<JCheckBox>();
public CheckBoxPanel(){
addCheckBox.addActionListener(new AddCheckBoxAction( this ) );
add(addCheckBox);
}
public void addNewCheckBox() {
JCheckBox chBox = new JCheckBox("CheckBox "+( this.checkBoxes.size()+1 ));
chBox.addActionListener(new CheckBoxAction(this.checkBoxes.size()+1));
this.checkBoxes.add(chBox);
add(chBox);
this.revalidate();
}
}
public class DynamicCheckBoxTest {
/**
* #param args
*/
public static void main(String[] args) {
CheckBoxPanel chD = new CheckBoxPanel();
JFrame mainFrame = new JFrame();
JScrollPane scrollP = new JScrollPane( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
scrollP.setViewportView(chD);
mainFrame.setSize(320,200);
mainFrame.getContentPane().add(scrollP);
mainFrame.setVisible(true);
}
}
AbsoluteLayout is not a healthy option,
Instead, you can use - Containers
I was able to fix your issue with that.
Below is the code, do refer it
Container contentPane = getContentPane();
contentPane = getContentPane();
JPanel panel = new JPanel();
List<String> configList = new ArrayList<>();
for( int i = 0; i < configList.size(); i++ )
{
String configValues = configList.get( i );
JCheckBox value = new JCheckBox( configValues );
panel.add( value );
}
JScrollPane scrollPane = new JScrollPane( panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
scrollPane.setPreferredSize( new Dimension( *SIZE*, *SIZE*) );
add( scrollPane );
contentPane.add( scrollPane, BorderLayout.CENTER );

Adding rows of JTextFields to a JScrollPane

I need some advice on which Swing Components to choose in order to achieve the following:
I have something like a "table" structure, that every time that I click the "Add" button, another "row" should be inserted on the "table". Each row is composed of 2 JTextField. The problem I am having with the GridLayout (the layout used in the pictures below) is that if I add another row, then the heights of the text fields will be shortened and I don't want that (picture on the right), I want to preserve the same height for every row.
What I would like to happen is to have the extra row appear below the last one, so that I could use the JScrollPane and scroll to see it.
Should I use another layout rather than the GridLayout? Maybe the AbsoluteLayout or even using the Table Component?
Thanks.
I would use a JTable and set the row height to whatever you desire. For example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TableEg {
private static final int ROW_HEIGHT = 40;
private static final String[] TABLE_COLUMNS = {"Foo", "Bar"};
private static void createAndShowGui() {
final DefaultTableModel tableModel = new DefaultTableModel(TABLE_COLUMNS, 2);
JTable table = new JTable(tableModel );
table.setRowHeight(ROW_HEIGHT);
JScrollPane scrollpane = new JScrollPane(table);
JButton addRowBtn = new JButton(new AbstractAction("Add Row") {
#Override
public void actionPerformed(ActionEvent arg0) {
tableModel.addRow(new String[]{"", ""});
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(addRowBtn);
JFrame frame = new JFrame("TableEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollpane, BorderLayout.CENTER);
frame.getContentPane().add(btnPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Let's say that you add your JTextField in a Jpanel, and you Jpanel in a JScrollPane. Now you would set a preferredSize for you JScrollPane (since you want a fixed displayable area), but you modify the height of the JPanel dinamically based in the amount of JTextField you are placing at that time.
In other words, if you have 2 JTextField in a Jpanel set with GridLayout of 2 columns; you JTextField would take the entire height of the Jpanel; but if you include 2 more they would have to make room for this two and therefore shortening.
Notice that you have 2 rows in a JPanel set to "100" height each row would use "50". if you add another row but also modify the height of the JPanel to "150" each JTextField would still take "50" pixels.
I am a newbie, and it is a possibility that i am not 100% right; if that it is the case "Sorry". I just wanted help.
Try this....
JScrollPane scroll = new JScrollPane(Your_Table);
This will make your table to scroll....

JTable is not showing result after update?

I am creating a table at run time after fetching the result from the database. The flow of my application is like this.
Initializing a empty JScrollPane(); JScrollPane tableScroll = new JScrollPane();
Fetching result from the database;
Updating result to JTable and adding JTable to JScrollPane using following method:
Code:
private void setResultTable(Vector documents, Vector header) {
TableModel model = new DefaultTableModel(documents, header);
documentTable.setModel(model);
tableScroll.add(documentTable);
tableScroll.repaint();
}
my problem is that after calling setResultTable the result are not appearing in the table. Please help me with that. Thanks in advance !!!
You appear to be adding the JTable directly to the JScrollPane. If so this isn't correct and you'll want to change this so that you're actually adding the table to the scroll pane's viewport:
tableScroll.getViewport().add(documentTable);
There is no need to repaint the JScrollPane after doing this.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class AddTableToScroll {
public static void main(String[] args) {
final JScrollPane sPane = new JScrollPane();
// Sorry Jeanette!!
sPane.setPreferredSize(new Dimension(200, 150));
JButton button = new JButton(new AbstractAction("Press Me!") {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new Integer[][] {
{ 1, 2 }, { 3, 4 } }, new String[] { "A", "B" });
JTable table = new JTable(model);
sPane.getViewport().add(table);
}
});
JPanel panel = new JPanel();
panel.add(sPane);
panel.add(button);
JOptionPane.showMessageDialog(null, panel);
}
}
If this doesn't help, you'll want to also tell us exactly what happens, what you see, and if possible supply us with a small compilable runnable program that demonstrates your problem, an SSCCE

Java (Swing): JScrollPane.setBounds() does not apply?

I'm trying to create a simple JList with a scrollbar, and therefore i need to have the JList within a JScrollPane. So far, so good. However, for some reason i can't resize/position the JScrollPane!? It sounds logic that everything inside it should stretch to 100%, so if i set the JScrollPane to be 300px wide, the elements inside will be as well. Is that correct?
While you're at it, please critisize and give me hints if i should change something or optimize it.
Anyhow, here's the code:
package train;
import java.awt.*;
import javax.swing.*;
public class GUI {
private DefaultListModel loggerContent = new DefaultListModel();
private JList logger = new JList(loggerContent);
GUI() {
JFrame mainFrame = new JFrame("title");
this.addToLog("testing testing");
this.addToLog("another test");
// Create all elements
logger = new JList(loggerContent);
JScrollPane logWrapper = new JScrollPane(logger);
logWrapper.setBounds(10, 10, 20, 50);
// Add all elements
mainFrame.add(logWrapper);
// Show everything
mainFrame.setSize(new Dimension(600, 500));
mainFrame.setVisible(true);
}
public void addToLog(String inputString) {
int size = logger.getModel().getSize();
loggerContent.add(size, inputString);
}
}
Thanks in advance,
qwerty
EDIT: Here's a screenshot of it running: http://i.stack.imgur.com/sLGgQ.png
The setVisibleRowCount() method of JList is particularly convenient for this, as suggested in the relevant tutorial. ListDemo is a good example.
Addendum:
please critisize and give me hints…
Well, since you ask: Don't invoke public methods in the constructor; make them private or invoke them after the constructor finishes. There's no need to find the last index for add(), when addElement() is available. Also, be sure to construct your GUI on the event dispatch thread .
import java.awt.*;
import javax.swing.*;
/** #see http://stackoverflow.com/questions/5422160 */
public class ListPanel extends JPanel {
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
ListPanel() {
list.setVisibleRowCount(5);
}
public void append(String inputString) {
model.addElement(inputString);
}
private void init() {
for (int i = 0; i < 10; i++) {
this.append("String " + String.valueOf(i));
}
JFrame mainFrame = new JFrame("GUI");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane jsp = new JScrollPane(list);
mainFrame.add(jsp);
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ListPanel().init();
}
});
}
}
The bounds & size of a component are generally ignored over that of it's preferred size and the constraints of the layout being used by the container.
To solve this problem, learn how to use layouts & apply them appropriately.
Try to put your JScrollPane inside a JPanel and add the panel to the frame.
JPanel panel = new JPanel();
panel.add (logWrapper);
mainFrame.add(panel);
Then set the bounds of the panel instead of the JScrollpane
panel.setBounds(10, 10, 20, 50);
The probles is that Swing uses layout managers to control child bounds property. Adding a JScrollpane directly to the main frame, doesn't allow you to choose right bounds properly.

Categories

Resources