JTable not visible when adding with JScrollPane - java

i am working on a gui based project and i need to add a jtable in a jpanel.But i am not getting why the table is not being displayed when adding with a scrollpane.Also when adding without scrollpane,the table header is not displayed.
Thanks for any help...
Following is the code i am using..
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
public class FrmAddEditDN extends JDialog{
JButton JBUpdate = new JButton(new ImageIcon("images/save.png"));
JButton JBReset = new JButton("Reset",new ImageIcon("images/reset.png"));
JButton JBCancel = new JButton("Cancel",new ImageIcon("images/cancel.png"));
JLabel JLPic1 = new JLabel();
JLabel JLBanner = new JLabel("Please fill-up all the required fields.");
public FrmAddEditDN(boolean ADD_STATE,JFrame OwnerForm,Connection srcCN,String srcSQL){
super(OwnerForm,true);
cnAEDN = srcCN;
ADDING_STATE = ADD_STATE;
JPanel JPContainer = new JPanel();
JPContainer.setLayout(null);
String[] columnNames = {
"Sr No","Invoice No","Invoice Date","Consignee","Description","Basic Amount","Invoice Amount","Payment Received",
"EFT Date","Payment Earlier Received","Comm. # %","Comm.Claim # %","Comm. Received","Date","Bank","Remarks"};
String[][] data = {
{"","","","","","","","","","","","","","","",""}
};
DefaultTableModel DTModel = new DefaultTableModel(data,columnNames);
JTable table = new JTable(5,16);
table.setBounds(15,295,screen.width-40,150);
table.setRowHeight(30);
table.setForeground(Color.black);
table.setBackground(Color.white);
JTableHeader header = table.getTableHeader();
header.setForeground(Color.red);
header.setBackground(Color.green);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(2);
table.getColumnModel().getColumn(1).setPreferredWidth(50);
JScrollPane tableContainer = new JScrollPane();
tableContainer.setViewportView(table);
JPContainer.add(tableContainer);
getContentPane().add(JPContainer);
setSize(screen.width-5,screen.height-45);
setResizable(false);
setLocation(0,0);
}
}

You need to pass Component while creating a JScrollPane.
JScrollPane scrollPane = new JScrollPane(table);
JPContainer.add(scrollPane);

Related

Function to find out if JScrollbar has content

I have a program with a JScrollbar, a JButton and a JList which should run like this:
import java.awt.*;
import jawa.awt.event.ActionEvent;
import jawa.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.*;
#SuppressWarnings("serial")
public class ListClass extends JFrame implements ActionListener, ListSelectionListener {
static ListClass statList = new ListClass();
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(600, 800);
frame.setDefaultCloseOperation(3);
JPanel panel = new JPanel();
JTextArea newTask_field = new JTextArea();
newTask_field.setPreferredSize(new Dimension(400, 80));
newTask_field.setLineWrap(true);
newTask_field.setWrapStyleWord(true);
JScrollPane newTask = new JScrollPane(newTask_field);
newTask.setPreferredSize(new Dimension(400, 80));
JButton confirm = new JButton("Confirm");
confirm.setHorizontalAlignment(JButton.CENTER);
confirm.setEnabled(false);
DefaultListModel<String> listModel = new DefaultListModel<>();
JList<String> myList = new JList<String>(listModel);
myList.setPreferredSize(new Dimension(200, 400));
// Missing code //
panel.add(newTask);
panel.add(confirm);
panel.add(myList);
frame.add(panel);
frame.setVisible(true);
}
}
I want the JButton confirm to be enabled when the JScrollPane contains something and to be disabled again when the JScrollPane is empty. And when the JButton is clicked, the content of the JScrollPane becomes a new element in the JList, the JScrollPane is emptied and the JButton is disabled. But apparently a JScrollPane can't use the ActionListener. Also, there isn't any "if([Name of JScrollPane].isEmpty())" or "if([Name of JScrollPane].getContent=="")" or something like that.
How can I solve this problem?
You may be able to just check if newTask_Field is empty or not since it is the content you have put inside JScrollPane.
if(newTask_Field.getText().eqauls("")){}

JTextField not fillling up column as expected?

Learning to use MigLayout. I am trying to make a very simple form that is two columns, a label, a text input, repeat, until a submit button on the bottom that should span both columns. However it does not seem to be working as expected. The text fields are not spreading and neither is the button. It looks like this
Here is my code -
package com.mypackage;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import net.miginfocom.swing.MigLayout;
public class DiceOddCalculator extends JFrame {
public DiceOddCalculator(String title) {
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setTitle(title);
//Layout and panel to house components
MigLayout layout = new MigLayout("wrap 2, debug");
JPanel panel = new JPanel(layout);
//Components
JLabel maxDiceLabel = new JLabel("Max value of die");
JTextField maxDiceInput = new JTextField();
JLabel protectionCriteriaLabel = new JLabel("Die protection Criteria:");
JTextField protectionCriteriaInput = new JTextField("");
JLabel numOfDiceLabel = new JLabel("Number of dice:");
JTextField numOfDiceInput = new JTextField("");
JButton addDice = new JButton("Add dice");
//add to panel
panel.add(maxDiceLabel);
panel.add(maxDiceInput);
panel.add(protectionCriteriaLabel);
panel.add(protectionCriteriaInput);
panel.add(numOfDiceLabel);
panel.add(numOfDiceInput);
panel.add(addDice, "span");
//Turn window on
this.setContentPane(panel);
this.setVisible(true);
}
public static void main(String[] args) {
DiceOddCalculator f = new DiceOddCalculator("Dice Odds Simulator");
}
}
What needs to change in my code so that the JTextField and Button are the appropriate widths?
I figured out it had to do with how I was constructing MigLayout. Using
MigLayout layout = new MigLayout("wrap 2, debug", "[fill, grow]", "") made the component stretch across its column as I was expecting.

JTable how to remove header border

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

Create dynamic table to add new entry with button

I am trying to build a register, so that when a button is clicked, a new entry appears on a table. Ideally, I am looking to build a table on the left side of the screen, with two rows and new column appears when the button is clicked. I want the table to have a fixed size, but it should be scrollable after a certain amount of entries. So far, I have created and formatted the JButton objects that I want to be clicked for a new entry to appear. I also know that I should use a JTable to pursue this.
How should I go about making this dynamic table?
Code So Far:
private void addRegister(JPanel pane) {
JPanel everythingPane = new JPanel();
JPanel pluPane = new JPanel();
Dimension button = new Dimension(200,150);
JTable pluTable = new JTable();
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.Y_AXIS));
//JPanel buttonPane = new JPanel (new FlowLayout (FlowLayout.LEFT));
JPanel subPane1 = new JPanel();
subPane1.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane2 = new JPanel();
subPane2.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane3 = new JPanel();
subPane3.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane4 = new JPanel();
subPane4.setAlignmentX(LEFT_ALIGNMENT);
JPanel subPane5 = new JPanel();
subPane5.setAlignmentX(LEFT_ALIGNMENT);
JPanel alignmentLayer = new JPanel();
JButton frappuccino = new JButton("Frappuccino");
JButton icedCoffee = new JButton("Iced Coffee");
frappuccino.setPreferredSize(button);
icedCoffee.setPreferredSize(button);
JButton arizona = new JButton("Arizona Green Tea");
JButton izze = new JButton("Izze");
arizona.setPreferredSize(button);
izze.setPreferredSize(button);
JButton snapple = new JButton("Snapple");
JButton gatorade = new JButton("Gatorade");
snapple.setPreferredSize(button);
gatorade.setPreferredSize(button);
JButton water = new JButton("Water");
JButton appleJuice = new JButton("Apple Juice");
water.setPreferredSize(button);
appleJuice.setPreferredSize(button);
JButton orangeJuice = new JButton("Orange Juice");
JButton mentos = new JButton("Mentos");
orangeJuice.setPreferredSize(button);
mentos.setPreferredSize(button);
JButton gum = new JButton("Gum");
JButton cliffBar = new JButton("Cliff Bar");
gum.setPreferredSize(button);
cliffBar.setPreferredSize(button);
JButton littleBites = new JButton("Little Bites");
JButton welchs = new JButton("Welch's Fruit Snacks");
littleBites.setPreferredSize(button);
welchs.setPreferredSize(button);
JButton fiberOneBar = new JButton("Fiber One Bar");
JButton fiberOneBrownie = new JButton("Fiber One Brownie");
fiberOneBar.setPreferredSize(button);
fiberOneBrownie.setPreferredSize(button);
JButton cheezeIts = new JButton("Cheeze Its");
JButton goldFish = new JButton("Gold Fish");
cheezeIts.setPreferredSize(button);
goldFish.setPreferredSize(button);
JButton teaBag = new JButton("Tea Bag");
JButton poptarts = new JButton("Poptarts");
teaBag.setPreferredSize(button);
poptarts.setPreferredSize(button);
JButton sampleButton = new JButton("Sample Button");
JButton sampleButton2 = new JButton("Sample Button");
sampleButton.setPreferredSize(button);
sampleButton2.setPreferredSize(button);
JButton sampleButton3 = new JButton("Sample Button");
JButton sampleButton4 = new JButton("Sample Button");
sampleButton3.setPreferredSize(button);
sampleButton4.setPreferredSize(button);
subPane1.add(frappuccino);
subPane1.add(icedCoffee);
subPane1.add(arizona);
subPane1.add(izze);
subPane2.add(snapple);
subPane2.add(gatorade);
subPane2.add(water);
subPane2.add(appleJuice);
subPane3.add(orangeJuice);
subPane3.add(mentos);
subPane3.add(gum);
subPane3.add(cliffBar);
subPane4.add(littleBites);
subPane4.add(welchs);
subPane4.add(fiberOneBar);
subPane4.add(fiberOneBrownie);
subPane5.add(cheezeIts);
subPane5.add(goldFish);
subPane5.add(teaBag);
subPane5.add(poptarts);
alignmentLayer.add(sampleButton);
alignmentLayer.add(sampleButton2);
alignmentLayer.add(sampleButton3);
alignmentLayer.add(sampleButton4);
buttonPane.add(subPane1);
buttonPane.add(subPane2);
buttonPane.add(subPane3);
buttonPane.add(subPane4);
buttonPane.add(subPane5);
buttonPane.add(Box.createRigidArea(new Dimension(5,100)));
buttonPane.add(alignmentLayer);
pluPane.add(pluTable);
everythingPane.add(pluPane);
everythingPane.add(buttonPane);
pane.add(everythingPane);
}
JTable is more commonly used in a way that adds rows, rather than columns. I re-factored this example to illustrate the basic idea below. Each time the button is clicked, a new row is added to the table's model, which updates the table itself.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
* #see https://stackoverflow.com/a/19472190/230513
* #see https://stackoverflow.com/a/7519403/230513
*/
public class TableAddTest extends JPanel {
private static final int N_ROWS = 8;
private static String[] header = {"ID", "String", "Number", "Boolean"};
private DefaultTableModel dtm = new DefaultTableModel(null, header) {
#Override
public Class<?> getColumnClass(int col) {
return getValueAt(0, col).getClass();
}
};
private JTable table = new JTable(dtm);
private JScrollPane scrollPane = new JScrollPane(table);
private JScrollBar vScroll = scrollPane.getVerticalScrollBar();
private int row;
private boolean isAutoScroll;
public TableAddTest() {
this.setLayout(new BorderLayout());
Dimension d = new Dimension(320, N_ROWS * table.getRowHeight());
table.setPreferredScrollableViewportSize(d);
for (int i = 0; i < N_ROWS; i++) {
addRow();
}
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
vScroll.addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
isAutoScroll = !e.getValueIsAdjusting();
}
});
this.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("Add Row") {
#Override
public void actionPerformed(ActionEvent e) {
addRow();
}
}));
this.add(panel, BorderLayout.SOUTH);
}
private void addRow() {
char c = (char) ('A' + row++ % 26);
dtm.addRow(new Object[]{
Character.valueOf(c),
String.valueOf(c) + String.valueOf(row),
Integer.valueOf(row),
Boolean.valueOf(row % 2 == 0)
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableAddTest nlt = new TableAddTest();
f.add(nlt);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}

How to update jtable in runtime?

I am new to JTable.
I want to update the jtable data at runtime in button press event.
Here is my code.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.*;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SetEditableTableCell extends JPanel {
JPanel top = new JPanel();
JPanel bottom = new JPanel();
JButton update = new JButton("Update");
JTable table;
Vector<String> rowOne;
Vector<String> rowTwo;
DefaultTableModel tablemodel;
public SetEditableTableCell() {
this.setLayout(new BorderLayout());
rowOne = new Vector<String>();
rowOne.addElement("Row1-1");
rowOne.addElement("Row1-2");
rowOne.addElement("Row1-3");
rowTwo = new Vector<String>();
rowTwo.addElement("Row2-2");
rowTwo.addElement("Row2-3");
rowTwo.addElement("Row2-4");
Vector<Vector> rowData = new Vector<Vector>();
rowData.addElement(rowOne);
rowData.addElement(rowTwo);
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("Column One");
columnNames.addElement("Column Two");
columnNames.addElement("Column Three");
tablemodel = new DefaultTableModel(rowData, columnNames);
table = new JTable(tablemodel);
// table.setValueAt("aa", 0, 0);
update.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
updatedata();
}
private void updatedata() {
rowOne = new Vector<String>();
rowOne.addElement("updated Row1-1");
rowOne.addElement("updated Row1-2");
rowOne.addElement("updated Row1-3");
rowTwo = new Vector<String>();
rowTwo.addElement("updated Row2-2");
rowTwo.addElement("updated Row2-3");
rowTwo.addElement("updated Row2-4");
// tablemodel.addRow(rowTwo);
tablemodel.fireTableDataChanged();
table.setModel(tablemodel);
System.out.println("button pressed");
// table.setValueAt("aa", 0, 0);
}
});
JScrollPane scrollPane = new JScrollPane(table);
top.add(scrollPane);
bottom.add(update);
add(top, BorderLayout.NORTH);
add(bottom, BorderLayout.SOUTH);
}
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SetEditableTableCell obj = new SetEditableTableCell();
frame.add(obj);
//frame.setSize(400, 300);
frame.pack();
frame.setVisible(true);
}
}
But it is not updating after pressing update button.
Can anybody solve my problem?
Thanks in advance..
It is not updated because you do not modify the values in your TableModel. By assigning a new Vector to rowOne and rowTwo in your updateData method, you are altering other Vector instances then the ones your TableModel knows about.
A possible solution is to reconstruct the data vector and use the setDataVector method
Construct your own table model using the AbstractTableModel and use it's "event" triggers to notify the JTable of changes to the underlying model

Categories

Resources