java swing not printing complete page - java

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

Change your buttons x and y to make them appear on form
button1.setBounds(100, 650, 100, 30);
button.setBounds(200, 650, 100, 30);
button2.setBounds(300, 650, 100, 30);

I assume you want to print all the contents of the user interface. You have to make a call to the frame.print() method; NOT table.print() method.
thanks.

Related

Java Swing GridLayout Change Grid Sizes

I'm trying to create a program that lists movies in a Netflix style to learn Front-End coding.
How I want it to look in the end:
My guess is that every movie is a button component with an image a name label and a release year label.
I'm struggling to recreate this look. This is how it looks when I try it:
The navigationbar in my image is at the page start of a border layout. Below the navigationbar the movie container is in the center of the border layout.
My idea was creating a GridLayout and then create a button for each movie and adding it to the GridLayout.
You can recreate this with this code:
public class Main {
private static JFrame frame;
public static void main(String[] args) throws HeadlessException {
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setBackground(new Color(32, 32, 32));
JPanel navigationPanel = createNavigationBar();
frame.add(navigationPanel, BorderLayout.PAGE_START);
JPanel moviePanel = createMoviePanel();
frame.add(moviePanel, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(1920, 1080));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Example App");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel moviePanel = new JPanel();
GridLayout layout = new GridLayout(0, 10);
layout.setHgap(3);
layout.setVgap(3);
moviePanel.setLayout(layout);
moviePanel.setBackground(new Color(32, 32, 32));
ArrayList<String> exampleList = new ArrayList<>();
// Add stuff to the example list
for(int i = 0; i < 120; i++) {
exampleList.add(Integer.toString(i));
}
final File root = new File("");
for(final String movie : exampleList) {
JLabel picLabel = new JLabel();
try {
File imageFile = new File(root.getAbsolutePath() + "\\src\\images\\" + "imageName.jpg"); // Try to find the cover image
if(imageFile.exists()) {
BufferedImage movieCover = ImageIO.read(imageFile);
picLabel = new JLabel(new ImageIcon(movieCover));
} else {
BufferedImage movieCover = ImageIO.read(new File(root.getAbsolutePath() + "\\src\\images\\temp.jpg")); // Get a temp image
picLabel = new JLabel(new ImageIcon(movieCover));
}
} catch (IOException e) {
e.printStackTrace();
}
JLabel movieName = new JLabel("New Movie");
movieName.setForeground(Color.WHITE);;
JButton movieButton = new JButton();
movieButton.setLayout(new GridLayout(0, 1));
//movieButton.setContentAreaFilled(false);
//movieButton.setBorderPainted(false);
//movieButton.setFocusPainted(false);
movieButton.add(picLabel);
movieButton.add(movieName);
moviePanel.add(movieButton);
}
return moviePanel;
}
public static JPanel createNavigationBar() {
JPanel navBar = new JPanel();
navBar.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20));
navBar.setBackground(new Color(25, 25, 25));
JButton homeButton = new JButton("Home");
homeButton.setContentAreaFilled(false);
homeButton.setBorderPainted(false);
homeButton.setFocusPainted(false);
JButton movieButton = new JButton("Movies");
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
// Add all the buttons to the navbar
navBar.add(homeButton);
navBar.add(movieButton);
return navBar;
}
}
I noticed that the GridLayout always tries to fit everything onto the window.
All that's needed is a properly configured JButton in a GridLayout.
E.G.
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 1; ii < 21; ii++) {
JButton picButton = new JButton("Mov " + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
Here is a complete source for the above with a tweak to put the year on a new line. It uses HTML in the JButton to break the button text into two lines.
The input focus is on the first button, whereas the mouse hovers over the '2009' movie:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
class MovieGrid {
MovieGrid() {
JFrame f = new JFrame("Movie Grid");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.add(createMoviePanel());
f.pack();
f.setVisible(true);
}
public static JPanel createMoviePanel() {
JPanel movieLibraryPanel = new JPanel(new GridLayout(0, 10, 3, 3));
movieLibraryPanel.setBackground(new Color(132, 132, 132));
int m = 5;
BufferedImage image = new BufferedImage(
9 * m, 16 * m, BufferedImage.TYPE_INT_RGB);
for (int ii = 2001; ii < 2021; ii++) {
JButton picButton = new JButton(
"<html>Movie<br>" + ii, new ImageIcon(image));
picButton.setMargin(new Insets(0,0,0,0));
picButton.setForeground(Color.WHITE);
picButton.setContentAreaFilled(false);
picButton.setHorizontalTextPosition(JButton.CENTER);
picButton.setVerticalTextPosition(JButton.BOTTOM);
movieLibraryPanel.add(picButton);
}
return movieLibraryPanel;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new MovieGrid();
}
};
SwingUtilities.invokeLater(r);
}
}
Same idea's from Andrew Thompson answer but with some minor text alignment changes and hover effect
final class Testing
{
public static void main(String[] args)
{
JFrame frame=new JFrame("NEFLIX");
frame.setContentPane(new GridDisplay());
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static final class GridDisplay extends JPanel implements ActionListener
{
private GridDisplay()
{
super(new GridLayout(0,5,20,20));
setBackground(new Color(0,0,0,255));
BufferedImage image=new BufferedImage(150,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d=(Graphics2D)image.getGraphics();
g2d.setColor(Color.BLUE);
g2d.fillRect(0,0,image.getWidth(),image.getHeight());
HoverPainter painter=new HoverPainter();
for(int i=0;i<10;i++)
{
TVShowCard card=new TVShowCard(image,"Show "+i,"199"+i);
card.addMouseListener(painter);
add(card);
}
}
//highlight only on hover
private final class HoverPainter extends MouseAdapter
{
#Override
public void mouseExited(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(false);
}
#Override
public void mouseEntered(MouseEvent e) {
((TVShowCard)e.getSource()).setBorderPainted(true);
}
}
private final class TVShowCard extends JButton
{
private TVShowCard(BufferedImage preview,String name,String year)
{
super();
setContentAreaFilled(false);
setBackground(new Color(0,0,0,0));
setFocusPainted(false);
setBorderPainted(false);
//I didn't use image icon & text horizontal alignment because the text always horizontally centered aligned but from the expected output it was left so created 2 labels for the job
setLayout(new GridBagLayout());
addIcon(preview);
addLabel(name,year);
addActionListener(GridDisplay.this);
}
private void addIcon(BufferedImage preview)
{
JLabel icon=new JLabel();
icon.setIcon(new ImageIcon(preview));
add(icon,new GridBagConstraints(0,0,1,1,1.0f,0.0f,GridBagConstraints.WEST,GridBagConstraints.NONE,new Insets(0,0,0,0),0,0));
}
private void addLabel(String name,String year)
{
JLabel label=new JLabel("<html><body>"+name+"<br>"+year+"</body></html>");
label.setForeground(Color.white);
label.setBackground(new Color(0,0,0,0));
add(label,new GridBagConstraints(0,1,1,1,1.0f,1.0f,GridBagConstraints.SOUTHWEST,GridBagConstraints.NONE,new Insets(5,0,0,0),0,0));
}
}
#Override
public void actionPerformed(ActionEvent e)
{
TVShowCard card=(TVShowCard)e.getSource();
//do stuff with it
}
}
}

when I make a popup menu with JPopupMenu it quits my file explorer page that I made and goes back to the main page(desktop)

I have tried telling it to dispose the file explorer and recreate it works but I cannot seem to get my file image on it now any help in making it not quit in the first place?
here is the code(btw I am on IntelliJ IDEA CE):
package os_pack;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OS extends JFrame implements ActionListener {
String title = "waliOS";
String message = "please login";
int width = 600;
int height = 400;
JButton b;
JLabel label;
JTextField text;
JLabel c;
JPasswordField pass;
JFrame f;
JFrame f2;
JLabel username;
JLabel password;
JLabel welcomeMain;
JFrame folderFrame;
JFrame textFrame;
JLabel folderLabel;
OS() {
f = new JFrame(title);
f.setSize(width, height);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel(message);
label.setBounds(200, 100, 200, 50);
label.setForeground(Color.WHITE);
text = new JTextField();
text.setBounds(200, 150, 200, 30);
b = new JButton("login");
b.setBounds(200, 250, 200, 50);
b.addActionListener(this);
pass = new JPasswordField();
pass.setBounds(200, 200, 200, 30);
c = new JLabel();
c.setBounds(200, 300, 200, 50);
c.setForeground(Color.WHITE);
username = new JLabel("username");
username.setBounds(130, 140, 200, 50);
username.setForeground(Color.WHITE);
password = new JLabel("password");
password.setBounds(130, 190, 200, 50);
password.setForeground(Color.WHITE);
f.add(password);
f.add(username);
f.add(c);
f.add(pass);
f.add(b);
f.add(label);
f.add(text);
f.setLayout(null);
f.setVisible(true);
f.setResizable(false);
f.getContentPane().setBackground(Color.BLACK);
}
public void mainPage(){
f.dispose();
f2 = new JFrame();
f2.setTitle(title);
f2.setSize(width, height);
f2.setLocationRelativeTo(null);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setResizable(false);
f2.setLayout(null);
f2.setVisible(true);
f2.setResizable(false);
f2.getContentPane().setBackground(Color.BLACK);
welcomeMain = new JLabel("this is the home page");
welcomeMain.setForeground(Color.WHITE);
welcomeMain.setBounds(200, 100, 200, 50);
f2.add(welcomeMain);
ImageIcon folder = new ImageIcon(getClass().getResource("OS_file.png"));
JLabel folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
folderPage();
}
});
ImageIcon textEdit = new ImageIcon(getClass().getResource("text_edit.png"));
JLabel textImage = new JLabel(textEdit);
textImage.setBounds(200, 200, 80, 80);
textImage.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent em){
textEditPage();
}
});
f2.add(folderLabel);
f2.add(textImage);
}
public void folderPage() {
f2.dispose();
folderFrame = new JFrame(title + " folder");
folderFrame.setSize(width, height);
folderFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
folderFrame.setLocationRelativeTo(null);
folderFrame.setResizable(false);
folderFrame.setLayout(null);
folderFrame.setVisible(true);
folderFrame.getContentPane().setBackground(Color.BLACK);
JLabel test = new JLabel("this is the folder page");
test.setForeground(Color.WHITE);
test.setBounds(300, 200, 200, 50);
JButton back = new JButton("back");
back.setBounds(10, 10, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
folderFrame.dispose();
}
});
JPopupMenu menu = new JPopupMenu();
JMenuItem newFolder = new JMenuItem("new Folder");
newFolder.addActionListener(this);
newFolder.setActionCommand("NF");
menu.add(newFolder);
folderFrame.addMouseListener((new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)){
menu.show(folderFrame, e.getX(), e.getY());
}
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}));
ImageIcon folder = new ImageIcon("folder.png");
folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderFrame.add(test);
folderFrame.add(back);
}
public void textEditPage() {
f2.dispose();
textFrame = new JFrame(title + " text editor");
textFrame.setResizable(false);
textFrame.setLayout(null);
textFrame.setSize(width, height);
textFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textFrame.setVisible(true);
textFrame.setLocationRelativeTo(null);
textFrame.getContentPane().setBackground(Color.BLACK);
JTextArea textArea = new JTextArea();
Font font = new Font(
Font.MONOSPACED,
Font.PLAIN,
textArea.getFont().getSize());
textArea.setFont(font);
textArea.setBounds(1, 30, 599, 399);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JLabel title = new JLabel("Text Editor");
title.setBounds(250, 2, 100, 30);
title.setForeground(Color.WHITE);
JButton back = new JButton("back");
back.setBounds(10, 4, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
textFrame.dispose();
}
});
textFrame.add(back);
textFrame.add(title);
textFrame.add(textArea);
}
public static void main(String[] args){
new OS();
}
#Override
public void actionPerformed(ActionEvent e) {
String user = text.getText();
String pass1 = pass.getText();
if (user.trim().equals("wali") && pass1.trim().equals("haider")) {
c.setText("welcome wali");
mainPage();
} else if(user.trim().equals("admin") && pass1.trim().equals("admin")) {
c.setText("welcome admin");
mainPage();
} else {
c.setText("wrong user");
}
String command = e.getActionCommand();
switch (command) {
case "NF":
System.out.println("done");
folderPage();
folderFrame.dispose();
System.out.print("hello");
folderFrame.add(folderLabel);
}
}
}
can I please get some help on this because I am really stuck if you have questions tell me in the comments that will be very helpful

JTable column labels not printing

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

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

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

How to invoke a progress bar by clicking a button in another frame?

I have two frames in my java program. One is for the credential window and another for the progress bar. When I click the login button the progress bar should also start working. This is my code
package Javapkg;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
public class ProgressBarDemo extends JPanel implements ActionListener,
PropertyChangeListener {
private static final long serialVersionUID = 1L;
JFrame frame;
JPanel panel;
JTextField userText;
JPasswordField passwordText;
JButton loginButton;
JLabel userLabel;
JLabel passwordLabel;
JButton cancelButton;
JButton startButton;
private JProgressBar progressBar;
// private JButton startButton;
private JTextArea taskOutput;
private Task task;
class Task extends SwingWorker<Void, Void> {
/*
* Main task. Executed in background thread.
*/
public void Credential() {
JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setSize(new Dimension(400, 300));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (g instanceof Graphics2D) {
final int R = 220;
final int G = 220;
final int B = 250;
Paint p = new GradientPaint(0.0f, 0.0f, new Color(R, G,
B, 0), 0.0f, getHeight(), new Color(R, G, B,
255), true);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(p);
g2d.fillRect(0, 0, getWidth(), getHeight());
Font font = new Font("Serif", Font.PLAIN, 45);
g2d.setFont(font);
g2d.setColor(Color.lightGray);
g2d.drawString("Get Credential", 60, 80);
}
}
};
frame.setContentPane(panel);
frame.setLayout(new FlowLayout());
frame.placeComponents(panel);
}
public void placeComponents(JPanel panel) {
panel.setLayout(null);
userLabel = new JLabel("User");
userLabel.setBounds(40, 100, 80, 25);
panel.add(userLabel);
userText = new JTextField(20);
userText.setBounds(130, 100, 160, 25);
userText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel.add(userText);
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(40, 140, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField(20);
passwordText.setBounds(130, 140, 160, 25);
panel.add(passwordText);
loginButton = new JButton("login");
loginButton.setBounds(100, 180, 80, 25);
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProcessBuilder pb = new ProcessBuilder("powershell.exe",
"-File", "D:\\MyPowershell\\stage1.ps1");
Map<String, String> env = pb.environment();
env.put("USER", userText.getText());
env.put("PASS", passwordText.getText());
System.out.println(userText.getText());
System.out.println(passwordText.getText());
try {
Process process = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
panel.add(loginButton);
cancelButton = new JButton("cancel");
cancelButton.setBounds(220, 180, 80, 25);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
panel.add(cancelButton);
}
}
public Void doInBackground() {
Random random = new Random();
int progress = 0;
// Initialize progress property.
setProgress(0);
while (progress < 100) {
// Sleep for up to one second.
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException ignore) {
}
// Make random progress.
progress += random.nextInt(10);
setProgress(Math.min(progress, 100));
}
return null;
}
private void setProgress(int min) {
// TODO Auto-generated method stub
}
/*
* Executed in event dispatching thread
*/
public void done() {
Toolkit.getDefaultToolkit().beep();
startButton.setEnabled(true);
// turn off the wait cursor
taskOutput.append("Done!\n");
}
public ProgressBarDemo() {
super(new BorderLayout());
// Create the demo's UI.
//startButton = new JButton("Start");
//startButton.setActionCommand("start");
//startButton.addActionListener(this);
progressBar = new JProgressBar(0, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);
taskOutput = new JTextArea(5, 20);
taskOutput.setMargin(new Insets(5, 5, 5, 5));
taskOutput.setEditable(false);
JPanel panel = new JPanel();
//panel.add(startButton);
panel.add(progressBar);
add(panel, BorderLayout.PAGE_START);
add(new JScrollPane(taskOutput), BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
/**
* Invoked when the user presses the start button.
*/
public void actionPerformed(ActionEvent evt) {
// startButton.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// Instances of javax.swing.SwingWorker are not reusuable, so
// we create new instances as needed.
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
}
/**
* Invoked when task's progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if ("progress" == evt.getPropertyName()) {
int progress = (Integer) evt.getNewValue();
progressBar.setValue(progress);
taskOutput.append(String.format("Completed %d%% of task.\n",
task.getProgress()));
}
}
/**
* Create the GUI and show it. As with all GUI code, this must run on the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("ProgressBarDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new ProgressBarDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
Credential gtw = new Credential();
gtw.setVisible(true);
}
});
}
}
I am getting both frames being displayed. But I am not getting the progressbar running when I press the login button.. Also I am not able to get the values of username and password fields into the powershell script.. My powershell code is given below stage1.ps1:
$username = $env:USER
$password = $env:PASS
$url = "https://www.jabong.com/customer/account/login/"
$ie = New-Object -com internetexplorer.application;
$ie.visible = $true;
$ie.navigate($url);
while ($ie.Busy -eq $true)
{
Start-Sleep 1;
}
$ie.Document.getElementById("LoginForm_email").value = $username
$ie.Document.getElementByID("LoginForm_password").value=$password
$ie.Document.getElementByID("qa-login-button").Click();
The web page is invoked when I click the login button.But I am not getting the values of credentials being passed in the swing window into it

Categories