How to refresh a progress bar in java? - java

I have tried to create this progress bar:
public class ProgressBar extends JFrame{
private JButton fine = new JButton("Chiudi");
final JProgressBar jp;
JPanel body;
JLabel banner1;
JLabel banner2;
JPanel testo;
JTextArea areatesto;
JPanel provapannello;
JTextArea provatesto;
JPanel pannellofine;
public ProgressBar() {
super("loading");
setSize(440, 400);
setResizable(true);
Container content = getContentPane();
content.setBackground(Color.YELLOW);
body = new JPanel();
body.setLayout(new FlowLayout());
ImageIcon image1 = new ImageIcon("prova1.png");
banner1 = new JLabel();
banner2 = new JLabel();
banner1.setIcon(image1);
JTextArea prova = new JTextArea("bar", 2, 40);
prova.setBackground(Color.LIGHT_GRAY);
prova.setLineWrap(true);
body.add(banner1);
body.add(prova);
body.add(banner2);
banner.setBounds(30, 80, 120, 120);
testo = new JPanel();
areatesto = new JTextArea("Attendi Per Favore, Sto Preparando Il Tuo PDF", 2, 33);
areatesto.setLineWrap(true);
testo.add(areatesto);
ImagePanel progress_background = new ImagePanel("p.jpg");
UIManager.put("ProgressBar.background", new Color(29, 29, 29));
UIManager.put("ProgressBar.foreground", new Color(16, 95, 173));
UIManager.put("ProgressBar.selectionBackground", new Color(214, 214, 214));
UIManager.put("ProgressBar.selectionForeground", new Color(29, 29, 29));
jp = new JProgressBar();
jp.setUI(new BasicProgressBarUI());
jp.setBounds(0, 205, 434, 25);
jp.setMinimum(0);
jp.setMaximum(100);
jp.setStringPainted(true);
jp.setBorder(null);
progress_background.add(jp);
provapannello = new JPanel();
provatesto = new JTextArea("prova", 2, 70);
provatesto.setBackground(Color.LIGHT_GRAY);
provapannello.setBounds(0, 226, 500, 100);
provapannello.add(provatesto);
content.add(provapannello);
content.add(progress_background);
pannellofine = new JPanel();
pannellofine.add(fine);
pannellofine.setBounds(340, 330, 100, 100);
pannellofine.setVisible(false);
content.add(pannellofine);
content.add(testo);
content.add(body);
Thread runner;
jp.setValue(0);
setVisible(true);
public void setValue(final int j) {
Runnable target = new Runnable() {
#Override
public void run() {
jp.setValue(j);
}
};
SwingUtilities.invokeLater(target);
}
public static void main(String Args[]) {
ProgressBar p = new ProgressBar();
int i = 0;
while(true){
System.out.println("work");
try {
Thread.sleep(500);
} catch (InterruptedException ex) { }
p.setValue(i++);
}
}
I have tried to change the value of the ProgressBar with the method "setValue" but the bar does not increase, "while" cycles to infinity, but I see no change. what's wrong?

I've stripped out most of the unnecessary code (and fixed your compilation errors), and your example works (I've changed the delay and increment, because again, for reproduction purposes you shouldn't waste people's time)
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
public class ProgressBar extends JFrame {
private JProgressBar progressBar;
public ProgressBar() {
super("loading");
setSize(200, 100);
Container content = getContentPane();
content.setLayout(new BorderLayout());
progressBar = new JProgressBar();
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setStringPainted(true);
progressBar.setBorder(null);
content.add(progressBar, BorderLayout.SOUTH);
setVisible(true);
}
void updateProgress(final int newValue) {
progressBar.setValue(newValue);
}
public void setValue(final int j) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
updateProgress(j);
}
});
}
public static void main(final String Args[]) {
ProgressBar myProgressBar = new ProgressBar();
int i = 0;
while (i <= 100) {
System.out.println("" + i + "%");
myProgressBar.setValue(i);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
i = i + 5;
}
}
}
You should really have invested the time in creating an SSCCE
Also on a side note, you should follow this advice when handling InterruptedExcetions

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

Is it possible to split initialize section into different classes?

I have been working on some side project involving MySQL, with will use tree different screens: 'menu, ' add breed', 'browse breed'.
At this point section initialize is getting quite large and I would like to split it into 3 different classes.
Is it possible to initialize for example JPanel outside Window class?
public class Window {
public static void setBreed()
{
for(int i=0; i<16;i++) {
breedLabels[i].setText(breedInfo[i]);
breedLabels[i].setBounds(600,100+i*30,300, 100);
breedLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(breedLabels[i]);
}
}
public static void setText()
{
for(int i=0; i<16;i++) {
textLabels[i].setText(text[i]);
textLabels[i].setBounds(300,100+i*30,300, 100);
textLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(textLabels[i]);
}
}
public static String URL = "jdbc:mysql://localhost:3306/chooseyourpuppy";
public static String user = "root";
public static String password = "";
public static String query = "select * from breeds";
static String [] breedInfo = new String[16];
static String [] text = new String[16];
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
View.connect(URL, user, password, query);
}
public Window() {
initialize();
}
private JFrame frame;
public JPanel addBreed;
public static JPanel viewBreed;
public JPanel menu;
public static JLabel[] textLabels;
public static JLabel[] breedLabels;
private void initialize() {
final int WIDTH = 1280, HEIGHT = 720;
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("MyBREEDS Viewer");
frame.setResizable(false);
frame.setVisible(true);
//header
JPanel red = new JPanel();
red.setBounds(400, 0, 888, 80);
frame.getContentPane().add(red);
red.setBackground(new Color(204, 0, 0));
red.setLayout(null);
JPanel darkGrey = new JPanel();
darkGrey.setBounds(0, 0, 387, 80);
frame.getContentPane().add(darkGrey);
darkGrey.setBackground(new Color(51, 51, 51));
darkGrey.setLayout(null);
JLabel txtpnChoose = new JLabel();
txtpnChoose.setForeground(new Color(240, 240, 240));
txtpnChoose.setBounds(56, 11, 367, 63);
txtpnChoose.setFont(new Font("Verdana", Font.BOLD, 46));
txtpnChoose.setText("Choose your");
txtpnChoose.setBackground(null);
darkGrey.add(txtpnChoose);
JLabel txtpnPuppy = new JLabel();
txtpnPuppy.setBounds(5, 11, 166, 63);
txtpnPuppy.setForeground(new Color(240, 240, 240));
txtpnPuppy.setFont(new Font("Nunito-Bold", Font.BOLD, 46));
txtpnPuppy.setText("puppy");
txtpnPuppy.setBackground(null);
red.add(txtpnPuppy);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, WIDTH, HEIGHT);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
JButton btnMenu = new JButton("Back to menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(menu);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnMenu.setForeground(Color.WHITE);
btnMenu.setBackground(new Color(51, 51, 51));
btnMenu.setFont(new Font("Verdana", Font.BOLD, 18));
btnMenu.setBounds(660, 20, 180, 40);
btnMenu.setBorderPainted(false);
btnMenu.setFocusPainted(false);
red.add(btnMenu);
//menu
menu = new JPanel();
menu.setBackground(Color.WHITE);
layeredPane.add(menu, "name_410359960271086");
menu.setLayout(null);
JButton btnBrowse = new JButton("Browse breeds");
btnBrowse.setBounds(100, 300, 400, 200);
btnBrowse.setFont(new Font("Verdana", Font.PLAIN, 40));
btnBrowse.setBorder(new LineBorder(Color.DARK_GRAY));
btnBrowse.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnBrowse.setBackground(Color.WHITE);
btnBrowse.setRequestFocusEnabled(false);
btnBrowse.setVisible(true);
btnBrowse.setFocusPainted(false);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(viewBreed);
layeredPane.repaint();
layeredPane.revalidate();
setText();
setBreed();
}
});
btnBrowse.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnBrowse.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnBrowse.setBackground(Color.WHITE);
}
});
menu.add(btnBrowse);
addBreed = new JPanel();
layeredPane.add(addBreed, "name_410359942089403");
addBreed.setVisible(false);
addBreed.setBackground(Color.WHITE);
addBreed.setLayout(null);
//view breed window
viewBreed = new JPanel();
layeredPane.add(viewBreed, "name_410359924014670");
viewBreed.setLayout(null);
viewBreed.setVisible(false);
viewBreed.setBackground(Color.WHITE);
ImageIcon previous = new ImageIcon("src/images/previous.png");
ImageIcon previousHover = new ImageIcon("src/images/previousHover.png");
JButton prevBreed = new JButton(previous);
prevBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
prevBreed.setIcon(previousHover);
}
#Override
public void mouseExited(MouseEvent e) {
prevBreed.setIcon(previous);
}
});
prevBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(false);
}
});
prevBreed.setBounds(30, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(prevBreed);
prevBreed.setRequestFocusEnabled(false);
prevBreed.setOpaque(false);
prevBreed.setContentAreaFilled(false);
prevBreed.setBorderPainted(false);
prevBreed.setFocusPainted(false);
ImageIcon next = new ImageIcon("src/images/next.png");
ImageIcon nextHover = new ImageIcon("src/images/nextHover.png");
JButton nextBreed = new JButton(next);
nextBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
nextBreed.setIcon(nextHover);
}
#Override
public void mouseExited(MouseEvent e) {
nextBreed.setIcon(next);
}
});
nextBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(true);
}
});
nextBreed.setBounds(1140, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(nextBreed);
nextBreed.setRequestFocusEnabled(false);
nextBreed.setVisible(true);
nextBreed.setOpaque(false);
nextBreed.setContentAreaFilled(false);
nextBreed.setBorderPainted(false);
nextBreed.setFocusPainted(false);
//add breed window
JButton btnAdd = new JButton("Add new breed");
btnAdd.setBounds(780, 300, 400, 200);
btnAdd.setFont(new Font("Verdana", Font.PLAIN, 40));
btnAdd.setBorder(new LineBorder(Color.DARK_GRAY));
btnAdd.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnAdd.setBackground(Color.WHITE);
btnAdd.setRequestFocusEnabled(false);
btnAdd.setFocusPainted(false);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(addBreed);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnAdd.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnAdd.setBackground(Color.WHITE);
}
});
menu.add(btnAdd);
breedLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
breedLabels[i] = new JLabel(breedInfo[i]);
}
textLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
textLabels[i] = new JLabel(breedInfo[i]);
}
}
}
Is it possible to initialize for example JPanel outside Window class?"
Yes. A different class might contain a method that creates & returns a JPanel.
Other tips:
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.
new Font("Verdana", Font.PLAIN, 20) Use defaults or logical fonts (E.G. Font.SERIF) unless the font is supplied with your app. as an embedded resource.
The loop and array of labels that are added to viewBreed suggest it should be a JList rather than a JPanel
layeredPane.removeAll(); .. Ugh.. Use a CardLayout as shown in this answer.
What is the purpose of the JLayeredPane? I expect it's unnecessary purely on the basis that there is so little use for them.

How to make int variable visible to other class from GUI JButton

I'm trying to access the int myInt in this GUI form class from another class. The method does pass the input variable to myInt properly but I have not been able to make it visible to the other java file. I have been reading about scope and class declarations and have been able to muddle along up until now, but I am doing something wrong here. Nothing I have tried has worked.
package com.jdividend.platform.allocation;
import com.ib.client.*;
import com.jdividend.platform.model.*;
import com.jdividend.platform.trader.*;
import com.jdividend.platform.util.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
* Dialog to show the account size allowed info.
*/
public class AllocationDialog extends JDialog {
/* inner class to define the "about" model */
public static class AllocationTableModel extends TableDataModel {
private AllocationTableModel() {
String[] aboutSchema = {"Property", "Value"};
setSchema(aboutSchema);
}
}
public AllocationDialog(JFrame parent) {
super(parent);
init();
pack();
setLocationRelativeTo(parent);
setVisible(true);
}
public void init() {
setModal(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle("Allocation - JDividend");
JPanel contentPanel = new JPanel();
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
{
JPanel panel = new JPanel();
contentPanel.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBounds(84, 146, 274, 19);
panel.add(panel_1);
JLabel lblNewLabel = new JLabel("Total account cash and margin that");
panel_1.add(lblNewLabel);
JPanel panel_2 = new JPanel();
panel_2.setBounds(84, 163, 274, 19);
panel.add(panel_2);
JLabel lblJdividendIsAllowed = new JLabel("JDividend is allowed to trade with.");
panel_2.add(lblJdividendIsAllowed);
JFormattedTextField formattedTextField = new JFormattedTextField();
formattedTextField.setBounds(172, 189, 100, 20);
panel.add(formattedTextField);
JButton btnOk = new JButton("OK");
btnOk.setBounds(121, 221, 89, 23);
panel.add(btnOk);
btnOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
int myInt = Integer.parseInt(formattedTextField.getText());
System.out.println(myInt);
//do some stuff
}
catch (NumberFormatException ex) {
System.out.println("Not a number");
//do you want
}
JButton btnCancel = new JButton("Cancel");
btnCancel.setBounds(238, 220, 89, 23);
panel.add(btnCancel);
formattedTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JButton button = new JButton("OK");
}
});
}
});
}
String serverVersion = "Disconnected from server";
Trader trader = Dispatcher.getInstance().getTrader();
if (trader != null) {
int version = trader.getAssistant().getServerVersion();
if (version != 0) {
serverVersion = String.valueOf(version);
}
}
TableDataModel aboutModel = new AllocationTableModel();
getContentPane().setPreferredSize(new Dimension(450, 400));
Properties properties = System.getProperties();
Enumeration<?> propNames = properties.propertyNames();
while (propNames.hasMoreElements()) {
String key = (String) propNames.nextElement();
String value = properties.getProperty(key);
String[] row = {key, value};
aboutModel.addRow(row);
}
}
}
myInt should be declared inside the class, but outside of any method implementations:
public class AllocationDialog extends JDialog {
public int myInt;
// ...
}

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

Java, runing "textArea = new JTextArea()" taking too much time

Something strange happened to me. For some reason, it takes a long time(1.60900 seconds) till it runs the following line:
textArea = new JTextArea();
I declared textArea variable as globally.
This only happens in one window (Jframe). In others it does not happen.
public class FAQ extends JFrame
{
/*--------attributes--------*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel;
private JScrollPane scrollPaneInput;
private JScrollPane scrollPaneQuestions;
private JPanel paneQuestions;
private JPanel paneSelectOrNewFAQ;
private JButton btnEditSelection;
private JButton btnNewFAQ;
public JTextArea textArea;
private JLabel lblQuestions;
public JList list;
private User user;
private FAQ currentWindow;
private int selectedFaq = 0;
private DatabaseManager DManager;
private Vector<FAQ_class> Faqs = new Vector<FAQ_class>();
private JButton btnNewButton;
/*--------methods--------*/
public FAQ(User _user,DatabaseManager DM)
{
setResizable(false);
DManager = DM;
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent arg0) {
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
Menu menu = new Menu(user,DManager);
menu.setVisible(true);
}
});
currentWindow = this;
user = _user;
addGui();
if(!user.rule.equals("patient"))
{
btnEditSelection.setEnabled(true);
btnNewFAQ.setEnabled(true);
}
loadFaqs();
}//end of FAQ
public void loadFaqs()
{
Faqs = DManager.getQuestionsList();
Vector<String> temp = new Vector<String>();
for(int i = 0 ; i < Faqs.size();i++)
{
temp.addElement(Faqs.get(i).question);
}
list.setListData(temp);
}
public void addGui()
{
setTitle("FAQ - Online medical help");
setIconImage(Toolkit.getDefaultToolkit().getImage(FAQ.class.getResource("/Images/question.png")));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 708, 438);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 0, 0, 0));
addPanel();
addPanes();
addButtons();
addGroupLayout();
addJTextArea();
}//end of addGui
public void addPanel()
{
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(panel);
}//end of addPanel
public void addPanes()
{
scrollPaneInput = new JScrollPane();
scrollPaneInput.setBounds(327, 0, 365, 398);
paneQuestions = new JPanel();
paneQuestions.setBounds(0, 0, 317, 38);
paneQuestions.setBackground(new Color(154, 205, 50));
}//end of addScrollPanes
public void addButtons()
{
}//end of addButtons
public void addJTextArea()
{
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(new Font("Courier New", Font.PLAIN, 14));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
scrollPaneInput.setViewportView(textArea);
}//end of addJTextArea
public void addGroupLayout()
{
lblQuestions = new JLabel("Questions");
lblQuestions.setHorizontalAlignment(SwingConstants.CENTER);
lblQuestions.setBounds(0, 0, 317, 38);
lblQuestions.setForeground(new Color(255, 255, 255));
lblQuestions.setFont(new Font("Tahoma", Font.BOLD, 22));
panel.setLayout(null);
scrollPaneQuestions = new JScrollPane();
scrollPaneQuestions.setBounds(0, 37, 317, 318);
list = new JList();
list.setSelectionBackground(new Color(154, 205, 50));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
try
{
for(int i = 0; i<Faqs.size();i++)
{
if(!list.isSelectionEmpty())
if(Faqs.get(i).question.equals(list.getSelectedValue().toString()))
{
textArea.setText(Faqs.get(i).answer);
selectedFaq = i;
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
scrollPaneQuestions.setViewportView(list);
panel.add(scrollPaneQuestions);
panel.add(paneQuestions);
paneQuestions.setLayout(null);
paneQuestions.add(lblQuestions);
panel.add(scrollPaneInput);
paneSelectOrNewFAQ = new JPanel();
paneSelectOrNewFAQ.setBounds(0, 348, 317, 50);
btnEditSelection = new JButton("Edit Selected");
btnEditSelection.setBounds(68, 11, 131, 40);
btnEditSelection.setEnabled(false);
btnEditSelection.addActionListener(new ActionListener() {
//open EditFAQ to edit FAQ
public void actionPerformed(ActionEvent e) {
if(!list.isSelectionEmpty())
{
EditFAQ faq = new EditFAQ(user,Faqs.get(selectedFaq),currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
else
{
JOptionPane.showMessageDialog(null,"You must select for the list first.");
}
}
});
btnEditSelection.setIcon(new ImageIcon(FAQ.class.getResource("/Images/tool.png")));
btnNewFAQ = new JButton("New FAQ");
btnNewFAQ.setBounds(203, 11, 114, 40);
btnNewFAQ.setEnabled(false);
btnNewFAQ.addActionListener(new ActionListener() {
//open EditFAQ to make new FAQ
public void actionPerformed(ActionEvent e) {
EditFAQ faq = new EditFAQ(user,null,currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
});
btnNewFAQ.setMinimumSize(new Dimension(95, 23));
btnNewFAQ.setMaximumSize(new Dimension(95, 23));
btnNewFAQ.setPreferredSize(new Dimension(95, 23));
btnNewFAQ.setIcon(new ImageIcon(FAQ.class.getResource("/Images/add.png")));
btnNewButton = new JButton("");
btnNewButton.setBounds(0, 10, 42, 41);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnNewButton.setIcon(new ImageIcon(FAQ.class.getResource("/Images/left.png")));
panel.add(paneSelectOrNewFAQ);
paneSelectOrNewFAQ.setLayout(null);
paneSelectOrNewFAQ.add(btnNewButton);
paneSelectOrNewFAQ.add(btnEditSelection);
paneSelectOrNewFAQ.add(btnNewFAQ);
}//end of addGroupLayout
}//end of class
Something strange happened to me. For some reason, it takes a long time(5 second~) till it runs the following line: Run this class and give me the result:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTextArea;
public class JTextAreaRunningTime {
JTextArea textArea;
public JTextAreaRunningTime(){
long startTime = System.currentTimeMillis();
textArea = new JTextArea();
long endTime = System.currentTimeMillis();
NumberFormat nf = new DecimalFormat("#0.00000");
String totalTime = nf.format((endTime-startTime)/1000d);
System.out.println("Execution time is " + totalTime + " seconds");
}
public static void main (String...argW){
new JTextAreaRunningTime();
}
}

Categories