JTable column labels not printing - java

I have a JTable that I am using to display data from my database as a print preview. I can get it to print how I want except that the column headers wont print no matter what I try. I add my JTable to a JScrollPane, I have even gone so far as to add my JScrollPane to another JPanel which gets added to another JPanel with everything .setVisible(true).
After extensively traversing the Google-verse, the only solution I have found was here but I am already doing what they said. Here is my code so far:
public class PrintPreview extends JDialog implements ActionListener
{
private JTable infoTable;
private boolean printed;
private int windowWidth;
private int windowHeight;
JPanel scrollerPanel;
JPanel dataPanel;
private int[] idList;
private Connection conn;
private JScrollPane scroller;
private JButton printButton;
public PrintPreview(int[] tIds, Connection tConn)
{
printed = false;
idList = tIds;
conn = tConn;
setupFrame();
setupScroller();
setupButtons();
this.pack();
this.setVisible (true);
}
//returns true if printed, false otherwise
public boolean getCloseValue()
{
return printed;
}
private void setupFrame()
{
this.setTitle("Edit Data");
this.setSize (800, 700); //Width, Height
this.setLocationRelativeTo(null); //Centers the JFrame on the screen
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
this.setResizable(false);
this.setModalityType(APPLICATION_MODAL);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//Gets the size of the contentPanel of the frame
Insets inset = this.getInsets();
windowWidth = this.getSize().width - (inset.left + inset.right);
windowHeight = this.getSize().height - (inset.top + inset.bottom);
}
private void setupScroller()
{
scrollerPanel = new JPanel();
scroller = new JScrollPane (setupTable(), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
infoTable.setFillsViewportHeight(true);
scroller.setSize(windowWidth, windowHeight - 120);
scroller.setMinimumSize(new Dimension (windowWidth, windowHeight - 120));
scroller.setMaximumSize(new Dimension (windowWidth, windowHeight - 120));
scroller.setPreferredSize(new Dimension (windowWidth, windowHeight - 120));
scroller.setVisible(true);//*********************************************************
scroller.add (setupTable());
this.add (scroller);
}
private void setupButtons()
{
JPanel spacer1 = new JPanel();
spacer1.setSize(100, 20);
spacer1.setMaximumSize(new Dimension (100, 20));
spacer1.setMinimumSize(new Dimension (100, 20));
spacer1.setPreferredSize(new Dimension (100, 20));
JPanel spacer2 = new JPanel();
spacer2.setSize(100, 20);
spacer2.setMaximumSize(new Dimension (100, 20));
spacer2.setMinimumSize(new Dimension (100, 20));
spacer2.setPreferredSize(new Dimension (100, 20));
printButton = new JButton ("Print");
printButton.setFont((new Font("", Font.BOLD, 14)));
printButton.setSize(new Dimension (130, 35));
printButton.setMaximumSize(new Dimension (130, 35));
printButton.setMinimumSize(new Dimension (130, 35));
printButton.setPreferredSize(new Dimension (130, 35));
printButton.addActionListener(this);
spacer1.setAlignmentX(Component.CENTER_ALIGNMENT);
printButton.setAlignmentX(Component.CENTER_ALIGNMENT);
this.add (spacer1);
this.add (printButton);
this.add (spacer2);
}
private JTable setupTable()
{
infoTable = new JTable();
DefaultTableModel dm = new DefaultTableModel(0, 0);
String header[] = new String[] {"Case #", "Date", "Officer #", "Offence",
"Description", "Report"};
dm.setColumnIdentifiers(header);
infoTable.setModel(dm);
infoTable.setRowHeight(26);
infoTable.setFocusable(false);//display only
//Adds everything to the table
int idSize = idList.length;
for (int x = 0; x < idSize; x++)
{
try
{
String[] values = getInfo(idList[x]);
values[4] = values[4].trim();
values[4] = values[4].replaceAll("<html>", "");
dm.addRow(values);
}
catch (SQLException e)
{
System.out.println ("Error: " + e);
System.out.println ("Event-addObjects(): Problem with getting event info");
}
infoTable.setFont(new Font("Serif", Font.PLAIN, 10));
}
//Centers the values on the smaller columns
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
infoTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
infoTable.getColumnModel().getColumn(1).setCellRenderer(centerRenderer);
infoTable.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
infoTable.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
infoTable.getColumnModel().getColumn(5).setCellRenderer(centerRenderer);
//Sets the sizes of the columns
infoTable.getColumnModel().getColumn(0).setMinWidth(40);
infoTable.getColumnModel().getColumn(1).setMinWidth(65);
infoTable.getColumnModel().getColumn(2).setMinWidth(40);
infoTable.getColumnModel().getColumn(3).setMinWidth(80);
infoTable.getColumnModel().getColumn(4).setMinWidth(250);
infoTable.getColumnModel().getColumn(5).setMinWidth(50);
//Makes the Description column cells JTextFields
infoTable.getColumnModel().getColumn(4).setCellRenderer(new VariableRowHeightRenderer());
//Looks at the size each JTextField would like to be and changes the rows to accomidate
int column = 4;
for (int row = 0; row < infoTable.getRowCount(); row++)
{
int rowHeight = 26;
Component comp = infoTable.prepareRenderer(infoTable.getCellRenderer(row, column), row, column);
rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
if(rowHeight != infoTable.getRowHeight(row))
{
infoTable.setRowHeight(row, rowHeight);
}
}
infoTable.setVisible(true);//***********************************************************************
return infoTable;
}
private String[] getInfo(int id) throws SQLException
{
String result[];
ResultSet rs;
String command = "SELECT * FROM Logs_Table where id = " + id;
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(command);
result = new String[] {rs.getString("Case_Num"), rs.getString("Event_Date"),
rs.getString("Officer_Num"), rs.getString("Offence"),
("<html>" + rs.getString("Description") + "<html>"),
rs.getString("Report")};
return result;
}
#Override
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
switch (cmd)
{
case "Print":
printed = true;
try
{
infoTable.setSize(infoTable.getPreferredSize());
//Makes the margins smaller
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add (new MediaPrintableArea((float)8.25, (float)10.0, (float)8.5, (float)11.0, MediaPrintableArea.INCH));
MessageFormat empty = new MessageFormat ("");
MessageFormat footerFormat = new MessageFormat("- {0} -");
infoTable.print (PrintMode.FIT_WIDTH, empty, footerFormat, true, aset, false);
}
catch (PrinterException ex)
{
System.out.println ("Error: " + ex);
System.out.println ("Built in table print didnt work");
}
//this.dispose();
break;
default:
break;
}
}
private class VariableRowHeightRenderer extends JTextArea implements TableCellRenderer
{
public VariableRowHeightRenderer()
{
super();
this.setEditable(false);
this.setLineWrap(true);
this.setWrapStyleWord(true);
this.setWrapStyleWord(true);
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
this.setBackground(Color.WHITE);
this.setText((String) (value));
this.setSize(table.getColumnModel().getColumn(column).getWidth(),
Short.MAX_VALUE);
return this;
}
}
}
Can someone please tell me what I am doing wrong?

Okay, after much screwing around, I got "something" to work. The "core" problems seem to come down to
Creating multiple instance of the JTable
"add" the JTable to the JScrollPane (scroller.add(setupTable());), as apposed to setting it as the screen pane's viewport's view
Addition, unnecessary UI elements which just made it more difficult to understand the code then was required
This example just dumps the output to a file, but it should work just fine for printing.
import java.awt.Color;
import java.awt.Component;
import static java.awt.Dialog.ModalityType.APPLICATION_MODAL;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.text.MessageFormat;
import javax.imageio.ImageIO;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class PrintPreview extends JDialog implements ActionListener {
public static void main(String[] args) {
new PrintPreview(new int[]{1, 2, 3, 4}, null);
}
private JTable infoTable;
private boolean printed;
private int windowWidth;
private int windowHeight;
JPanel container;
// JPanel scrollerPanel;
JPanel dataPanel;
private int[] idList;
private Connection conn;
private JScrollPane scroller;
private JButton printButton;
JTable printable;
public PrintPreview(int[] tIds, Connection tConn) {
container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
printed = false;
idList = tIds;
conn = tConn;
setupFrame();
setupScroller();
setupButtons();
this.setContentPane(container);
this.pack();
this.setVisible(true);
}
//returns true if printed, false otherwise
public boolean getCloseValue() {
return printed;
}
private void setupFrame() {
this.setTitle("Edit Data");
this.setSize(800, 700); //Width, Height
this.setLocationRelativeTo(null); //Centers the JFrame on the screen
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
// this.setResizable(false);
this.setModalityType(APPLICATION_MODAL);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//Gets the size of the contentPanel of the frame
Insets inset = this.getInsets();
windowWidth = this.getSize().width - (inset.left + inset.right);
windowHeight = this.getSize().height - (inset.top + inset.bottom);
}
private void setupScroller() {
// scrollerPanel = new JPanel();
scroller = new JScrollPane(setupTable());
// scroller = new JScrollPane(setupTable(), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
// JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// infoTable.setFillsViewportHeight(true);
// scroller.setSize(windowWidth, windowHeight - 120);
// scroller.setMinimumSize(new Dimension(windowWidth, windowHeight - 120));
// scroller.setMaximumSize(new Dimension(windowWidth, windowHeight - 120));
// scroller.setPreferredSize(new Dimension(windowWidth, windowHeight - 120));
// scroller.setVisible(true);//*********************************************************
// scroller.add(setupTable());
// scrollerPanel.add(scroller);
// scrollerPanel.setVisible(true);//******************************************************
// scrollerPanel.setOpaque(true);//*************************************************************
container.add(scroller);
}
private void setupButtons() {
JPanel spacer1 = new JPanel();
spacer1.setSize(100, 20);
spacer1.setMaximumSize(new Dimension(100, 20));
spacer1.setMinimumSize(new Dimension(100, 20));
spacer1.setPreferredSize(new Dimension(100, 20));
JPanel spacer2 = new JPanel();
spacer2.setSize(100, 20);
spacer2.setMaximumSize(new Dimension(100, 20));
spacer2.setMinimumSize(new Dimension(100, 20));
spacer2.setPreferredSize(new Dimension(100, 20));
printButton = new JButton("Print");
printButton.setFont((new Font("", Font.BOLD, 14)));
printButton.setSize(new Dimension(130, 35));
printButton.setMaximumSize(new Dimension(130, 35));
printButton.setMinimumSize(new Dimension(130, 35));
printButton.setPreferredSize(new Dimension(130, 35));
printButton.addActionListener(this);
spacer1.setAlignmentX(Component.CENTER_ALIGNMENT);
printButton.setAlignmentX(Component.CENTER_ALIGNMENT);
container.add(spacer1);
container.add(printButton);
container.add(spacer2);
}
private JTable setupTable() {
infoTable = new JTable();
DefaultTableModel dm = new DefaultTableModel(0, 0);
String header[] = new String[]{"Case #", "Date", "Officer #", "Offence",
"Description", "Report"};
dm.setColumnIdentifiers(header);
infoTable.setModel(dm);
infoTable.setRowHeight(26);
infoTable.setFocusable(false);//display only
//Adds everything to the table
int idSize = idList.length;
for (int row = 0; row < 10; row++) {
String value = Integer.toString(row);
String[] values = new String[]{value, value, value, value, value, value};
dm.addRow(values);
}
// for (int x = 0; x < idSize; x++) {
// try {
// String[] values = getInfo(idList[x]);
// values[4] = values[4].trim();
// values[4] = values[4].replaceAll("<html>", "");
//
// dm.addRow(values);
// } catch (SQLException e) {
// System.out.println("Error: " + e);
// System.out.println("Event-addObjects(): Problem with getting event info");
// }
//
// infoTable.setFont(new Font("Serif", Font.PLAIN, 10));
// }
//Centers the values on the smaller columns
// DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
// centerRenderer.setHorizontalAlignment(JLabel.CENTER);
// infoTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
// infoTable.getColumnModel().getColumn(1).setCellRenderer(centerRenderer);
// infoTable.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
// infoTable.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
// infoTable.getColumnModel().getColumn(5).setCellRenderer(centerRenderer);
//
// //Sets the sizes of the columns
// infoTable.getColumnModel().getColumn(0).setMinWidth(40);
// infoTable.getColumnModel().getColumn(1).setMinWidth(65);
// infoTable.getColumnModel().getColumn(2).setMinWidth(40);
// infoTable.getColumnModel().getColumn(3).setMinWidth(80);
// infoTable.getColumnModel().getColumn(4).setMinWidth(250);
// infoTable.getColumnModel().getColumn(5).setMinWidth(50);
//Makes the Description column cells JTextFields
// infoTable.getColumnModel().getColumn(4).setCellRenderer(new VariableRowHeightRenderer());
//Looks at the size each JTextField would like to be and changes the rows to accomidate
// int column = 4;
// for (int row = 0; row < infoTable.getRowCount(); row++) {
// int rowHeight = 26;
//
// Component comp = infoTable.prepareRenderer(infoTable.getCellRenderer(row, column), row, column);
// rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
//
// if (rowHeight != infoTable.getRowHeight(row)) {
// infoTable.setRowHeight(row, rowHeight);
// }
// }
// infoTable.setVisible(true);//***********************************************************************
return infoTable;
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
switch (cmd) {
case "Print":
printed = true;
//Makes the margins smaller
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new MediaPrintableArea((float) 8.25, (float) 10.0, (float) 8.5, (float) 11.0, MediaPrintableArea.INCH));
MessageFormat empty = new MessageFormat("");
MessageFormat footerFormat = new MessageFormat("- {0} -");
// printable.print(PrintMode.FIT_WIDTH, empty, footerFormat, true, aset, false);
Paper paper = new Paper();
paper.setImageableArea(0, 0, 700, 890);
paper.setSize(700, 890);
PageFormat format = new PageFormat();
format.setPaper(paper);
format.setOrientation(PageFormat.PORTRAIT);
// printjob.setPrintable(printable, format);
BufferedImage img = new BufferedImage(700, 890, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fill(new Rectangle(0, 0, 890, 700));
Printable printable = infoTable.getPrintable(JTable.PrintMode.FIT_WIDTH, null, null);
try {
printable.print(g2d, format, 0);
} catch (Exception exp) {
exp.printStackTrace();
}
g2d.dispose();
try {
ImageIO.write(img, "png", new File("Print.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
//this.dispose();
break;
default:
break;
}
}
}

Related

How can I resize my JTextFields in my Jpanel

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:

How to make this text area show which toggle buttons are selected?

Please can someone help me, I'm trying to make a seat reservation part for my cinema ticket system assignment ... so the problem is i want the text of the button to show in the text area when selected and not show only the specific text when deselected .. but when i deselect a button the whole text area is cleared.
For e.g. when I select C1, C2, C3 - it shows in the text area correctly, but if I want to deselect C3, the text area must now show only C1 & C2. Instead, it clears the whole text area!
Can anyone spot the problem in the logic?
import java.awt.*;
import static java.awt.Color.blue;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.Border;
public class Cw_Test2 extends JFrame {
JButton btn_payment,btn_reset;
JButton buttons;
JTextField t1,t2;
public static void main(String[] args) {
// TODO code application logic here
new Cw_Test2();
}
public Cw_Test2()
{
Frame();
}
public void Frame()
{
this.setSize(1200,700); //width, height
this.setTitle("Seat Booking");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 6);
Font newFont = myFont.deriveFont(20F);
t1=new JTextField();
t1.setBounds(15, 240, 240,30);
JPanel thePanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
thePanel.setLayout(null);
JPanel ourPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border ourBorder = BorderFactory.createLineBorder(blue , 2);
ourPanel.setBorder(ourBorder);
ourPanel.setLayout(null);
ourPanel.setBounds(50,90, 1100,420);
JPanel newPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border newBorder = BorderFactory.createLineBorder(blue , 1);
newPanel.setBorder(newBorder);
newPanel.setLayout(null);
newPanel.setBounds(790,50, 270,340);
JLabel label1 = new JLabel( new ColorIcon(Color.GRAY, 400, 100) );
label1.setText( "SCREEN" );
label1.setHorizontalTextPosition(JLabel.CENTER);
label1.setVerticalTextPosition(JLabel.CENTER);
label1.setBounds(130,50, 400,30);
JLabel label2 = new JLabel(" CINEMA TICKET MACHINE ");
label2.setBounds(250,50,400,30);
label2.setFont(newFont);
JLabel label3 = new JLabel("Please Select Your Seat");
label3.setBounds(270,10,500,30);
label3.setFont(newFont);
JLabel label4 = new JLabel("Selected Seats:");
label4.setBounds(20,10,200,30);
label4.setFont(newFont);
btn_payment=new JButton("PROCEED TO PAY");
btn_payment.setBounds(35,290,200,30);
JLabel label6 = new JLabel("Center Stall");
label6.setBounds(285,172,200,30);
JPanel seatPane, seatPane1, seatPane2, seatPane3, seatPane4, seatPane5;
JToggleButton[] seat2 = new JToggleButton[8];
JTextArea chosen = new JTextArea();
chosen.setEditable(false);
chosen.setLineWrap(true);
chosen.setBounds(20, 60, 200, 100);
// Center Seats
seatPane1 = new JPanel();
seatPane1.setBounds(200,200,250,65);
seatPane1.setLayout(new FlowLayout());
for(int x=0; x<8; x++){
seat2[x] = new JToggleButton("C"+(x+1));
seatPane1.add(seat2[x]);
seat2[x].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
AbstractButton abstractButton = (AbstractButton) ev.getSource();
boolean selected = abstractButton.getModel().isSelected();
for(int x=0; x<8; x++){
if(seat2[x]==ev.getSource()){
if(selected){
chosen.append(seat2[x].getText()+",");
}else{
chosen.setText(seat2[x].getText().replace(seat2[x].getText(),""));
}
}
}
}
});
}
newPanel.add(chosen);
ourPanel.add(seatPane1);
ourPanel.add(label6);
thePanel.add(label2);
ourPanel.add(label3);
ourPanel.add(label1);
newPanel.add(btn_payment);
newPanel.add(label4);
ourPanel.add(newPanel);
thePanel.add(ourPanel);
add(thePanel);
setResizable(false);
this.setVisible(true);
}
public static class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
When any seat is selected or deselected, this code iterates an array of seats (in the method showSelectedSeats()) and updates the text area to show the seats that are selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CinemaTicketMachine {
private JComponent ui = null;
private JToggleButton[] seats = new JToggleButton[80];
private JTextArea selectedSeats = new JTextArea(3, 40);
CinemaTicketMachine() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
selectedSeats.setLineWrap(true);
selectedSeats.setWrapStyleWord(true);
selectedSeats.setEditable(false);
ui.add(new JScrollPane(selectedSeats), BorderLayout.PAGE_END);
JPanel cinemaFloor = new JPanel(new BorderLayout(40, 0));
cinemaFloor.setBorder(new TitledBorder("Available Seats"));
ui.add(cinemaFloor, BorderLayout.CENTER);
JPanel leftStall = new JPanel(new GridLayout(0, 2, 2, 2));
JPanel centerStall = new JPanel(new GridLayout(0, 4, 2, 2));
JPanel rightStall = new JPanel(new GridLayout(0, 2, 2, 2));
cinemaFloor.add(leftStall, BorderLayout.WEST);
cinemaFloor.add(centerStall, BorderLayout.CENTER);
cinemaFloor.add(rightStall, BorderLayout.EAST);
ActionListener seatSelectionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showSelectedSeats();
}
};
for (int ii=0; ii <seats.length; ii++) {
JToggleButton tb = new JToggleButton("S-" + (ii+1));
tb.addActionListener(seatSelectionListener);
seats[ii] = tb;
int colIndex = ii%8;
if (colIndex<2) {
leftStall.add(tb);
} else if (colIndex<6) {
centerStall.add(tb);
} else {
rightStall.add(tb);
}
}
}
private void showSelectedSeats() {
StringBuilder sb = new StringBuilder();
for (int ii=0; ii<seats.length; ii++) {
JToggleButton tb = seats[ii];
if (tb.isSelected()) {
sb.append(tb.getText());
sb.append(", ");
}
}
String s = sb.toString();
if (s.length()>0) {
s = s.substring(0, s.length()-2);
}
selectedSeats.setText(s);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
CinemaTicketMachine o = new CinemaTicketMachine();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

java swing not printing complete page

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.print.*;
import javax.swing.*;
import javax.swing.table.JTableHeader;
class print implements ActionListener,KeyListener,Printable
{
JTable table,stable;
JTable footer = new JTable(1,6);
JTable table2= new JTable(11,2);;
JPanel panel,panell;
String data[][] = new String[100][6];
JLabel labelf[]=new JLabel[7];
JFrame f;
public static void main(String[] args)
{
new print();
}
print()
{
f = new JFrame("Bill Invoice......");
f.setLayout(null);
JButton jbe = new JButton("Back");
//jbe.setFont(labfont3);
// labfont=new Font("Kunstler Script",Font.BOLD,40);
JLabel la1=new JLabel("SOLD TO :");
JLabel la2=new JLabel("PROFORMA INVOICE");
Font l1=new Font("Times New Roman",Font.BOLD,15);
Font l2=new Font("Times New Roman",Font.BOLD,18);
//Font l3=new Font("Times New Roman",Font.BOLD,15);
la1.setForeground(new Color(138,10,178));
la2.setForeground(new Color(138,10,178));
ImageIcon ic2 = new ImageIcon("vv.jpg");
JLabel piclab2 = new JLabel(ic2);
JButton button = new JButton("Print");
JButton button1 = new JButton("Save");
JButton button2 = new JButton("Finish");
String[] columnheader = {"S.No.", "Description", "Bales Bags", "Weight in Kgs", "Price ", "Total" };
labelf[0]=new JLabel("txt10");
labelf[1]=new JLabel("txt11");
labelf[2]=new JLabel("txt111");
labelf[3]=new JLabel("txtt");
labelf[4]=new JLabel("txt12");
labelf[5]=new JLabel("txtx");
labelf[6]=new JLabel("txty");
table2.getColumnModel().getColumn(0).setPreferredWidth(200);
table2.getColumnModel().getColumn(1).setPreferredWidth(200);
table2.setRowHeight(20);
table2.getModel().setValueAt("INVOICE NO.",0,0);
table2.getModel().setValueAt("txt00",0,1);
table2.getModel().setValueAt("DATE",1,0);
table2.getModel().setValueAt(""+"currentTime",1,1);
table2.getModel().setValueAt("EXPORTRANS REF.",2,0);
table2.getModel().setValueAt("txtz",2,1);
table2.getModel().setValueAt("BOOKING NO.",3,0);
table2.getModel().setValueAt("txt22",3,1);
table2.getModel().setValueAt("CONTAINER NO.",4,0);
table2.getModel().setValueAt("txt33",4,1);
table2.getModel().setValueAt("SEAL NO.",5,0);
table2.getModel().setValueAt("txt44",5,1);
table2.getModel().setValueAt("VESSEL NAME",6,0);
table2.getModel().setValueAt("txt55",6,1);
table2.getModel().setValueAt("SHIPPING LINE",7,0);
table2.getModel().setValueAt("txt66",7,1);
table2.getModel().setValueAt("BILL OF LANDING NO.",8,0);
table2.getModel().setValueAt("txt77",8,1);
table2.getModel().setValueAt("IDF NO.",9,0);
table2.getModel().setValueAt("txt88",9,1);
table2.getModel().setValueAt("IO NO.",10,0);
table2.getModel().setValueAt("txt99",10,1);
table = new JTable(data,columnheader);
//table.setTableHeader(columnNames);
footer.getModel().setValueAt("Total",0,1);
JTableHeader header = table.getTableHeader();
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(header, BorderLayout.NORTH);
panel.add(table, BorderLayout.CENTER);
panel.add(footer,BorderLayout.SOUTH);
table.getTableHeader().setReorderingAllowed(false);
table.setRowHeight(25);
footer.setRowHeight(25);
table.setShowGrid(false);
table.setShowVerticalLines(true);
JScrollPane pane = new JScrollPane(table);
table.getColumnModel().getColumn(0).setPreferredWidth(24);
table.getColumnModel().getColumn(1).setPreferredWidth(200);
//table.getModel().setValueAt(1,0,0);
table.getTableHeader().setPreferredSize(new Dimension(pane.getWidth(),35));
footer.getColumnModel().getColumn(0).setPreferredWidth(13);
footer.getColumnModel().getColumn(1).setPreferredWidth(190);
footer.getColumnModel().getColumn(2).setPreferredWidth(65);
footer.getColumnModel().getColumn(3).setPreferredWidth(65);
footer.getColumnModel().getColumn(4).setPreferredWidth(65);
footer.getColumnModel().getColumn(5).setPreferredWidth(82);
jbe.setBounds(0,0,105,30);
panel.setBounds(180,350,1000,290);
table2.setBounds(780,100,400,220);
panel.add(pane, BorderLayout.CENTER);
la1.setBounds(190,95,150,60);
int y=140;
for(int i=0;i<=6;i++)
{
labelf[i].setFont(l1);
labelf[i].setBounds(190,y,500,20);
y=y+20;
f.add(labelf[i]);
}
la2.setBounds(530,300,300,60);
button1.setBounds(1250,550,100,30);
button.setBounds(1250,600,100,30);
button2.setBounds(1250,650,100,30);
table.setFont(l1);
table2.setFont(l1);
footer.setFont(l1);
la1.setFont(l2);
la2.setFont(l2);
header.setFont(l1);
f.add(jbe);
f.add(la1);
f.add(la2);
f.add(button);
f.add(button1);
f.add(button2);
button.addActionListener(this);
button1.addActionListener(this);
button2.addActionListener(this);
jbe.addActionListener(this);
f.add(panel);
f.add(table2);
piclab2.setBounds(0,0,1366,768);
f.add(piclab2);
f.setSize(1366,768);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0)
{
String s=arg0.getActionCommand( );
if (s.equals("Print"))
{
PrinterJob pj = PrinterJob.getPrinterJob();
PageFormat pf = pj.defaultPage();
Paper paper = new Paper();
paper.setImageableArea(50, 100, 400, 200);
pf.setPaper(paper);
pj.setPrintable(this, pf);
if (pj.printDialog())
{
try
{
pj.print();
}
catch (PrinterException pe)
{
System.err.println("Error printing: " + pe.getMessage());
}
}
}
}
#Override
public int print(Graphics g, PageFormat pf, int page) throws PrinterException
{
if (page > 0)
{
return (NO_SUCH_PAGE);
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
Rectangle rec = f.getBounds();
BufferedImage snapshot = new BufferedImage(rec.width,rec.height,BufferedImage.TYPE_INT_ARGB);
//BufferedImage snapshot = AnimeUtilities.createSnapshotOfFrame(pf, Transparency.TRANSLUCENT);
double scaleX = pf.getWidth()/snapshot.getWidth();
double scaleY = pf.getHeight();///snapshot.getHeight();
double scaleValue = Math.min(scaleX, scaleY);
System.out.println(""+scaleValue);
g2d.scale(scaleValue+0.3, scaleValue+0.3);
table2.print(g2d);
return (PAGE_EXISTS);
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
I have tried too much but this code is printing only some part of my page......i want to print whole page......I am not familier with print commands.....does anybody have idea to print whole page...
Change your buttons x and y to make them appear on form
button1.setBounds(100, 650, 100, 30);
button.setBounds(200, 650, 100, 30);
button2.setBounds(300, 650, 100, 30);
I assume you want to print all the contents of the user interface. You have to make a call to the frame.print() method; NOT table.print() method.
thanks.

ImageManager program

I am working on a project where I have to create an image manager program in Java. The program will have the following features in it: Program should take image from the user as input. Then it should display the image in panel(1), and in panel(2) it should give the user an options of changing width, height, hgap, vgap, top margin and left margin of the image with an 'OK' button at the end including an 'action listener' feature. Using the above mentioned features we will get the grids on the image. Now if the user clicks on the particular grid then that particular image should get extracted into a folder.
I am attaching the program which we have done so far.
The difficulties we are facing are: we are not able to insert a JScrollPane for the image. As well as we are unaware of how to add action listeners to the grids so that we can extract that particular image.
package project_image_manager_imp_files;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
class SidePanel1 extends JPanel implements ActionListener {
JTextField top_margin = new JTextField(10);
JTextField left_margin = new JTextField(10);
JTextField Width = new JTextField(10);
JTextField Height = new JTextField(10);
JTextField Vgap = new JTextField(10);
JTextField Hgap = new JTextField(10);
JLabel j1 = new JLabel("Top margin");
JLabel j2 = new JLabel("Left margin");
JLabel j3 = new JLabel("Width");
JLabel j4 = new JLabel("Height");
JLabel j5 = new JLabel("Vertical gap");
JLabel j6 = new JLabel("Horizontal gap");
JButton b = new JButton("OK");
public SidePanel1() {
this.setBackground(Color.black);
Dimension d1 = new Dimension(1000, 1000);
this.setMaximumSize(d1);
this.setPreferredSize(d1);
JPanel p = new JPanel();
JScrollPane vertical = new JScrollPane();
vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(vertical);
vertical.setVerticalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(vertical);
//showCoo.build(c);
//c.add(p);
//p.setOpaque(false);
//t1.addActionListener(new JTextFieldEventClass() );
//b.addActionListener(new JTextFieldEventClass() );
// String s=t3.getText();
//int c=Integer.parseInt(s);
p.add(j1);
p.add(top_margin);
p.add(j2);
p.add(left_margin);
p.add(j3);
p.add(Width);
p.add(j4);
p.add(Height);
p.add(j5);
p.add(Vgap);
p.add(j6);
p.add(Hgap);
p.add(b);
p.setLayout(new GridLayout(7, 2));
b.addActionListener(this);
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1, 2));
frame.setBounds(200, 200, 600, 400);
frame.setTitle("Hello World Test");
frame.setResizable(true);
//frame.setSize (500, 300);
Container c = frame.getContentPane();
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.WEST);
frame.add(p, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
int height;
int width;
int hgap;
int vgap;
int tm;
int lm;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(Toolkit.getDefaultToolkit().getImage("images1.jpg"), 0, 0, this);
Graphics2D g2d = (Graphics2D) g.create();
//File f=new File("images1.jpg");
//BufferedImage im=ImageIO.read(f);
int frame_width = getWidth();
int frame_height = getHeight();
for (int j = 0; j < frame_height; j++) {
int y = tm + (height * j) + (vgap * j);
for (int i = 0; i < frame_width; i++) {
int x = lm + (width * i) + (hgap * i);
g.drawRect(x, y, width, height);
}
}
}
public static void main(String[] argv) {
//static JScrollBar scrollbar;
SidePanel1 panel = new SidePanel1();
panel.setLayout(new FlowLayout());
//scrollbar = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//panel.add(scrollbar);
try {
while (true) {
Thread.sleep(100);
///.out.println("("+MouseInfo.getPointerInfo().getLocation().x+", "+MouseInfo.getPointerInfo().getLocation().y+")");
}
} catch (InterruptedException e) {}
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
width = Integer.parseInt(Width.getText());
height = Integer.parseInt(Height.getText());
hgap = Integer.parseInt(Hgap.getText());
vgap = Integer.parseInt(Vgap.getText());
lm = Integer.parseInt(left_margin.getText());
tm = Integer.parseInt(top_margin.getText());
repaint();
}
}

JScrollPane inside JPanel inside a JTabbedPane is not scrolling

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

Categories