I have a jframe with page navigation buttons,print,search buttons.When i clicked on the print button it is perfectly opening the window and i am able to print the page also.But when i clicked on search button i am not able to get the window.My requirement is clicking on the Search button should open a window(same as print window) with text field and when i enter the search data then it should display the matches and unmatches.
I have tried the below code but i am not succeed.
import com.google.common.base.CharMatcher;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import com.sun.pdfview.PagePanel;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import static com.google.common.base.Strings.isNullOrEmpty;
public class PdfViewer extends JPanel {
private static enum Navigation {
GO_FIRST_PAGE, FORWARD, BACKWARD, GO_LAST_PAGE, GO_N_PAGE
}
private static final CharMatcher POSITIVE_DIGITAL = CharMatcher.anyOf("0123456789");
private static final String GO_PAGE_TEMPLATE = "%s of %s";
private static final int FIRST_PAGE = 1;
private int currentPage = FIRST_PAGE;
private JButton btnFirstPage;
private JButton btnPreviousPage;
private JTextField txtGoPage;
private JButton btnNextPage;
private JButton btnLastPage;
private JButton print;
private JButton search;
private PagePanel pagePanel;
private PDFFile pdfFile;
public PdfViewer() {
initial();
}
private void initial() {
setLayout(new BorderLayout(0, 0));
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
add(topPanel, BorderLayout.NORTH);
btnFirstPage = createButton("|<<");
topPanel.add(btnFirstPage);
btnPreviousPage = createButton("<<");
topPanel.add(btnPreviousPage);
txtGoPage = new JTextField(10);
txtGoPage.setHorizontalAlignment(JTextField.CENTER);
topPanel.add(txtGoPage);
btnNextPage = createButton(">>");
topPanel.add(btnNextPage);
btnLastPage = createButton(">>|");
topPanel.add(btnLastPage);
print = new JButton("print");
topPanel.add(print);
search = new JButton("search");
topPanel.add(search);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
JPanel viewPanel = new JPanel(new BorderLayout(0, 0));
scrollPane.setViewportView(viewPanel);
pagePanel = new PagePanel();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
pagePanel.setPreferredSize(screenSize);
viewPanel.add(pagePanel, BorderLayout.CENTER);
disableAllNavigationButton();
btnFirstPage.addActionListener(new PageNavigationListener(Navigation.GO_FIRST_PAGE));
btnPreviousPage.addActionListener(new PageNavigationListener(Navigation.BACKWARD));
btnNextPage.addActionListener(new PageNavigationListener(Navigation.FORWARD));
btnLastPage.addActionListener(new PageNavigationListener(Navigation.GO_LAST_PAGE));
txtGoPage.addActionListener(new PageNavigationListener(Navigation.GO_N_PAGE));
print.addActionListener(new PrintUIWindow());
search.addActionListener(new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
}
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.setPreferredSize(new Dimension(55, 20));
return button;
}
private void disableAllNavigationButton() {
btnFirstPage.setEnabled(false);
btnPreviousPage.setEnabled(false);
btnNextPage.setEnabled(false);
btnLastPage.setEnabled(false);
}
private boolean isMoreThanOnePage(PDFFile pdfFile) {
return pdfFile.getNumPages() > 1;
}
private class PageNavigationListener implements ActionListener {
private final Navigation navigation;
private PageNavigationListener(Navigation navigation) {
this.navigation = navigation;
}
public void actionPerformed(ActionEvent e) {
if (pdfFile == null) {
return;
}
int numPages = pdfFile.getNumPages();
if (numPages <= 1) {
disableAllNavigationButton();
} else {
if (navigation == Navigation.FORWARD && hasNextPage(numPages)) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_LAST_PAGE) {
goPage(numPages, numPages);
}
if (navigation == Navigation.BACKWARD && hasPreviousPage()) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_FIRST_PAGE) {
goPage(FIRST_PAGE, numPages);
}
if (navigation == Navigation.GO_N_PAGE) {
String text = txtGoPage.getText();
boolean isValid = false;
if (!isNullOrEmpty(text)) {
boolean isNumber = POSITIVE_DIGITAL.matchesAllOf(text);
if (isNumber) {
int pageNumber = Integer.valueOf(text);
if (pageNumber >= 1 && pageNumber <= numPages) {
goPage(Integer.valueOf(text), numPages);
isValid = true;
}
}
}
if (!isValid) {
JOptionPane.showMessageDialog(PdfViewer.this,
format("Invalid page number '%s' in this document", text));
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
}
}
}
}
private void goPage(int pageNumber, int numPages) {
currentPage = pageNumber;
PDFPage page = pdfFile.getPage(currentPage);
pagePanel.showPage(page);
boolean notFirstPage = isNotFirstPage();
btnFirstPage.setEnabled(notFirstPage);
btnPreviousPage.setEnabled(notFirstPage);
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
boolean notLastPage = isNotLastPage(numPages);
btnNextPage.setEnabled(notLastPage);
btnLastPage.setEnabled(notLastPage);
}
private boolean hasNextPage(int numPages) {
return (++currentPage) <= numPages;
}
private boolean hasPreviousPage() {
return (--currentPage) >= FIRST_PAGE;
}
private boolean isNotLastPage(int numPages) {
return currentPage != numPages;
}
private boolean isNotFirstPage() {
return currentPage != FIRST_PAGE;
}
}
private class PrintUIWindow implements Printable, ActionListener {
/*
* (non-Javadoc)
*
* #see java.awt.print.Printable#print(java.awt.Graphics,
* java.awt.print.PageFormat, int)
*/
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int pagenum = pageIndex+1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages ())
return NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) graphics;
AffineTransform at = g2d.getTransform ();
PDFPage pdfPage = pdfFile.getPage (pagenum);
Dimension dim;
dim = pdfPage.getUnstretchedSize ((int) pageFormat.getImageableWidth (),
(int) pageFormat.getImageableHeight (),
pdfPage.getBBox ());
Rectangle bounds = new Rectangle ((int) pageFormat.getImageableX (),
(int) pageFormat.getImageableY (),
dim.width,
dim.height);
PDFRenderer rend = new PDFRenderer (pdfPage, (Graphics2D) graphics, bounds,
null, null);
try
{
pdfPage.waitForFinish ();
rend.run ();
}
catch (InterruptedException ie)
{
//JOptionPane.showMessageDialog (this, ie.getMessage ());
}
g2d.setTransform (at);
g2d.draw (new Rectangle2D.Double (pageFormat.getImageableX (),
pageFormat.getImageableY (),
pageFormat.getImageableWidth (),
pageFormat.getImageableHeight ()));
return PAGE_EXISTS;
}
/*
* (non-Javadoc)
*
* #see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
* )
*/
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Inside action performed");
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
try
{
HashPrintRequestAttributeSet attset;
attset = new HashPrintRequestAttributeSet ();
//attset.add (new PageRanges (1, pdfFile.getNumPages ()));
if (printJob.printDialog (attset))
printJob.print (attset);
}
catch (PrinterException pe)
{
//JOptionPane.showMessageDialog (this, pe.getMessage ());
}
}
}
public PagePanel getPagePanel() {
return pagePanel;
}
public void setPDFFile(PDFFile pdfFile) {
this.pdfFile = pdfFile;
currentPage = FIRST_PAGE;
disableAllNavigationButton();
txtGoPage.setText(format(GO_PAGE_TEMPLATE, FIRST_PAGE, pdfFile.getNumPages()));
boolean moreThanOnePage = isMoreThanOnePage(pdfFile);
btnNextPage.setEnabled(moreThanOnePage);
btnLastPage.setEnabled(moreThanOnePage);
}
public static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
public static void main(String[] args) {
try {
long heapSize = Runtime.getRuntime().totalMemory();
System.out.println("Heap Size = " + heapSize);
JFrame frame = new JFrame("PDF Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// load a pdf from a byte buffer
File file = new File("/home/swarupa/Downloads/2626OS-Chapter-5-Advanced-Theme.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
final PDFFile pdffile = new PDFFile(buf);
PdfViewer pdfViewer = new PdfViewer();
pdfViewer.setPDFFile(pdffile);
frame.add(pdfViewer);
frame.pack();
frame.setVisible(true);
PDFPage page = pdffile.getPage(0);
pdfViewer.getPagePanel().showPage(page);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Where i am doing wrong.Can any one point me.
I think, that this should solve your problem ;) You've forgotten to set the window to be visible :)
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
parent.setVisible(true);
}
}
Btw-why do you create that JDialog?
You create JDialog and JFrame, why? You never call setVisible(true), why?
What you expect from the Action1?
Sorry for posting this answer to your comment as a new post, but it was too long to post it as a comment. You just can't remove close and minimize buttons from JFrame. If you want some window without those buttons, you have to create and customize your own JDialog. Nevertheless there will still be a close button (X). You can make your JDialog undecorated and make it to behave more like JFrame when you implement something like this:
class CustomizedDialog extends JDialog {
public CustomizedDialog(JFrame frame, String str) {
super(frame, str);
super.setUndecorated(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
And then you can call it in your code with this:
CustomizedDialog myCustomizedDialog = new CustomizedDialog(new JFrame(), "My title");
JPanel panel = new JPanel();
panel.setSize(256, 256);
myCustomizedDialog.add(panel);
myCustomizedDialog.setSize(256, 256);
myCustomizedDialog.setLocationRelativeTo(null);
myCustomizedDialog.setVisible(true);
I hope, this helps :)
Related
I have the code for my print preview
package printprew;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.print.*;
import javax.swing.border.*;
public class PrintPrew extends JFrame implements ActionListener, ChangeListener, ItemListener {
JButton print = new JButton("Print"),
printThisPage = new JButton("Print Current Page"),
cancel = new JButton("Close");
Pageable pg = null;
double scale = 1.0;
JSlider slider = new JSlider();
Page page[] = null;
JComboBox jcb = new JComboBox();
CardLayout cl = new CardLayout();
JPanel p = new JPanel(cl);
JButton back = new JButton("<<"), forward = new JButton(">>");
public PrintPrew(Pageable pg) {
super("Print Preview");
this.pg = pg;
createPreview();
}
public PrintPrew(final Printable pr, final PageFormat p) {
super("Print Preview");
this.pg = new Pageable() {
public int getNumberOfPages() {
Graphics g = new java.awt.image.BufferedImage(2,2,java.awt.image.BufferedImage.TYPE_INT_RGB).getGraphics();
int n=0;
try { while(pr.print(g, p, n) == pr.PAGE_EXISTS) n++; }
catch(Exception ex) {ex.printStackTrace();}
return n;
}
public PageFormat getPageFormat(int x) { return p; }
public Printable getPrintable(int x) { return pr; }
};
createPreview();
}
private void createPreview() {
page = new Page[pg.getNumberOfPages()];
FlowLayout fl = new FlowLayout();
PageFormat pf = pg.getPageFormat(0);
Dimension size = new Dimension((int)pf.getPaper().getWidth(), (int)pf.getPaper().getHeight());
if(pf.getOrientation() != PageFormat.PORTRAIT)
size = new Dimension(size.height, size.width);
JPanel temp = null;
for(int i=0; i<page.length; i++) {
jcb.addItem(""+(i+1));
page[i] = new Page(i, size);
p.add(""+(i+1), new JScrollPane(page[i]));
}
setTopPanel();
this.getContentPane().add(p, "Center");
Dimension d = this.getToolkit().getScreenSize();
this.setSize(d.width,d.height-60);
slider.setSize(this.getWidth()/2, slider.getPreferredSize().height);
this.setVisible(true);
page[jcb.getSelectedIndex()].refreshScale();
}
private void setTopPanel() {
FlowLayout fl = new FlowLayout();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
JPanel topPanel = new JPanel(gbl), temp = new JPanel(fl); slider.setBorder(new TitledBorder("Percentage Zoom"));
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMinimum(0);
slider.setMaximum(500);
slider.setValue(100);
slider.setMinorTickSpacing(20);
slider.setMajorTickSpacing(100);
slider.addChangeListener(this);
back.addActionListener(this);
forward.addActionListener(this);
back.setEnabled(false);
forward.setEnabled(page.length > 1);
gbc.gridx = 0;
gbc.gridwidth = 1;
gbl.setConstraints(slider, gbc);
topPanel.add(slider);
temp.add(back);
temp.add(jcb);
temp.add(forward);
temp.add(cancel);
temp.add(print);
temp.add(printThisPage);
gbc.gridx = 1;
gbc.gridwidth = 2;
gbl.setConstraints(temp, gbc);
topPanel.add(temp);
print.addActionListener(this);
printThisPage.addActionListener(this);
cancel.addActionListener(this);
jcb.addItemListener(this);
print.setMnemonic('P');
cancel.setMnemonic('C');
printThisPage.setMnemonic('U');
this.getContentPane().add(topPanel, "North");
}
public void itemStateChanged(ItemEvent ie) {
cl.show(p, (String)jcb.getSelectedItem());
page[jcb.getSelectedIndex()].refreshScale();
back.setEnabled(jcb.getSelectedIndex() == 0 ? false: true);
forward.setEnabled(jcb.getSelectedIndex() == jcb.getItemCount()-1 ? false:true);
this.validate();
} public void actionPerformed(ActionEvent ae) {
Object o = ae.getSource();
if(o == print) {
try {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.defaultPage(pg.getPageFormat(0));
pj.setPageable(pg);
if(pj.printDialog())
pj.print();
}
catch(Exception ex) {
JOptionPane.showMessageDialog(null,ex.toString(), "Error in Printing",1);
}
}
else if(o == printThisPage)
printCurrentPage();
else if(o == back) {
jcb.setSelectedIndex(jcb.getSelectedIndex() == 0 ? 0:jcb.getSelectedIndex()-1);
if(jcb.getSelectedIndex() == 0)
back.setEnabled(false);
}
else if(o == forward) {
jcb.setSelectedIndex(jcb.getSelectedIndex() == jcb.getItemCount()-1 ? 0:jcb.getSelectedIndex()+1);
if(jcb.getSelectedIndex() == jcb.getItemCount()-1)
forward.setEnabled(false);
}
else if(o == cancel) this.dispose();
}
public void printCurrentPage() {
try {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.defaultPage(pg.getPageFormat(0));
pj.setPrintable(new PsuedoPrintable());
javax.print.attribute.HashPrintRequestAttributeSet pra =
new javax.print.attribute.HashPrintRequestAttributeSet();
if(pj.printDialog(pra))
pj.print(pra);
}
catch(Exception ex) {
JOptionPane.showMessageDialog(null,ex.toString(), "Error in Printing", 1);
}
}
public void stateChanged(ChangeEvent ce) {
double temp = (double)slider.getValue()/100.0;
if(temp == scale)
return;
if(temp == 0) temp = 0.01;
scale = temp;
page[jcb.getSelectedIndex()].refreshScale();
this.validate();
}
class Page extends JLabel {
final int n;
final PageFormat pf;
java.awt.image.BufferedImage bi = null;
Dimension size = null;
public Page(int x, Dimension size) {
this.size = size;
bi = new java.awt.image.BufferedImage(size.width, size.height, java.awt.image.BufferedImage.TYPE_INT_RGB);
n = x;
pf = pg.getPageFormat(n);
Graphics g = bi.getGraphics();
Color c = g.getColor();
g.setColor(Color.white);
g.fillRect(0, 0, (int)pf.getWidth(), (int)pf.getHeight());
g.setColor(c);
try {
g.clipRect(0, 0, (int)pf.getWidth(), (int)pf.getHeight());
pg.getPrintable(n).print(g, pf, n);
}
catch(Exception ex) { }
this.setIcon(new ImageIcon(bi));
}
public void refreshScale() {
if(scale != 1.0)
this.setIcon(new ImageIcon(bi.getScaledInstance((int)(size.width*scale), (int)(size.height*scale), bi.SCALE_FAST)));
else
this.setIcon(new ImageIcon(bi));
this.validate();
}
}
class PsuedoPrintable implements Printable {
public int print(Graphics g, PageFormat fmt, int index) {
if(index > 0) return Printable.NO_SUCH_PAGE;
int n = jcb.getSelectedIndex();
try { return pg.getPrintable(n).print(g, fmt, n); }
catch(Exception ex) {}
return Printable.PAGE_EXISTS;
}
}
}
And my test class for printPrew
package printprew;
import javax.swing.*;
import java.awt.event.*;
import java.awt.print.*;
import java.text.*;
public class TestPr extends JFrame implements ActionListener{
PrinterJob pj = PrinterJob.getPrinterJob();
javax.print.attribute.HashPrintRequestAttributeSet att =
new javax.print.attribute.HashPrintRequestAttributeSet();
JEditorPane tp = null;
JTable tab = null;
public TestPr() {
super("Печать");
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp.setBottomComponent(createTable());
java.awt.Dimension d = this.getToolkit().getScreenSize();
this.setSize(d.width/2, d.height);
this.getContentPane().add(sp);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
sp.setDividerLocation(0.5);
this.validate();
}
private JPanel createTable() {
String val[][] = {{"т1", "тт1"}, {"т2","тт2"},{"т3","тт3"},
{"т4","тт4"}, {"т5","тт5"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},
{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},
{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},
{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},
{"т6","тт6"},{"т6","тт6"},{"т6","тт6"},{"т7","тт7"},{"т7","тт7"},
{"т7","тт7"},{"т7","тт7"},{"т7","тт7"},{"т7","тт7"},{"т7","тт7"}
};
String title[] = {"стобл1_назв","столб2_назв"};
tab = new JTable(val,title);
tab.setRowHeight(25);
tab.setFont(new java.awt.Font("Times New Roman",java.awt.Font.BOLD,16));
JButton b = new JButton("Просмотр таблицы");
b.addActionListener(this);
JPanel p = new JPanel(new java.awt.BorderLayout()), top = new JPanel(new java.awt.FlowLayout());
top.add(b);
p.add(top, "North");
p.add(new JScrollPane(tab), "Center");
return p;
}
public void actionPerformed(ActionEvent ae) {
PageFormat pf= pj.getPageFormat(att);
pf.setOrientation(PageFormat.LANDSCAPE);
new PrintPrew(tab.getPrintable(javax.swing.JTable.PrintMode.FIT_WIDTH,
new MessageFormat("Накладная"), new MessageFormat("{0}")),pf);
}
public static void main(String arg[]) {
new TestPr();
}
}
This table was created just for test my printPreview class. This table has 3 page. But my print prew all time show just last page. If I change the page for preview, it show same last page, but change number of page... And when I print same problem. Averytime print last page of table, just change the number of page. If I print whole document, it print 3 times last page with different number in the buttom.
What need to change?((
I have a swing application where the user inputs a number into two of the three fields, and my application does Pythagoras Theorem on those two numbers, and sets the answer field with the answer. However, the three fields (hypotenuse, short side 1, short side 2) are all returning 0 (shorter side 1 and shorter side 2 are different fields, forgot to add the : there), and 0 is the default value. This is not the case for other windows, this is only the case for the Maths tab. My question is, what is the problem?
Here is a screenshot of the error:
And here is the code:
Entry.java
package Entry;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenuBar;
import Settings.SettingsLoader;
import Window.ErrorWindow;
import Window.SmallLinkWindow;
import Window.Window;
import Window.WindowEntry;
public class Entry {
public static JFrame frame;
public static File file;
public static JInternalFrame currentframe;
public static void main(String[] args){
file = new File("settings.txt");
frame = new JFrame("GUI_Base");
JMenuBar menu = new JMenuBar();
JMenuBar bottom = new JMenuBar();
SmallLinkWindow[] smallwindows = WindowEntry.getSmallWindows();
for(int i = 0; i < smallwindows.length; i++){
SmallLinkWindow window = smallwindows[i];
JButton button = window.getButton(); //ActionListener already added at this point.
button.addActionListener(getActionListener(window));
bottom.add(button);
}
List<String> data = readAllData();
SettingsLoader loader = new SettingsLoader(data);
loader.obtainSettings();
Window[] windows = WindowEntry.getAllWindows();
for(int i = 0; i < windows.length; i++){
Window window = windows[i];
JButton item = new JButton(window.getName());
item.addActionListener(getActionListener(window));
menu.add(item);
}
currentframe = windows[0].getInsideFrame();
menu.add(getRefresh(), BorderLayout.EAST);
frame.setSize(2000, 1000);
frame.add(menu, BorderLayout.NORTH);
frame.add(bottom, BorderLayout.SOUTH);
frame.getRootPane().setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("Loaded!");
}
private static JButton getRefresh() {
try {
BufferedImage image = ImageIO.read(new File("refresh.png"));
int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
image = resizeImage(image, type, 25, 25);
ImageIcon icon = new ImageIcon(image);
JButton label = new JButton(icon);
label.addActionListener(getActionListener());
return label;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static ActionListener getActionListener() {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
frame.repaint();
}
};
}
//Copied from http://www.mkyong.com/java/how-to-resize-an-image-in-java/
public static BufferedImage resizeImage(BufferedImage originalImage, int type, int width, int height){
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
private static ActionListener getActionListener(SmallLinkWindow window) {
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
Entry.frame.remove(currentframe);
JInternalFrame frame = window.getInsideFrame();
frame.setSize(1400, 925);
Entry.frame.add(frame);
currentframe = frame;
frame.setVisible(true);
}
};
return listener;
}
private static ActionListener getActionListener(Window window) {
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
Entry.frame.remove(currentframe);
JInternalFrame frame = window.getInsideFrame();
frame.setSize(1400, 925);
Entry.frame.add(frame);
currentframe = frame;
frame.setVisible(true);
}
};
return listener;
}
private static List<String> readAllData() {
try {
return Files.readAllLines(file.toPath());
} catch (IOException e) {
ErrorWindow.forException(e);
}
ErrorWindow.forException(new RuntimeException("Unable to read file!"));
System.exit(1);
return null;
}
}
MathWindow.java
package Window;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import Math.Pythagoras;
import Math.Trig;
import Math.TrigValue;
import Math.TrigonometryException;
import Settings.GUISetting;
public class MathWindow implements Window {
private Color colour;
private JSplitPane splitPane;
#Override
public String getName() {
return "Maths";
}
#Override
public JInternalFrame getInsideFrame() {
JInternalFrame frame = new JInternalFrame();
JSplitPane pane = new JSplitPane();
pane.setDividerLocation(300);
JPanel panel = new JPanel();
panel.setSize(300, 925);
JButton pyth = new JButton();
JButton trig = new JButton();
pyth.setText("Pythagoars theorem");
trig.setText("Trigonometry");
pyth.setSize(300, 200);
trig.setSize(300, 200);
pyth.addActionListener(getActionListenerForPythagoras());
trig.addActionListener(getActionListenerForTrignomotry());
panel.setLayout(new GridLayout(0,1));
panel.add(pyth);
panel.add(trig);
pane.setLeftComponent(panel);
splitPane = pane;
frame.getContentPane().add(pane);
return frame;
}
private ActionListener getActionListenerForPythagoras() {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
JPanel overseePanel = new JPanel();
JTextField hypField = new JTextField();
JTextField aField = new JTextField();
JTextField bField = new JTextField();
JLabel hypLabel = new JLabel();
JLabel aLabel = new JLabel();
JLabel bLabel = new JLabel();
JButton button = new JButton();
JTextField field = new JTextField();
hypLabel.setText("Hypotenuse");
aLabel.setText("Small side 1");
bLabel.setText("Small side 2");
hypLabel.setSize(400, hypLabel.getHeight());
aLabel.setSize(400, aLabel.getHeight());
bLabel.setSize(400, bLabel.getHeight());
hypField.setText("0");
aField.setText("0");
bField.setText("0");
hypField.setSize(400, hypLabel.getHeight());
aField.setSize(400, aLabel.getHeight());
bField.setSize(400, bLabel.getHeight());
button.setText("Work it out!");
button.addActionListener(getActionListenerForPythagorasFinal(hypField.getText(), aField.getText(), bField.getText(), field));
overseePanel.setLayout(new GridLayout(0,1));
overseePanel.add(hypLabel, BorderLayout.CENTER);
overseePanel.add(hypField, BorderLayout.CENTER);
overseePanel.add(aLabel, BorderLayout.CENTER);
overseePanel.add(aField, BorderLayout.CENTER);
overseePanel.add(bLabel, BorderLayout.CENTER);
overseePanel.add(bField, BorderLayout.CENTER);
overseePanel.add(button);
overseePanel.add(field);
splitPane.setRightComponent(overseePanel);
}
};
}
protected ActionListener getActionListenerForPythagorasFinal(String hyp, String s1, String s2, JTextField field) {
return new ActionListener(){
private Pythagoras p = new Pythagoras();
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Hypotenuse: " + hyp);
System.out.println("Shorter side 1" + s1);
System.out.println("Shorter side 2" + s2);
if(hyp.equals("0")){
double a = Double.parseDouble(s1);
double b = Double.parseDouble(s2);
if(a == 3 && b == 4 || a == 4 && b == 3) System.out.println("The result should be 5!");
field.setText(String.valueOf(p.getHypotenuse(a, b)));
}else if(s1.equals("0")){
double c = Double.parseDouble(hyp);
double b = Double.parseDouble(s2);
field.setText(String.valueOf(p.getShorterSide(b, c)));
}else if(s2.equals("0")){
double c = Double.parseDouble(hyp);
double a = Double.parseDouble(s1);
field.setText(String.valueOf(p.getShorterSide(a, c)));
}else throw new IllegalArgumentException("All of the fields have stuff in them!");
}
};
}
private ActionListener getActionListenerForTrignomotry(){
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel overseePanel = new JPanel();
JTextField hypField = new JTextField();
JTextField aField = new JTextField();
JTextField bField = new JTextField();
JTextField anField = new JTextField();
JLabel hypLabel = new JLabel();
JLabel aLabel = new JLabel();
JLabel bLabel = new JLabel();
JLabel anLabel = new JLabel();
JButton button = new JButton();
JTextField field = new JTextField();
hypLabel.setText("Hypotenuse");
aLabel.setText("Opposite");
bLabel.setText("Adjacent");
anLabel.setText("Angle size");
hypLabel.setSize(400, hypLabel.getHeight());
aLabel.setSize(400, aLabel.getHeight());
bLabel.setSize(400, bLabel.getHeight());
anLabel.setSize(400, anLabel.getHeight());
hypField.setText("0");
aField.setText("0");
bField.setText("0");
anField.setText("0");
hypField.setSize(400, hypLabel.getHeight());
aField.setSize(400, aLabel.getHeight());
bField.setSize(400, bLabel.getHeight());
anField.setSize(400, anLabel.getHeight());
button.setText("Work it out!");
button.addActionListener(getActionListenerForTrigonomotryFinal(hypField.getText(), aField.getText(), bField.getText(), anField.getText(), field));
overseePanel.setLayout(new GridLayout(0,1));
overseePanel.add(hypLabel, BorderLayout.CENTER);
overseePanel.add(hypField, BorderLayout.CENTER);
overseePanel.add(aLabel, BorderLayout.CENTER);
overseePanel.add(aField, BorderLayout.CENTER);
overseePanel.add(bLabel, BorderLayout.CENTER);
overseePanel.add(bField, BorderLayout.CENTER);
overseePanel.add(anLabel, BorderLayout.CENTER);
overseePanel.add(anField, BorderLayout.CENTER);
overseePanel.add(button);
overseePanel.add(field);
splitPane.setRightComponent(overseePanel);
}
};
}
//a == opposite, b == adjacent
protected ActionListener getActionListenerForTrigonomotryFinal(String hyp,
String a, String b, String an, JTextField field) {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Trig trigonometry = new Trig();
double value = 0.000;
if(an == "0"){
if(hyp == "0"){
int shorta = Integer.parseInt(a);
int shortb = Integer.parseInt(b);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
value = trigonometry.getAngleSize(tA, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(a == "0"){
int hypotenuse = Integer.parseInt(hyp);
int shortb = Integer.parseInt(b);
try {
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, hypotenuse);
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
value = trigonometry.getAngleSize(tH, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b == "0"){
int hypotenuse = Integer.parseInt(hyp);
int shorta = Integer.parseInt(a);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, hypotenuse);
value = trigonometry.getAngleSize(tA, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}
}else{
int angle = Integer.parseInt(an);
if(angle >= 90) throw new IllegalArgumentException("Angle is bigger than 90");
if(hyp.equals("0")){
if(a.equals("?")){
int shortb = Integer.parseInt(b);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
TrigValue tA = new TrigValue(TrigValue.OPPOSITE);
value = trigonometry.getSideLength(tB, angle, tA);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b.equals("?")){
int shorta = Integer.parseInt(a);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT);
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
value = trigonometry.getSideLength(tA, angle, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else throw new IllegalArgumentException("We already know what we want to know.");
}else if(a.equals("0")){
if(hyp.equals("?")){
int shortb = Integer.parseInt(b);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE);
value = trigonometry.getSideLength(tB, angle, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b.equals("?")){
int h = Integer.parseInt(hyp);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, h);
value = trigonometry.getSideLength(tH, angle, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else throw new IllegalArgumentException("We already know what we want to know.");
}else if(b.equals("0")){
if(hyp.equals("?")){
int shorta = Integer.parseInt(a);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE);
value = trigonometry.getSideLength(tA, angle, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(a.equals("?")){
int h = Integer.parseInt(hyp);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, h);
value = trigonometry.getSideLength(tH, angle, tA);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}
}
}
field.setText(String.valueOf(value));
}
};
}
#Override
public GUISetting[] getSettings() {
GUISetting setting = new GUISetting("Show working", "Maths");
GUISetting setting2 = new GUISetting("Round", "Maths");
return new GUISetting[]{setting, setting2};
}
#Override
public void setColour(Color c) {
colour = c;
}
#Override
public Color getCurrentColour() {
return colour;
}
}
If I need to add anything else please add a comment.
You create a new instance of JTextField, you then pass it's text property to the getActionListenerForPythagorasFinal method, so it no longer has what "will" be entered into the fields, only what it's initial value is (""), thus it's completely unable to perform the calculation on the fields in question
You could try passing the fields themselves to the method instead, but as a general piece of advice, I would create a custom class which contains the fields and associated actions which you can create whenever you need it, making significantly easier to manage and maintain
Here is my code. I want to know which l was clicked and then in a new frame, display that ImageIcon.
The e.getSource() is not working...
final JFrame shirts = new JFrame("T-shirts");
JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3));
for (int i = 1; i < 13; i++) {
l = new JLabel(new ImageIcon("T-shirts/"+i+".jpg"), JLabel.CENTER);
l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
l.setFont(l.getFont().deriveFont(20f));
panel.add(l);
}//end of for loop
panel.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e)
{
sizes = new JFrame("Shopping");
sizes.setVisible(true);
sizes.setSize(500, 500);
sizes.setLocation(100,200);
shirts.dispose();
if(e.getSource()==l){//FIX
sizes.add(l);
}//end of if
}
});
shirts.setContentPane(panel);
shirts.setSize(1000, 1000);
shirts.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
shirts.setVisible(true);
If you add your MouseListener directly to your JLabels, then you can display the pressed label's icon easily in a JOptionPane:
#Override
public void mousePressed(MouseEvent mEvt) {
JLabel label = (JLabel) mEvt.getSource();
Icon icon = label.getIcon();
JOptionPane.showMessageDialog(label, icon);
}
For example:
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
public class FooMouseListener extends JPanel {
private GetImages getImages;
public FooMouseListener() throws IOException {
getImages = new GetImages();
setLayout(new GridLayout(GetImages.SPRITE_ROWS, GetImages.SPRITE_COLS));
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
for (int i = 0; i < GetImages.SPRITE_CELLS; i++) {
JLabel label = new JLabel(getImages.getIcon(i));
add(label);
label.addMouseListener(myMouseAdapter);
}
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
Icon icon = label.getIcon();
JOptionPane.showMessageDialog(label, icon, "Selected Icon", JOptionPane.PLAIN_MESSAGE);
}
}
private static void createAndShowGui() {
FooMouseListener mainPanel = null;
try {
mainPanel = new FooMouseListener();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("FooMouseListener");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class GetImages {
private static final String SPRITE_PATH = "http://th02.deviantart.net/"
+ "fs70/PRE/i/2011/169/0/8/blue_player_sprite_sheet_by_resetado-d3j7zba.png";
public static final int SPRITE_ROWS = 6;
public static final int SPRITE_COLS = 6;
public static final int SPRITE_CELLS = SPRITE_COLS * SPRITE_ROWS;
private List<Icon> iconList = new ArrayList<>();
public GetImages() throws IOException {
URL imgUrl = new URL(SPRITE_PATH);
BufferedImage mainImage = ImageIO.read(imgUrl);
for (int i = 0; i < SPRITE_CELLS; i++) {
int row = i / SPRITE_COLS;
int col = i % SPRITE_COLS;
int x = (int) (((double) mainImage.getWidth() * col) / SPRITE_COLS);
int y = (int) ((double) (mainImage.getHeight() * row) / SPRITE_ROWS);
int w = (int) ((double) mainImage.getWidth() / SPRITE_COLS);
int h = (int) ((double) mainImage.getHeight() / SPRITE_ROWS);
BufferedImage img = mainImage.getSubimage(x, y, w, h);
ImageIcon icon = new ImageIcon(img);
iconList.add(icon);
}
}
// get the Icon from the List at index position
public Icon getIcon(int index) {
if (index < 0 || index >= iconList.size()) {
throw new ArrayIndexOutOfBoundsException(index);
}
return iconList.get(index);
}
public int getIconListSize() {
return iconList.size();
}
}
Have you tried this?
public void mouseClicked(MouseEvent e)
{
sizes = new JFrame("Shopping");
sizes.add(l);
sizes.setVisible(true);
sizes.setSize(500, 500);
sizes.setLocation(100,200);
shirts.dispose();
//Remove the "e.getSource()" part.
}
It will automatically display the image, because you are assigning the Image Name to it, in the same segment as the Addition to the new JFrame.
Let me know of the outcome
This project requires that a user inputs data into text fields on a dialog box accessed from a menu bar and places the data from the text fields into a JTable. The problem is that once the user clicks okay on the dialog box after putting the information into the text field, the dialog box is no longer visible, but nothing appears in the JTable. The JTable headers are there, but the info just submitted is not.
It is a camping registration program, and all of the classes compile okay. I am only working on taking information from an RV reservation first, but will eventually do the same for a tent reservation. Here are the classes that correspond to an RV check in. There is an RV constructor that has parameters (String (name), String (check in day), int (days staying), String (leave day), int (site number), int (power needed)).
First the dialog box class:
package campingPrj;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogCheckInRv extends javax.swing.JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
private javax.swing.JTextField nameTxt;
private javax.swing.JTextField dateIn;
private javax.swing.JTextField stayingTxt;
private javax.swing.JTextField siteNumberTxt;
private javax.swing.JTextField checkOutDate;
private javax.swing.JTextField powerTxt;
private javax.swing.JButton okButton;
private javax.swing.JButton cancelButton;
private boolean cancel;
private boolean okay;
public DialogCheckInRv(java.awt.Frame parent) {
super(parent, true);
setupDialog();
setTitle("RV Check In");
}
private void setupDialog() {
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
nameTxt = new javax.swing.JTextField(27);
dateIn = new javax.swing.JTextField(25);
stayingTxt = new javax.swing.JTextField(25);
siteNumberTxt = new javax.swing.JTextField(27);
powerTxt = new javax.swing.JTextField(27);
okButton = new javax.swing.JButton("Ok");
okButton.addActionListener(this);
cancelButton = new javax.swing.JButton("Cancel");
cancelButton.addActionListener(this);
setLayout(new GridLayout(6, 1));
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Name Reserving:"));
panel.add(nameTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Start Date (mm/dd/yy) :"));
panel.add(dateIn);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Days Planning on Staying:"));
panel.add(stayingTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Requested Site Number:"));
panel.add(siteNumberTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Power Needed (in AMPs):"));
panel.add(powerTxt);
add(panel);
panel = new JPanel();
panel.add(okButton);
panel.add(cancelButton);
add(panel);
pack();
setLocationRelativeTo(null);
}
public void actionPerformed(java.awt.event.ActionEvent event) {
if (event.getSource() == okButton) {
okay = true;
cancel = false;
setVisible(false);
}
if (event.getSource() == cancelButton) {
okay = false;
cancel = true;
setVisible(false);
}
}
public boolean isOk() {
return okay;
}
public boolean isCancel() {
return cancel;
}
public String getName() {
return nameTxt.getText();
}
public String getDateIn() {
return dateIn.getText();
}
public String getDaysStaying() {
return stayingTxt.getText();
}
public String getCheckOutDate() {
return checkOutDate.getText();
}
public String getPower() {
return powerTxt.getText();
}
public String getSiteNumber() {
return siteNumberTxt.getText();
}
public void clear() {
nameTxt.setText(null);
dateIn.setText(null);
stayingTxt.setText(null);
dateIn.setText(null);
powerTxt.setText(null);
siteNumberTxt.setText(null);
}
}
The GUI with the table (where I'm guessing the problem is in the actionPerformed method):
package campingPrj;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUICampingReg extends javax.swing.JFrame implements ActionListener {
private JMenuItem openSerialFileItem = new JMenuItem("Open Serialized File");
private JMenuItem openTextFileItem = new JMenuItem("Open Text File");
private JMenuItem saveSerialFileItem = new JMenuItem("Save Serialized File");
private JMenuItem saveTextFileItem = new JMenuItem("Save Text File");
private JMenuItem exitItem = new JMenuItem("Exit");
private JMenuItem checkInTentItem = new JMenuItem("Check in tent");
private JMenuItem checkInRVItem = new JMenuItem("Check in RV");
private JMenuItem checkOutItem = new JMenuItem("Date Leaving");
private JTextField nameReservingTxt;
private JTextField dateInTxt;
private JTextField daysStayingTxt;
private JTextField checkOutOnTxt;
private JTextField siteNumberTxt;
private JTextField powerTxt;
private JFrame frame;
private JTable table;
private SiteModel model;
private JScrollPane scrollPane;
private DialogCheckInRv newRv;
public GUICampingReg() {
setupFrame();
newRv = new DialogCheckInRv(this);
model = new SiteModel();
table.setModel(model);
}
private void setupFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Camping Registration Program");
scrollPane = new JScrollPane();
table = new JTable();
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.add(openSerialFileItem);
fileMenu.add(openTextFileItem);
fileMenu.add(saveSerialFileItem);
fileMenu.add(saveTextFileItem);
fileMenu.add(exitItem);
JMenu checkInMenu = new JMenu("Check In");
checkInMenu.add(checkInRVItem);
checkInMenu.add(checkInTentItem);
JMenu checkOutMenu = new JMenu("Check Out");
checkOutMenu.add(checkOutItem);
menubar.add(fileMenu);
menubar.add(checkInMenu);
menubar.add(checkOutMenu);
openSerialFileItem.addActionListener(this);
openTextFileItem.addActionListener(this);
saveSerialFileItem.addActionListener(this);
saveTextFileItem.addActionListener(this);
exitItem.addActionListener(this);
checkInTentItem.addActionListener(this);
checkInRVItem.addActionListener(this);
checkOutItem.addActionListener(this);
frame.setJMenuBar(menubar);
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
table.setToolTipText("");
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table.getTableHeader().setReorderingAllowed(false);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked();
}
});
scrollPane.setViewportView(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void tableMouseClicked() {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent evt) {
Object pressed = evt.getSource();
if (pressed == exitItem) {
System.exit(0);
}
if (pressed == openSerialFileItem) {
}
if (pressed == openTextFileItem) {
}
if (pressed == saveSerialFileItem) {
}
if (pressed == saveTextFileItem) {
}
if (pressed == checkInTentItem) {
}
if (pressed == checkInRVItem) {
newRv.clear();
newRv.setVisible(true);
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
}
if (pressed == checkOutItem) {
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUICampingReg();
}
});
}
}
The site model class:
package campingPrj;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class SiteModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private ArrayList<Site> listSites;
private String[] columnNames = { "Name Reserving", "Checked in Date",
"Days Staying", "Site #", "Tenters/RV Power Needed" };
public SiteModel() {
listSites = new ArrayList<Site>();
}
public String getColumnName(int col) {
return columnNames[col];
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return listSites.size();
}
public Object getValueAt(int row, int col) {
Object val = null;
switch (col) {
case 0:
val = listSites.get(row).getNameReserving();
break;
case 1:
val = listSites.get(row).getCheckIn();
break;
case 2:
val = listSites.get(row).getDaysStaying();
break;
case 3:
val = listSites.get(row).getSiteNumber();
break;
case 4:
val = listSites.get(row).getCheckOutOn();
break;
}
return val;
}
public Site get(int index) {
return listSites.get(index);
}
public int indexOf(Site s) {
return listSites.indexOf(s);
}
public void add(Site s) {
if (s != null) {
listSites.add(s);
fireTableRowsInserted(listSites.size() - 1, listSites.size() - 1);
}
}
public void add(int index, Site s) {
if (s != null) {
listSites.add(index, s);
fireTableRowsInserted(index, index);
}
}
public void remove(int index) {
listSites.remove(index);
fireTableRowsDeleted(index, index);
return;
}
public void remove(Site s) {
remove(indexOf(s));
}
public void saveAsSerialized(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(listSites);
os.close();
}
#SuppressWarnings("unchecked")
public void loadFromSerialized(String filename) throws IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream is = new ObjectInputStream(fis);
listSites = (ArrayList<Site>) is.readObject();
is.close();
}
}
So, how do I get the information to show up in JTable?
Maybe I'm misinterpreting your code, but I don't see where you areextracting the information that the user enters into the dialog. For example here:
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
You appear to be extracting information from the fields held by the GUICampingReg, not by the newRv object. Shouldn't you be calling methods of newRv to extract the data needed to create your RV object?
for example,
if (newRv.isOk()) {
String nameReserving = newRv.getName();
String checkIn = newRv.getDateIn();
// .... etc
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
Another problem, same program:
The following is MainGUI.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class MainGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 4149825008429377286L;
private final double version = 8;
public static int rows;
public static int columns;
private int totalCells;
private MainCell[] cell;
public static Color userColor;
JTextField speed = new JTextField("250");
Timer timer = new Timer(250,this);
String generationText = "Generation: 0";
JLabel generationLabel = new JLabel(generationText);
int generation = 0;
public MainGUI(String title, int r, int c)
{
rows = r;
columns = c;
totalCells = r*c;
System.out.println(totalCells);
cell = new MainCell[totalCells];
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Timer set up
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.setActionCommand("timer");
//set up menu bar
JMenuBar menuBar = new JMenuBar();
JMenu optionsMenu = new JMenu("Options");
JMenu aboutMenu = new JMenu("About");
menuBar.add(optionsMenu);
menuBar.add(aboutMenu);
JMenuItem helpButton = new JMenuItem("Help!");
helpButton.addActionListener(this);
helpButton.setActionCommand("help");
aboutMenu.add(helpButton);
JMenuItem aboutButton = new JMenuItem("About");
aboutButton.addActionListener(this);
aboutButton.setActionCommand("about");
aboutMenu.add(aboutButton);
JMenuItem colorSelect = new JMenuItem("Select a Custom Color");
colorSelect.addActionListener(this);
colorSelect.setActionCommand("colorSelect");
optionsMenu.add(colorSelect);
JMenuItem sizeChooser = new JMenuItem("Define a Custom Size");
sizeChooser.addActionListener(this);
sizeChooser.setActionCommand("sizeChooser");
optionsMenu.add(sizeChooser);
//Create text field to adjust speed and its label
JPanel speedContainer = new JPanel();
JLabel speedLabel = new JLabel("Enter the speed of a life cycle (in ms):");
speedContainer.add(speedLabel);
speedContainer.add(speed);
speedContainer.add(generationLabel);
Dimension speedDim = new Dimension(100,25);
speed.setPreferredSize(speedDim);
//Create various buttons
JPanel buttonContainer = new JPanel();
JButton randomizerButton = new JButton("Randomize");
randomizerButton.addActionListener(this);
randomizerButton.setActionCommand("randomize");
buttonContainer.add(randomizerButton);
JButton nextButton = new JButton("Next"); //forces a cycle to occur
nextButton.addActionListener(this);
nextButton.setActionCommand("check");
buttonContainer.add(nextButton);
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
startButton.setActionCommand("start");
buttonContainer.add(startButton);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(this);
stopButton.setActionCommand("stop");
buttonContainer.add(stopButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setActionCommand("clear");
buttonContainer.add(clearButton);
//holds the speed container and button container, keeps it neat
JPanel functionContainer = new JPanel();
BoxLayout functionLayout = new BoxLayout(functionContainer, BoxLayout.PAGE_AXIS);
functionContainer.setLayout(functionLayout);
functionContainer.add(speedContainer);
speedContainer.setAlignmentX(CENTER_ALIGNMENT);
functionContainer.add(buttonContainer);
buttonContainer.setAlignmentX(CENTER_ALIGNMENT);
//finish up with the cell container
GridLayout cellLayout = new GridLayout(rows,columns);
JPanel cellContainer = new JPanel(cellLayout);
cellContainer.setBackground(Color.black);
int posX = 0;
int posY = 0;
for(int i=0;i<totalCells;i++)
{
MainCell childCell = new MainCell();
cell[i] = childCell;
childCell.setName(String.valueOf(i));
childCell.setPosX(posX);
posX++;
childCell.setPosY(posY);
if(posX==columns)
{
posX = 0;
posY++;
}
cellContainer.add(childCell);
childCell.deactivate();
Graphics g = childCell.getGraphics();
childCell.paint(g);
}
//make a default color
userColor = Color.yellow;
//change icon
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
//add it all up and pack
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
container.add(cellContainer);
container.add(functionContainer);
add(menuBar);
setJMenuBar(menuBar);
add(container);
pack();
}
private void checkCells()
{
//perform check for every cell
for(int i=0;i<totalCells;i++)
{
cell[i].setNeighbors(checkNeighbors(i));
}
//use value from check to determine life
for(int i=0;i<totalCells;i++)
{
int neighbors = cell[i].getNeighbors();
if(cell[i].isActivated())
{
System.out.println(cell[i].getName()+" "+neighbors);
if(neighbors==0||neighbors==1||neighbors>3)
{
cell[i].deactivate();
}
}
if(cell[i].isActivated()==false)
{
if(neighbors==3)
{
cell[i].activate();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
//help button, self-explanatory
if(e.getActionCommand().equals("help"))
{
JOptionPane.showMessageDialog(this, "The game is governed by four rules:\nFor a space that is 'populated':"
+ "\n Each cell with one or no neighbors dies, as if by loneliness."
+ "\n Each cell with four or more neighbors dies, as if by overpopulation."
+ "\n Each cell with two or three neighbors survives."
+ "\nFor a space that is 'empty' or 'unpopulated':"
+ "\n Each cell with three neighbors becomes populated."
+ "\nLeft click populates cells. Right click depopulates cells.","Rules:",JOptionPane.PLAIN_MESSAGE);
}
//shameless self promotion
if(e.getActionCommand().equals("about"))
{
JOptionPane.showMessageDialog(this, "Game made and owned by *****!"
+ "\nFree usage as see fit, but give credit where credit is due!\nVERSION: "+version,"About:",JOptionPane.PLAIN_MESSAGE);
}
//clears all the cells
if(e.getActionCommand().equals("clear"))
{
timer.stop();
generation = 0;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
}
}
//starts timer
if(e.getActionCommand().equals("start"))
{
if(Integer.parseInt(speed.getText())>0)
{
timer.setDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
else
{
JOptionPane.showMessageDialog(this, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
}
//stops timer
if(e.getActionCommand().equals("stop"))
{
timer.stop();
}
//run when timer
if(e.getActionCommand().equals("timer"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
timer.stop();
checkCells();
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
//see checkCells()
if(e.getActionCommand().equals("check"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
checkCells();
}
//color select gui
if(e.getActionCommand().equals("colorSelect"))
{
userColor = JColorChooser.showDialog(this, "Choose a color:", userColor);
if(userColor==null)
{
userColor = Color.yellow;
}
}
//size chooser!
if(e.getActionCommand().equals("sizeChooser"))
{
SizeChooser size = new SizeChooser();
size.setLocationRelativeTo(null);
size.setVisible(true);
}
}
private int checkNeighbors(int c)
{
//if a LIVE neighbor is found, add one
int neighbors = 0;
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=0)
{
if(c-columns-1>=0)
{
if(cell[c-columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=0)
{
if(c-columns>=0)
{
if(cell[c-columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=0)
{
if(c-columns+1>=0)
{
if(cell[c-columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0)
{
if(c-1>=0)
{
if(cell[c-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1)
{
if(c+1<totalCells)
{
if(cell[c+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=rows-1)
{
if(c+columns-1<totalCells)
{
if(cell[c+columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=rows-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns<totalCells)
{
if(cell[c+columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns+1<totalCells)
{
if(cell[c+columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns+1].getName());
neighbors++;
}
}
}
return neighbors;
}
}
The following is MainCell.java:
public class MainCell extends JPanel implements MouseListener
{
//everything here should be self-explanatory
private static final long serialVersionUID = 1761933778208900172L;
private boolean activated = false;
public static boolean leftMousePressed;
public static boolean rightMousePressed;
private int posX = 0;
private int posY = 0;
private int neighbors = 0;
private URL cellImgURL_1 = getClass().getResource("images/cellImage_1.gif");
private ImageIcon cellImageIcon_1 = new ImageIcon(cellImgURL_1);
private Image cellImage_1 = cellImageIcon_1.getImage();
private URL cellImgURL_2 = getClass().getResource("images/cellImage_2.gif");
private ImageIcon cellImageIcon_2 = new ImageIcon(cellImgURL_2);
private Image cellImage_2 = cellImageIcon_2.getImage();
private URL cellImgURL_3 = getClass().getResource("images/cellImage_3.gif");
private ImageIcon cellImageIcon_3 = new ImageIcon(cellImgURL_3);
private Image cellImage_3 = cellImageIcon_3.getImage();
public MainCell()
{
Dimension dim = new Dimension(17, 17);
setPreferredSize(dim);
addMouseListener(this);
}
public void activate()
{
setBackground(MainGUI.userColor);
System.out.println(getName()+" "+posX+","+posY+" activated");
setActivated(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
else if(getPosY()!=0&&getPosX()!=MainGUI.columns-1)
{
g.drawImage(cellImage_1,0,0,null);
}
else if(getPosY()==0)
{
g.drawImage(cellImage_2,0,0,null);
}
else if(getPosX()==MainGUI.columns-1)
{
g.drawImage(cellImage_3,0,0,null);
}
}
public void setActivated(boolean b)
{
activated = b;
}
public void deactivate()
{
setBackground(Color.gray);
System.out.println(getName()+" "+posX+","+posY+" deactivated");
setActivated(false);
}
public boolean isActivated()
{
return activated;
}
public void setNeighbors(int i)
{
neighbors = i;
}
public int getNeighbors()
{
return neighbors;
}
public int getPosX()
{
return posX;
}
public void setPosX(int x)
{
posX = x;
}
public int getPosY()
{
return posY;
}
public void setPosY(int y)
{
posY = y;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
if(leftMousePressed&&SwingUtilities.isLeftMouseButton(e))
{
activate();
}
if(rightMousePressed&&SwingUtilities.isRightMouseButton(e))
{
deactivate();
}
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e)&&!leftMousePressed)
{
deactivate();
rightMousePressed = true;
}
if(SwingUtilities.isLeftMouseButton(e)&&!rightMousePressed)
{
activate();
leftMousePressed = true;
}
}
public void mouseReleased(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e))
{
rightMousePressed = false;
}
if(SwingUtilities.isLeftMouseButton(e))
{
leftMousePressed = false;
}
}
}
The following is SizeChooser.java:
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class SizeChooser extends JFrame
{
private static final long serialVersionUID = -6431709376438241788L;
public static MainGUI GUI;
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JTextField rowsTextField = new JTextField(String.valueOf((screenSize.height/17)-15));
JTextField columnsTextField = new JTextField(String.valueOf((screenSize.width/17)-10));
private static int rows = screenSize.height/17-15;
private static int columns = screenSize.width/17-10;
public SizeChooser()
{
setResizable(false);
setTitle("Select a size!");
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
add(container);
JLabel rowsLabel = new JLabel("Rows:");
container.add(rowsLabel);
container.add(rowsTextField);
JLabel columnsLabel = new JLabel("Columns:");
container.add(columnsLabel);
container.add(columnsTextField);
JButton confirmSize = new JButton("Confirm");
confirmSize.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GUI.setVisible(false);
GUI = null;
if(Integer.parseInt(rowsTextField.getText())>0)
{
rows = Integer.parseInt(rowsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
if(Integer.parseInt(columnsTextField.getText())>0)
{
columns = Integer.parseInt(columnsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
setVisible(false);
}
});
container.add(confirmSize);
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
pack();
}
public static void main(String[]args)
{
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
}
}
So the problem now is, when the randomize button is pressed, or a large number of cells exist and then the timer is started, the cells aren't as snappy as they would be with less active cells. For example, with 100 columns and 50 rows, when the randomize button is pressed, one cell activates, then the next, then another, and so forth. Can I have them all activate at exactly the same time? Is this just a problem with too many things calculated at once? Would concurrency help?
QUICK EDIT: Is the swing timer the best idea for this project?
I havent read through your code completely but I am guessing that your listener methods are fairly computationally intensive and hence the lag in updating the display.
This simple test reveals that your randomize operation should be fairly quick:
public static void main(String args[]) {
Random rn = new Random();
boolean b[] = new boolean[1000000];
long timer = System.nanoTime();
for (int i = 0; i < b.length; i++) {
b[i] = rn.nextInt(6) == 0;
}
timer = System.nanoTime() - timer;
System.out.println(timer + "ns / " + (timer / 1000000) + "ms");
}
The output for me is:
17580267ns / 17ms
So this leads me into thinking activate() or deactivate() is causing your UI to be redrawn.
I am unable to run this because I don't have your graphical assets, but I would try those changes to see if it works:
In MainGUI#actionPerformed, change:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
to:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
// This will not cause the object to be redrawn and should
// be a fairly cheap operation
cell[i].setActivated(rn.nextInt(6)==0);
}
// Cause the UI to repaint
repaint();
}
Add this to MainCell
// You can specify those colors however you like
public static final Color COLOR_ACTIVATED = Color.RED;
public static final Color COLOR_DEACTIVATED = Color.GRAY;
And change:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
to:
protected void paintComponent(Graphics g)
{
// We now make UI changes only when the component is painted
setBackground(activated ? COLOR_ACTIVATED : COLOR_DEACTIVATED);
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}