I work on my projekt where i need to copy one row from JTable into another JTable, the second JTable should be only one-row table. I created mouselistener to first JTable where on doubleclick it should copy row and insert it into another JTable but it doesn't work correctly, any ideas how to solve it? i Get the data from database in first table. with code:
public void cputable() {
try {
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test","postgres","postgres");
stat = conn.createStatement();
result = stat.executeQuery("SELECT name,bus_speed,socket,cores,chipset,price*1.3 FROM CPU");
cputable.setModel(DbUtils.resultSetToTableModel(result));
result.close();
stat.close();
}
catch (Exception e){
e.printStackTrace();
}
}
and here is the code which i try to copy row:
cputable.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable cputable =(JTable) me.getSource();
int row = cputable.getSelectedRow();
int col = cputable.getColumnCount();
if (me.getClickCount() == 2) {
cputablebottom.repaint();
for(int i = 0; i < col; i++) {
DefaultTableModel model = (DefaultTableModel) cputable.getModel();
List<String>list = new ArrayList<String>();
list.add( cputable.getValueAt(row, i).toString());
model.addRow(list.toArray());
cputablebottom.setModel(model);
}
Result before and after:
EDIT:
I remake a bit in the code and now it copy the whole list instead of only one row.
cputable.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JTable cputable =(JTable) me.getSource();
int row = cputable.getSelectedRow();
int col = cputable.getColumnCount();
if (me.getClickCount() == 2) {
cputablebottom.repaint();
DefaultTableModel model1 = (DefaultTableModel) cputable.getModel();
List<String>list = new ArrayList<String>();
model1.addRow(list.toArray());
for(int i = 0; i < col; i++) {
list.add( cputable.getValueAt(row, i).toString());
cputablebottom.setModel(model1);
System.out.println(model1);
System.out.println(list);
}
cputablebottom.setModel(model1);
I've not tried this, but...
DefaultTableModel model1 = (DefaultTableModel) cputable.getModel();
Vector data = model1.getDataVector();
Object rowObj = data.get(row);
Vector newData = new Vector(1);
newData.add(rowObj);
DefaultTableModel model2 = (DefaultTableModel) cputablebottom.getModel();
model2.setRowCount(0);
model2.addRow(newData);
This should preserve the column information of the second table.
Alternatively, you could create a new DefaultTableModel, but you'd have to reconfigure the column information each time
What I suggest you do is have a read of the JavaDocs for DefaultTableModel
Tested example
I don't use DefaultTableModel often, preferring to put an actual object in each row, which I can then define how it is displayed, which would make it generally simpler, but, if a DefaultTableModel is all you have...
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable top;
private JTable bottom;
public TestPane() {
setLayout(new GridLayout(2, 0));
String[][] rowData = new String[10][10];
for (int row = 0; row < 10; row++) {
String[] data = new String[10];
for (int col = 0; col < 10; col++) {
data[col] = row + "x" + col;
}
rowData[row] = data;
}
String[] names = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
DefaultTableModel model = new DefaultTableModel(rowData, names);
top = new JTable(model);
add(new JScrollPane(top));
DefaultTableModel emptyModel = new DefaultTableModel(new String[10][10], names);
bottom = new JTable(emptyModel);
add(new JScrollPane(bottom));
top.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
int row = top.rowAtPoint(e.getPoint());
if (row > -1) {
DefaultTableModel topModel = ((DefaultTableModel)top.getModel());
DefaultTableModel bottomModel = ((DefaultTableModel)bottom.getModel());
bottomModel.setRowCount(1);
for (int col = 0; col < topModel.getColumnCount(); col++) {
bottomModel.setValueAt(topModel.getValueAt(row, col), 0, col);
}
}
}
}
});
}
}
}
1.Code of 1st class where we are making our table-->
Sell.java
public class Sell extends JFrame {
public static void main(String args[]) {
new Sell();
}
JTextField tf1, tf2, tf3;
JButton b1, b2, b3;
JTable t1;
String s1;
public Sell() {
setBounds(450, 200, 600, 300);
setTitle("Sell");
Container con = getContentPane();
con.setBackground(Color.WHITE);
setLayout(null); // FlowLayout,GridLayout By default it is FlowLayout.
setVisible(true);
setResizable(false); // It allows to resize application size.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tf1 = new JTextField();
tf2 = new JTextField();
tf3 = new JTextField();
b1 = new JButton("Select");
b2 = new JButton("Add");
b3 = new JButton("Invoice");
t1 = new JTable(0, 2);
DefaultTableModel model = (DefaultTableModel) t1.getModel();
model.addRow(new Object[] { "Product", "Price" });
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
add(b3);
add(t1);
tf1.setBounds(50, 50, 50, 20);
tf2.setBounds(25, 100, 100, 20);
tf3.setBounds(150, 100, 100, 20);
b1.setBounds(150, 45, 75, 30);
b2.setBounds(100, 195, 75, 30);
b3.setBounds(200, 195, 75, 30);
t1.setBounds(350, 50, 225, 200);
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
s1 = tf1.getText();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/vanisb",
"root", "spirit");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from product where ID='" + s1 + "';");
while (rs.next()) {
tf2.setText(rs.getString("product_name"));
tf3.setText(rs.getString("price"));
}
conn.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(b1, ex);
}
}
});
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addRow(new Object[] { tf2.getText(), tf3.getText() });
}
});
b3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Invoice(model);
}
});
}
}
2.Code of 2nd class where we have to fetch the last table data-->
Invoice.java
public class Invoice extends JFrame {
public static void main(String[] args) {
}
JLabel l1, l2;
JTextField tf1, tf2;
JTable t2;
JButton b1;
public Invoice(DefaultTableModel model) {
setBounds(450, 200, 600, 300);
setTitle("Invoice");
Container con = getContentPane();
con.setBackground(Color.WHITE);
setLayout(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l1 = new JLabel("Name : ");
l2 = new JLabel("Phone No. : ");
tf1 = new JTextField();
tf2 = new JTextField();
b1 = new JButton("Add Customer");
t2 = new JTable(model);
add(l1);
add(l2);
add(tf1);
add(tf2);
add(b1);
add(t2);
l1.setBounds(50, 50, 100, 20);
l2.setBounds(50, 100, 100, 20);
tf1.setBounds(150, 50, 100, 20);
tf2.setBounds(150, 100, 100, 20);
b1.setBounds(100, 175, 150, 30);
t2.setBounds(300, 50, 275, 200);
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
}
}
Related
being new to programming, i'm having a slight issue resizing the text fields I've added to the JPanel. While I could go the route of creating individual panels with their own text field, I though it would be better to add all the components into one panel. Part of my overall idea is to have my add button reference the panel, containing the text fields, to add more text fields on the tracker for users to fill out, and while I can get the fields to display when I implement the setBounds method on my panel object, i'm having tough time figuring out how resize them in the panel itself. And if you have any other advice on my overall structure, I welcome it.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class UI {
JFrame frame;
JLabel Title,Name, CheckOut, CheckIn, Email;
JTextField NameField,CheckOutField, CheckInField, EmailField;
JButton Add, Delete;
JPanel buttons, textfields, primary;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UI window = new UI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public UI(){
design();
}
private void design(){
frame = new JFrame("Form 48 Tracker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 750, 400);
frame.getContentPane().setLayout(null);
Title = new JLabel();
Title.setText("Form 48 Tracker");
Title.setFont(new Font("Calibri", Font.PLAIN, 28));
Title.setBounds(233, 11, 200, 75);
frame.getContentPane().add(Title);
Title.setForeground(Color.BLACK);
Name = new JLabel();
Name.setText("Name");
Name.setFont(new Font("Calibri", Font.PLAIN, 15));
Name.setBounds(50, 80, 128, 20);
frame.getContentPane().add(Name);
Name.setForeground(Color.BLACK);
CheckOut = new JLabel();
CheckOut.setText("Check Out Date");
CheckOut.setFont(new Font("Calibri", Font.PLAIN, 15));
CheckOut.setBounds(200, 80, 128, 20);
frame.getContentPane().add(CheckOut);
CheckOut.setForeground(Color.BLACK);
CheckIn = new JLabel();
CheckIn.setText("Check In Date");
CheckIn.setFont(new Font("Calibri", Font.PLAIN, 15));
CheckIn.setBounds(350, 80, 128, 20);
frame.getContentPane().add(CheckIn);
CheckIn.setForeground(Color.BLACK);
Email = new JLabel();
Email.setText("Email");
Email.setFont(new Font("Calibri", Font.PLAIN, 15));
Email.setBounds(500, 80, 128, 20);
frame.getContentPane().add(Email);
Email.setForeground(Color.BLACK);
Add = new JButton("Add");
buttons = new JPanel();
buttons.add(Add);
buttons.setBounds(200, 270, 157, 50); //x , y , width , height//
frame.getContentPane().add(buttons);
Add.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
Delete = new JButton("Delete");
buttons = new JPanel();
buttons.add(Delete);
buttons.setBounds(605, 101, 128, 50);
frame.getContentPane().add(buttons);
primary = new JPanel();
NameField = new JTextField();
CheckOutField = new JTextField();
CheckInField = new JTextField();
EmailField = new JTextField();
primary.add(NameField);
primary.add(CheckOutField);
primary.add(CheckInField);
primary.add(EmailField);
primary.setBounds(50, 110, 128, 20);
frame.getContentPane().add(primary);
}
}
Let's concentrate on the code that's causing the problem, and only that code. I've created a minimal example program, one that has enough code to compile and run, and that demonstrates the problem, but that has no unnecessary code:
import javax.swing.*;
public class UiFoo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null); // **** no!! ****
JPanel primary = new JPanel();
JTextField NameField = new JTextField();
JTextField CheckOutField = new JTextField();
JTextField CheckInField = new JTextField();
JTextField EmailField = new JTextField();
primary.add(NameField);
primary.add(CheckOutField);
primary.add(CheckInField);
primary.add(EmailField);
primary.setBounds(50, 110, 128, 20);
frame.getContentPane().add(primary);
frame.setSize(600, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
So, if you run this code, you'll see 4 very small JTextFields. Why are they so small? Because you've not set the columns property for the JTextFields, and so they default to columns size 0 and show up like so:
So it's better if you can give the JTextField a columns property so that they have some width, e.g., make this change:
JPanel primary = new JPanel();
int columns = 8;
JTextField NameField = new JTextField(columns);
JTextField CheckOutField = new JTextField(columns);
JTextField CheckInField = new JTextField(columns);
JTextField EmailField = new JTextField();
But this just shows one JTextField, and cuts off the bottom as well:
Why? Because you're artificially constraining the size of the containing JPanel, primary via:
primary.setBounds(50, 110, 128, 20);
This containing JPanel is only 128 pixels wide by 20 pixels high, meaning that it won't even display one JTextField well.
One solution is to use a mix of layout managers and JPanels as well as a JScrollPane to allow for a grid of JPanels to be added, something like so (try it out!):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class UiFoo2 extends JPanel {
JPanel singleColumnPanel = new JPanel(new GridLayout(0, 1, 2, 2));
public UiFoo2() {
JButton addButton = new JButton("Add");
addButton.addActionListener(e -> {
JPanel rowPanel = new JPanel(new GridLayout(1, 4, 2, 2));
for (int i = 0; i < 4; i++) {
rowPanel.add(new JTextField(8));
}
singleColumnPanel.add(rowPanel);
singleColumnPanel.revalidate();
singleColumnPanel.repaint();
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
JPanel labelPanel = new JPanel(new GridLayout(1, 4, 2, 2));
labelPanel.add(new JLabel("Name", SwingConstants.CENTER));
labelPanel.add(new JLabel("Check Out Date", SwingConstants.CENTER));
labelPanel.add(new JLabel("Check In Date", SwingConstants.CENTER));
labelPanel.add(new JLabel("Email", SwingConstants.CENTER));
singleColumnPanel.add(labelPanel);
JPanel containerPanel = new JPanel(new BorderLayout(5, 5));
containerPanel.add(singleColumnPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(containerPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setPreferredSize(new Dimension(650, 400));
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
UiFoo2 mainPanel = new UiFoo2();
JFrame frame = new JFrame("UiFoo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
This will create a row JPanel that holds four JTextFields that get added to the JScrollPane when the add JButton is pressed, and looks like so:
but we still can do better. Why not instead create a class to hold a row of data, something like so:
import java.util.Date;
public class Form48Customer {
private String name;
private Date checkIn;
private Date checkOut;
private String Email;
public Form48Customer(String name, Date checkIn, Date checkOut, String email) {
this.name = name;
this.checkIn = checkIn;
this.checkOut = checkOut;
Email = email;
}
public Date getCheckIn() {
return checkIn;
}
public void setCheckIn(Date checkIn) {
this.checkIn = checkIn;
}
public Date getCheckOut() {
return checkOut;
}
public void setCheckOut(Date checkOut) {
this.checkOut = checkOut;
}
public String getName() {
return name;
}
public String getEmail() {
return Email;
}
// should override hashCode and equals here
}
and then create a JTable complete with custom model to display objects of this type, and then display them in the GUI. This is much cleaner, more flexible, and extendable. Something like so:
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.table.*;
#SuppressWarnings("serial")
public class Form48TrackerPanel extends JPanel {
public static final String TITLE = "Form 48 Tracker";
private static final String DATE_FORMAT_TXT = "MM/dd/yyyy";
private Form48TableModel model = new Form48TableModel();
private JTable table = new JTable(model);
private JButton addButton = new JButton("Add");
private JButton deleteButton = new JButton("Delete");
private JButton exitButton = new JButton("Exit");
public Form48TrackerPanel() {
final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_TXT);
TableCellRenderer dateRenderer = new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if( value instanceof Date) {
value = dateFormat.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
};
table.getColumnModel().getColumn(1).setCellRenderer(dateRenderer);
table.getColumnModel().getColumn(2).setCellRenderer(dateRenderer);
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 28f));
addButton.addActionListener(new AddListener());
addButton.setMnemonic(KeyEvent.VK_A);
deleteButton.addActionListener(new DeleteListener());
deleteButton.setMnemonic(KeyEvent.VK_D);
exitButton.addActionListener(new ExitListener());
exitButton.setMnemonic(KeyEvent.VK_X);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(exitButton);
setPreferredSize(new Dimension(800, 500));
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BorderLayout(ebGap, ebGap));
add(titleLabel, BorderLayout.PAGE_START);
add(new JScrollPane(table), BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
model.addRow(new Form48Customer("John Smith", new Date(), new Date(), "JSmith#Yahoo.com"));
model.addRow(new Form48Customer("Fred Flinstone", new Date(), new Date(), "FFlinstone#GMail.com"));
}
private class AddListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
AddForm48Panel addFormPanel = new AddForm48Panel();
int result = JOptionPane.showConfirmDialog(Form48TrackerPanel.this,
addFormPanel, "Add Customer", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
Form48Customer customer = addFormPanel.getForm48Customer();
model.addRow(customer);
}
}
}
private class DeleteListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO *** finish this code ***
}
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(Form48TrackerPanel.this);
win.dispose();
}
}
private static void createAndShowGui() {
Form48TrackerPanel mainPanel = new Form48TrackerPanel();
JFrame frame = new JFrame(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class AddForm48Panel extends JPanel {
private static final int TFIELD_COLS = 10;
private static final String DATE_FORMAT_TXT = "MM/dd/yyyy";
private static final Format DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_TXT);
private static final Insets INSETS = new Insets(5, 5, 5, 5);
private JTextField nameField = new JTextField(TFIELD_COLS);
private JFormattedTextField checkOutDateField = new JFormattedTextField(DATE_FORMAT);
private JFormattedTextField checkInDateField = new JFormattedTextField(DATE_FORMAT);
private JTextField emailField = new JTextField(TFIELD_COLS);
private JComponent[] fields = {nameField, checkOutDateField, checkInDateField, emailField};
private String[] labels = {"Name", "Check Out Date", "Check In Date", "Email"};
public AddForm48Panel() {
InputVerifier verifier = new DateFieldVerifier();
checkInDateField.setInputVerifier(verifier);
checkOutDateField.setInputVerifier(verifier);
setLayout(new GridBagLayout());
for (int i = 0; i < fields.length; i++) {
add(new JLabel(labels[i] + ":"), createGbc(0, i));
add(fields[i], createGbc(1, i));
}
}
public String getName() {
return nameField.getText();
}
public String getEmail() {
return emailField.getText();
}
public Date getCheckOut() {
return (Date) checkOutDateField.getValue();
}
public Date getCheckIn() {
return (Date) checkInDateField.getValue();
}
public Form48Customer getForm48Customer() {
String name = getName();
Date checkOut = getCheckOut();
Date checkIn = getCheckIn();
String email = getEmail();
return new Form48Customer(name, checkIn, checkOut, email);
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = INSETS;
gbc.anchor = x == 0 ? GridBagConstraints.WEST :GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
return gbc;
}
private class DateFieldVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
if (input instanceof JFormattedTextField) {
JFormattedTextField ftf = (JFormattedTextField)input;
AbstractFormatter formatter = ftf.getFormatter();
if (formatter != null) {
String text = ftf.getText();
try {
formatter.stringToValue(text);
return true;
} catch (ParseException pe) {
return false;
}
}
}
return true;
}
#Override
public boolean shouldYieldFocus(JComponent input) {
boolean verify = verify(input);
if (!verify) {
String message = "Enter a valid date, e.g.: 01/05/2017";
String title = "Invalid Date Format";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(input, message, title, type);
}
return verify;
}
}
}
#SuppressWarnings("serial")
class Form48TableModel extends DefaultTableModel {
private static final String[] COL_NAMES = {"Name", "Check Out Date", "Check In Date", "Email"};
public Form48TableModel() {
super(COL_NAMES, 0);
}
public void addRow(Form48Customer customer) {
Object[] rowData = {
customer.getName(),
customer.getCheckOut(),
customer.getCheckIn(),
customer.getEmail()
};
addRow(rowData);
}
public Form48Customer getRow(int row) {
String name = (String) getValueAt(row, 0);
Date checkIn = (Date) getValueAt(row, 1);
Date checkOut = (Date) getValueAt(row, 2);
String email = (String) getValueAt(row, 3);
return new Form48Customer(name, checkIn, checkOut, email);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 1:
return Date.class;
case 2:
return Date.class;
default:
break;
}
return super.getColumnClass(columnIndex);
}
}
Which would look like:
I have a Table inside Jpanel and the size of the table is fixed i wanted to make it dynamic. if we maximize the frame the size of the table should increase
below is the code
public class LogsAutomationUIFrame extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTable table;
private JTextField fieldDownloadPath = new JTextField(30);
JLabel lblNewLabel_4;
JLabel lblNewLabel_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LogsAutomationUIFrame frame = new LogsAutomationUIFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
static DefaultTableModel model= new DefaultTableModel(0, 0);
private JPasswordField passwordField;
/**
* Create the frame.
*/
public LogsAutomationUIFrame() {
JFrame frame = new JFrame();
table = new JTable();
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
table.setAutoCreateRowSorter(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 783, 567);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblEnvironment = new JLabel("Environment");
lblEnvironment.setBounds(10, 44, 81, 21);
contentPane.add(lblEnvironment);
/*textField = new JTextField();
textField.setBounds(103, 44, 109, 20);
contentPane.add(textField);*/
//textField.setColumns(10);
String[] choices = { "CHOICE 1","CHOICE 2", "CHOICE 3","CHOICE 4","CHOICE 5","CHOICE 6"};
final JComboBox<String> cb = new JComboBox<String>();
//ComboBoxModel<String[]> choice = new ComboBoxModel<String[]>();
final File folder = new File("");
File folderParent = new File(folder.getAbsolutePath());
List<String> choiceVal = listFilesForFolder(folderParent);
//List<String> choiceVal = new ArrayList<String>();
cb.setModel(new ToComboBoxModel(choiceVal));
cb.setBounds(103, 44, 109, 20);
cb.setVisible(true);
contentPane.add(cb);
JLabel Path = new JLabel("Path");
Path.setBounds(10, 76, 46, 14);
contentPane.add(Path);
textField_1 = new JTextField();
textField_1.setBounds(103, 73, 109, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblNewLabel = new JLabel("Search String");
lblNewLabel.setBounds(10, 101, 81, 21);
contentPane.add(lblNewLabel);
textField_2 = new JTextField();
textField_2.setBounds(103, 101, 109, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
JButton btnSearchString = new JButton("Search String");
btnSearchString.setBounds(231, 103, 137, 23);
btnSearchString.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try {
LogsAutomationServiceImpl serviceImpl = new LogsAutomationServiceImpl();
String searchEnvironment = cb.getSelectedItem().toString();
String searchPath = textField_1.getText();
String searchString = textField_2.getText();
/*Properties prop = LogsAutomationServiceImpl.getProperties();
lblNewLabel_4.setText(prop.getProperty("results_limit"));*/
//System.out.println("textField:::"+textField.getText());
String password = passwordField.getText();
model = serviceImpl.setTableData(searchEnvironment, searchPath, searchString, lblNewLabel_3, lblNewLabel_4, password);
table.setModel(model);
resizeColumnWidth(table);
table.setRowHeight(50);
} catch (Exception excption) {
excption.printStackTrace();
}
}
});
contentPane.add(btnSearchString);
JLabel lblNewLabel_1 = new JLabel("Results Number");
lblNewLabel_1.setBounds(10, 150, 101, 14);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("Results Limit");
lblNewLabel_2.setBounds(10, 178, 81, 14);
contentPane.add(lblNewLabel_2);
lblNewLabel_3 = new JLabel();
lblNewLabel_3.setBounds(103, 150, 60, 14);
contentPane.add(lblNewLabel_3);
lblNewLabel_4 = new JLabel();
lblNewLabel_4.setBounds(103, 178, 60, 14);
contentPane.add(lblNewLabel_4);
Object[] columnNames = {"host", "folder", "file", "grepResult"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50)},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25)},
{"Sell", "Apple", new Integer(3000), new Double(7.35)},
{"Buy", "Nortel", new Integer(4000), new Double(20.00)}
};
table.setModel(model);
// table.setCellSelectionEnabled(true);
table.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
int row = table.rowAtPoint(evt.getPoint());
int col = table.columnAtPoint(evt.getPoint());
if (col == 2) {
System.out.println("row is :::"+ row+":::"+col+"::::"+table.getValueAt(row, col));
String fileName = table.getValueAt(row, col).toString();
String hostName = table.getValueAt(row, 0).toString();
String folderName = table.getValueAt(row, 1).toString();
Exec obj = new Exec();
String password = passwordField.getText();
obj.downloadFile(hostName, cb.getSelectedItem().toString(), fileName, folderName, password);
}
}
});
//table.getSelectionModel().addListSelectionListener(new CustomTableCellRenderer());
//table.setDefaultRenderer(Object.class, new CustomTableCellRenderer());
table.setSize(this.WIDTH, this.HEIGHT);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(10, 267, 650, 205);
getContentPane().add(scrollPane);
//scrollPane.setSize(this.WIDTH, this.HEIGHT);
contentPane.add(scrollPane, BorderLayout.CENTER);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(10, 212, 81, 14);
contentPane.add(lblPassword);
passwordField = new JPasswordField();
passwordField.setBounds(103, 203, 109, 20);
contentPane.add(passwordField);
contentPane.setSize(this.WIDTH, this.HEIGHT);
//frame.getContentPane().add(contentPane);
}
public static void resizeColumnWidth(JTable table) {
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++) {
int width = 15; // Min width
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width +1 , width);
}
if(width > 500)
width=500;
columnModel.getColumn(column).setPreferredWidth(width);
}
}
class MyRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
JTextField editor = new JTextField();
if (value != null)
editor.setText(value.toString());
editor.setBackground((row % 2 == 0) ? Color.white : Color.cyan);
return editor;
}
}
public static List<String> listFilesForFolder(final File folder) {
List<String> fileNames = new ArrayList<String>();
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
if(fileEntry.getName().toString().contains(".properties")) {
fileNames.add(fileEntry.getName());
}
}
}
return fileNames;
}
}
I tried so many ways looking at the stack overflow links like setting size to "this.widht" and "this.height" none of them worked.
when i make the Jpanel width to "this.width" and launch the application the size is very very small and
when i tried to put the same thing for scrollbar data is not getting displayed
I would first add the JTable to a JScrollPane, then add this JScrollPane to a JPanel, having a LayoutManager like BorderLayout and then add the JPanel to the JFrame... something like this:
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JScrollPane scp = new JScrollPane(table);
panel.add(BorderLayout.CENTER,scp);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(BorderLayout.CENTER,panel);
this.pack();
this.setVisible(true);
As Sergiy mentioned, as soon, as there is a LayoutManger, it rocks...
I have a JTable inside a JScrollView But It doesn't seem to be aligned well more over the scroll bar is tiny i am guessing that this is because of the alignment.Moreover it is here is a snippet from the real code :
JFrame frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 771, 453);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
panel.setBounds(10, 32, 747, 370);
frame.getContentPane().add(panel);
panel.setLayout(null);
JPanel VPanel = new JPanel();
VPanel.setBounds(297, 43, 440, 224);
panel.add(VPanel);
JTable TableV = new JTable();
TableV.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableV.getTableHeader().setReorderingAllowed(false);
DefaultTableModel Model = new DefaultTableModel(0, 0);
String header[] = new String[] { "Country", "ID", "WAN IP", "User", "OS", "Java version" };
VPanel.add(new JScrollPane(TableV, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
// just adding some data to fill the table
Model.setColumnIdentifiers(header);
//set model into the table object
TableV.setModel(Model);
//just adding some diff data to check if it scrolls down
for (int count = 1; count <= 50; count++)
{
Model.addRow(new Object[] { "data1", "data2", "data3", "data4", "data5", "data6" });
}
for (int count = 1; count <= 70; count++)
{
Model.addRow(new Object[] { "data100", "data200", "data300", "data400", "data500", "data600" });
}
frame.setVisible(true);
Understand that VPanel (which should be renamed vPanel to comply with Java naming rules) uses FlowLayout, and so the scrollpane may not fit well within it. Give it a BorderLayout and add the JScrollPane BorderLayout.CENTER if you want the scroll pane to fill it.
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
#SuppressWarnings("serial")
public class TableFoo extends JPanel {
private static final String[] HEADER = new String[] { "Country", "ID", "WAN IP", "User", "OS", "Java version" };
private static final int PREF_W = 500;
private static final int PREF_H = 400;
private DefaultTableModel model = new DefaultTableModel(HEADER, 0);
private JTable table = new JTable(model);
public TableFoo() {
for (int count = 0; count < 50; count++) {
model.addRow(new Object[] { "data1", "data2", "data3", "data4", "data5", "data6" });
}
for (int count = 0; count < 70; count++) {
model.addRow(new Object[] { "data100", "data200", "data300", "data400", "data500", "data600" });
}
JScrollPane scrollPane = new JScrollPane(table);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("TableFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TableFoo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I have this code in Java Swings which creates 2 frames.The first frame contains 4 text fields(roll no,name,class,section) leaving the text fields blank I click on the search button in the 1st frame,another frame opens with all my table records in the database.Once I select a record(or the row) all the details of it appear in the 1st frame,i.e roll no,class,name and section get populated.
Right now I am using the search button to go to the next frame.What should I do so that the action is performed once I click on the roll no. text field instead of the search button?
This is the code:
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.Vector;
import java.awt.event.*;
public class barcoder1 implements ActionListener{
JFrame frame,frame1;
JTextField textbox,textbox1,textbox2,textbox3,textbox4,textbox5,textbox6,textbox7,textbox8;
JLabel label,label1,label2,label3,label4,label5,label6,label7,label8;
JButton button;
JPanel panel;
static JTable table;
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String userName = "root";
String password = "root";
String[] columnNames = {"Roll No", "Name", "Class", "Section"};
public void createUI()
{
frame = new JFrame("Database Search Result");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
textbox = new JTextField();
textbox.setBounds(120,30,150,20);
label=new JLabel("Roll No.");
label.setBounds(10, 30, 100, 20);
textbox1 = new JTextField();
textbox1.setBounds(120,50,150,20);
label1=new JLabel("Name");
label1.setBounds(10, 50, 100, 20);
textbox2 = new JTextField();
textbox2.setBounds(120,70,150,20);
label2=new JLabel("Class");
label2.setBounds(10, 70, 100, 20);
textbox3 = new JTextField();
textbox3.setBounds(120,90,150,20);
label3=new JLabel("Section");
label3.setBounds(10, 90, 100, 20);
button = new JButton("search");
button.setBounds(120,230,150,20);
button.addActionListener(this);
frame.add(textbox);
frame.add(label);
frame.add(textbox1);
frame.add(label1);
frame.add(textbox2);
frame.add(label2);
frame.add(textbox3);
frame.add(label3);
frame.add(button);
frame.setVisible(true);
frame.setSize(500, 400);
}
public void actionPerformed(ActionEvent ae)
{
button = (JButton)ae.getSource();
System.out.println("Showing Table Data.......");
showTableData();
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
//frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
final JTable table = new JTable(model);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int row = table.getSelectedRow();
System.out.println("Selecte table row = " + row);
if (row != -1) {
int modelRow = table.convertRowIndexToModel(row);
System.out.println("Selecte model row = " + row);
Vector data = (Vector) ((DefaultTableModel) table.getModel()).getDataVector().get(modelRow);
textbox.setText(data.get(0).toString());
textbox1.setText(data.get(1).toString());
textbox2.setText(data.get(2).toString());
textbox3.setText(data.get(3).toString());
}
}
});
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
if (table.getSelectedRow() != -1) {
SwingUtilities.getWindowAncestor(table).dispose();
}
}
}
});
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
String textvalue = textbox.getText();
String roll= "";
String name= "";
String cl = "";
String sec = "";
try
{
Class.forName(driverName);
Connection con = DriverManager.getConnection(url, userName, password);
//String sql = "select * from student where rollno = "+textvalue;
String sql="select * from student";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int i =0;
while(rs.next())
{
roll = rs.getString("rollno");
name = rs.getString("name");
cl = rs.getString("class");
sec = rs.getString("section");
model.addRow(new Object[]{roll, name, cl, sec});
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(400,300);
}
public static void main(String args[])
{
barcoder1 sr = new barcoder1();
sr.createUI();
}
}
I have this JPanel called CatalogPane, which is of size 800 by 600, which is inside a JTabbedPane inside a JFrame called BookFrame. So inside the CatalogPane, I created a JPanel called bookDisplay which displays a list of books and their details. I want it to be of size 780 by 900, leaving 20px for the scrollbar and taller than the frame so that it can scroll. Then I created a panel of size 800 by 400 because I need to leave some extra space at the bottom for other fields. I tried creating a JScrollPane for bookDisplay and then put it inside the other panel, but somehow the scrollbar appears but can't be used to scroll. I've experimented changing the sizes and scrollpane but I still can't get it to work.
What it looks like: http://prntscr.com/12j0d9
The scrollbar is there but can't work. I'm trying to get the scrollbar to work before I format the layout properly.
CatalogPane:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class CatalogPane extends JPanel{
//private Order currOrder = new Order();
//ArrayList<Book> bookCatalog = new ArrayList();
GridBagConstraints gbc = new GridBagConstraints();
GridBagLayout gbl = new GridBagLayout();
JPanel bookDisplay = new JPanel();
public CatalogPane()
{
//loadBookCatalog();
this.setPreferredSize(new Dimension(800, 600));
bookDisplay.setPreferredSize(new Dimension(780, 900));
bookDisplay.setLayout(new GridLayout(6, 5));
//bookDisplay.setLayout(gbl);
//gbc.fill = GridBagConstraints.NONE;
//gbc.weightx = 1;
//gbc.weighty = 1;
JLabel bookL = new JLabel("Books");
JLabel hardL = new JLabel("Hardcopy");
JLabel hardQuantL = new JLabel("Quantity");
JLabel eL = new JLabel("EBook");
JLabel eQuantL = new JLabel("Quantity");
bookDisplay.add(bookL);
bookDisplay.add(hardL);
bookDisplay.add(hardQuantL);
bookDisplay.add(eL);
bookDisplay.add(eQuantL);
/*
addComponent(bookL, 0, 0, 1, 1);
addComponent(hardL, 0, 1, 1, 1);
addComponent(hardQuantL, 0, 2, 1, 1);
addComponent(eL, 0, 3, 1, 1);
addComponent(eQuantL, 0, 4, 1, 1);
*/
Iterator<Book> bci = bookCatalog.iterator();
int row = 1;
/*
while(bci.hasNext())
{
Book temp = bci.next();
ImageIcon book1 = new ImageIcon(temp.getImage());
JLabel image = new JLabel(temp.getTitle(), book1, JLabel.CENTER);
image.setVerticalTextPosition(JLabel.TOP);
image.setHorizontalTextPosition(JLabel.CENTER);
String[] quant = {"1", "2", "3", "4", "5"};
JLabel hardP = new JLabel("$" + temp.getHardPrice());
JLabel eP = new JLabel("$" + temp.getEPrice());
JComboBox jbc1 = new JComboBox(quant);
JComboBox jbc2 = new JComboBox(quant);
jbc1.setSelectedIndex(0);
jbc2.setSelectedIndex(0);
/*
addComponent(b1temp, row, 0, 1, 1);
addComponent(hardP, row, 1, 1, 1);
addComponent(jbc1, row, 2, 1, 1);
addComponent(eP, row, 3, 1, 1);
addComponent(jbc2, row, 4, 1, 1);
row++;
bookDisplay.add(image);
bookDisplay.add(new JLabel("$" + temp.getHardPrice()));
bookDisplay.add(jbc1);
bookDisplay.add(new JLabel("$" + temp.getEPrice()));
bookDisplay.add(jbc2);
*/
for(int i=0;i<5;i++)
{
String[] quant = {"1", "2", "3", "4", "5"};
JComboBox jbc1 = new JComboBox(quant);
JComboBox jbc2 = new JComboBox(quant);
jbc1.setSelectedIndex(0);
jbc2.setSelectedIndex(0);
JLabel image = new JLabel("image");
bookDisplay.add(image);
bookDisplay.add(new JLabel("$" + 20));
bookDisplay.add(jbc1);
bookDisplay.add(new JLabel("$" + 15));
bookDisplay.add(jbc2);
}
JScrollPane vertical = new JScrollPane(bookDisplay);
//JPanel testP = new JPanel();
//testP.setPreferredSize(new Dimension(800, 400));
//JScrollPane vertical = new JScrollPane(testP);
//testP.add(bookDisplay);
vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel testP = new JPanel();
testP.setPreferredSize(new Dimension(800, 400));
testP.add(vertical);
add(testP);
}
public void addComponent(Component c, int row, int col, int hei, int wid)
{
gbc.gridx = col;
gbc.gridy = row;
gbc.gridwidth = wid;
gbc.gridheight = hei;
gbl.setConstraints(c, gbc);
bookDisplay.add(c);
}
public Order getCurrOrder()
{
return currOrder;
}
private void loadBookCatalog()
{
try
{
String[] str = new String[8];
Scanner sc = new Scanner(new File("bookcat.txt"));
double temp1, temp2;
while(sc.hasNextLine())
{
str = sc.nextLine().split(";");
temp1 = Double.parseDouble(str[3]);
temp2 = Double.parseDouble(str[4]);
Book temp = new Book(temp1, temp2, str[0], str[1], str[2], str[5]);
bookCatalog.add(temp);
}
}
catch(IOException e)
{
System.out.println("File not found!");
}
}
}
BookFrame:
public class BookFrame extends JFrame{
JButton closeButton;
CatalogPane cp;
//IntroPane ip;
public BookFrame(String name)
{
super(name);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(new IntroPane()),
"Thank you for visiting Groovy Book Company.", "Message",
JOptionPane.INFORMATION_MESSAGE, new ImageIcon("coffee.jpg"));
System.exit(0);
}
});
//ip = new IntroPane();
cp = new CatalogPane();
JTabbedPane jtp = new JTabbedPane();
jtp.setPreferredSize(new Dimension(800, 600));
//jtp.addTab("Intro", ip);
jtp.addTab("Catalog", cp);
add(jtp);
pack();
setVisible(true);
}
}
I'd look at JTable, which handles scrolling and rendering as shown here and below. This example shows how to render images and currency. Start by adding a third column for quantity of type Integer. This related example illustrates using a JComboBox editor.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.text.NumberFormat;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
/**
* #see https://stackoverflow.com/a/16264880/230513
*/
public class Test {
public static final Icon ICON = UIManager.getIcon("html.pendingImage");
private JPanel createPanel() {
JPanel panel = new JPanel();
DefaultTableModel model = new DefaultTableModel() {
#Override
public Class<?> getColumnClass(int col) {
if (col == 0) {
return Icon.class;
} else {
return Double.class;
}
}
};
model.setColumnIdentifiers(new Object[]{"Book", "Cost"});
for (int i = 0; i < 42; i++) {
model.addRow(new Object[]{ICON, Double.valueOf(i)});
}
JTable table = new JTable(model);
table.setDefaultRenderer(Double.class, new DefaultTableCellRenderer() {
#Override
protected void setValue(Object value) {
NumberFormat format = NumberFormat.getCurrencyInstance();
setText((value == null) ? "" : format.format(value));
}
});
table.setRowHeight(ICON.getIconHeight());
panel.add(new JScrollPane(table) {
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
});
return panel;
}
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Test1", createPanel());
jtp.addTab("Test2", createPanel());
f.add(jtp);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}