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();
}
});
}
}
Related
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;
}
}
}
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:
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);
}
}
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();
}
});
}
}
Can someone please tell me what's wrong with this code?
I need it to pop up a frame and fill the frame with certain field a namer field and an intake field and also display a button at the bottom of the grid.
Any help would be welcomed, Thanks!!
import java.awt.*;
import javax.swing.*;
public class FrameDemo
//To create the gui and show it.
{
public static void createAndShowGUI()
{
//create and set up the window.
JFrame frame = new JFrame("RungeKutta");
GridLayout first = new GridLayout(1,14);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create, name and Populate TextField
JTextField PL = new JTextField("Pendulum Length", 20);
//Set TextField to Uneditable. Each will have Empty Field Below For Variables
PL.setEditable(false);
//Set Textfield for user entered dat
JTextField PLv = new JTextField();
//Allow handler for user input on Empty Textfield?
JTextField AD = new JTextField("Angular Displacement", 20);
AD.setEditable(false);
JTextField ADv = new JTextField();
JTextField AV = new JTextField("Angular Velocity", 20);
AV.setEditable(false);
JTextField Avv = new JTextField();
JTextField TS= new JTextField("Time Steps", 20);
TS.setEditable(false);
JTextField TSv = new JTextField();
JTextField MT = new JTextField("Max Time", 20);
MT.setEditable(false);
JTextField MTv = new JTextField();
JTextField V = new JTextField("Viscosity (0-1)", 20);
V.setEditable(false);
JTextField Vv = new JTextField();
//Create Button to Restart
JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600,500));
frame.getContentPane().add(PL, first);
frame.getContentPane().add(PLv, first);
frame.getContentPane().add(AD, first);
frame.getContentPane().add(ADv, first);
frame.getContentPane().add(AV, first);
frame.getContentPane().add(Avv, first);
frame.getContentPane().add(TS, first);
frame.getContentPane().add(TSv, first);
frame.getContentPane().add(MT, first);
frame.getContentPane().add(MTv, first);
frame.getContentPane().add(V, first);
frame.getContentPane().add(Vv, first);
frame.getContentPane().add(BNewGraph, first);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
//add job to event scheduler
//create and show GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This is not how you use GridLayout:
frame.getContentPane().add(PL, first);
Instead you'd set the container's layout using the layout manager:
frame.getContentPane().setLayout(first);
and then add components to the container:
frame.getContentPane().add(PL);
frame.getContentPane().add(PLv);
frame.getContentPane().add(AD);
frame.getContentPane().add(ADv);
frame.getContentPane().add(AV);
frame.getContentPane().add(Avv);
frame.getContentPane().add(TS);
frame.getContentPane().add(TSv);
frame.getContentPane().add(MT);
frame.getContentPane().add(MTv);
// and so on for all the components.
You will want to read the tutorial on how to use GridLayout which you can find here: GridLayout Tutorial.
As an aside, note that this:
frame.getContentPane().add(PL);
can be shortened to this:
frame.add(PL);
Also you will want to study and learn Java naming conventions: class names begin with an upper case letter and all method and variables with lower case letters. Also avoid variable names like pl or plv, or ad or adv, and instead use names that are a little bit longer and have meaning, names that make your code self-commenting. So instead of AD, consider angularDisplacementField for the JTextfield's name.
Myself, I'd use a GridBagLayout and do something like:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.*;
public class GuiDemo extends JPanel {
// or better -- use an enum for this
public static final String[] FIELD_LABELS = {
"Pendulum Length", "Angular Displacement", "Angular Velocity",
"Time Steps", "Max Time", "Viscocity (0-1)"
};
private static final int TEXT_FIELD_COLUMNS = 10;
private static final int GAP = 3;
private static final Insets RIGHT_GAP_INSETS = new Insets(GAP, GAP, GAP, 3 * GAP);
private static final Insets BALANCED_INSETS = new Insets(GAP, GAP, GAP, GAP);
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public GuiDemo() {
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
int row = 0;
// to make sure that no focusAccelerator is re-used
Set<Character> focusAccelSet = new HashSet<>();
for (String fieldLabelLText : FIELD_LABELS) {
JLabel fieldLabel = new JLabel(fieldLabelLText);
JTextField textField = new JTextField(TEXT_FIELD_COLUMNS);
labelFieldPanel.add(fieldLabel, getGbc(row, 0));
labelFieldPanel.add(textField, getGbc(row, 1));
labelFieldMap.put(fieldLabelLText, textField);
for (char c : fieldLabelLText.toCharArray()) {
if (!focusAccelSet.contains(c)) {
textField.setFocusAccelerator(c);
fieldLabel.setDisplayedMnemonic(c);
focusAccelSet.add(c);
break;
}
}
row++;
}
JButton button = new JButton(new DrawGraphAction("Draw New Graph"));
labelFieldPanel.add(button, getGbc(row, 0, 2, 1));
setLayout(new BorderLayout(GAP, GAP));
add(labelFieldPanel, BorderLayout.CENTER);
}
private class DrawGraphAction extends AbstractAction {
public DrawGraphAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO calculation method
}
}
public static GridBagConstraints getGbc(int row, int column) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = column;
gbc.gridy = row;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
if (column == 0) {
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = RIGHT_GAP_INSETS;
} else {
gbc.anchor = GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = BALANCED_INSETS;
}
return gbc;
}
public static GridBagConstraints getGbc(int row, int column, int width, int height) {
GridBagConstraints gbc = getGbc(row, column);
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.insets = BALANCED_INSETS;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Gui Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GuiDemo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}