JButton is not adding - java

I'm not sure why my JButton is not displaying when I add it to the JPanel class: if my class extends JPanel, shouldn't this.add be sufficient? And if I remove this Jpanel class from another Jpanel, the components attached to this panel should disappear as well right? Thank you!
public class Menu extends JPanel{
private static final long serialVersionUID = 1L;
static boolean startGame = false;
public static String user;
public Menu(final JFrame frame) {
JPanel userName = new JPanel(); // create new JPanel
final JTextField text = new JTextField();
text.setText("input your username here");
//adds userName input box to the panel
Action action = new AbstractAction(){
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
user = text.getText();
text.setVisible(false);
Menu.startGame = true;
}};
text.addActionListener(action);
userName.add(text);
frame.add(userName, BorderLayout.SOUTH);
frame.revalidate();
frame.repaint();
setFocusable(true);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
sndMenu newMenu = new sndMenu(frame);
newMenu.setVisible(true);
}
});
/**
* this does not display help!
*/
//add a button to the menu called "help"
JButton help = new JButton("get instructions");
this.add(help,BorderLayout.CENTER);
help.setVisible(true);
help.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
instructions instr = new instructions(frame);
frame.add(instr);
frame.revalidate();
frame.repaint();
}
});
}
public void paint (Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
Font fnt0 = new Font("Manaspace", Font.BOLD, 40);
Font fnt1 = new Font("Manaspace", Font.BOLD, 30);
g.setFont(fnt0);
g.setColor(Color.white);
g.drawString("Welcome To Jumping Box!", 120, 300);
g.setFont(fnt1);
g.drawString("Click to play!", 260, 400);
}
}

Related

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.

Java : Can't display JPanel above a JLabel with image

here's my problem : I display an ArrayList of JLabel with image and a JPanel with buttons inside a JPanel and I want to display my JPanel above my JLabel when I press a button. But when I press the button, my JPanel is under the JLabels.
Please don't tell me to use a JLayerPane cause if I can do without it it would be best.
Thanks for your solutions.
Here's an exemple of my code :
To run this put the image 100x100 found here :
http://www.html5gamedevs.com/topic/32190-image-very-large-when-using-the-dragging-example/
in a file named image
Main :
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("test");
frame.setSize(900,700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
JPanelControler ctrl = new JPanelControler();
frame.add(ctrl.getMyJpanel());
frame.setVisible(true);
}
}
MyJPanelControler :
public class JPanelControler {
private MyJPanel myJpanel;
public JPanelControler() {
myJpanel = new MyJPanel();
myJpanel.createJLabel();
myJpanel.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myJpanel.displayJPanel();
}
});
}
public MyJPanel getMyJpanel() {
return myJpanel;
}
}
MyJPanel :
public class MyJPanel extends JPanel {
private JButton button;
private ArrayList<JLabel> labels;
//a JPanel that contains buttons,... I won't put this class here
private JPanel panel;
public MyJPanel() {
setLayout(null);
button = new JButton("X");
button.setBounds(600,600,50,50);
add(button);
}
public void createJLabel() {
labels = new ArrayList<>();
JLabel label;
try {
BufferedImage image = ImageIO.read(new File("images/image.jpg"));
for(int i=0; i<2; i++) {
label = new JLabel(new ImageIcon(image));
label.setBounds(i*100,50,image.getWidth(), image.getHeight());
labels.add(label);
add(label);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void displayJPanel() {
panel = new JPanel();
panel.setLayout(null);
JButton b = new JButton("Ok");
b.setBounds(0,0,100, 50);
JButton b2 = new JButton("Cancel");
b2.setBounds(0,50,100, 50);
panel.setBounds(150,50, 100, 100);
panel.add(b);
panel.add(b2);
add(panel);
refresh();
}
public void refresh() {
invalidate();
revalidate();
repaint();
}
public JButton getButton() {return this.button; }
}
If you want the buttons to appear over plain images, then you have one of two options:
Draw the images in a paintComponent override in the main JPanel and not as ImageIcons within a JLabel. This will allow you to add components to this same JPanel, including buttons and such, and the images will remain in the background. If you go this route, be sure to call the super.paintComponent(g); method first thing in your override.
Or you could use a JLayeredPane (regardless of your not wanting to do this). You would simply put the background JPanel into the JLayeredPane.DEFAULT_LAYER, the bottom layer (constant is Integer 0), and place the newly displayed JButton Panel in the JLayeredPane.PALETTE_LAYER, which us just above the default. If you go this route, be sure that the added JPanel is not opaque, else it will cover over all images completely.
For an example of the 2nd suggestion, please see below:
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
public class JPanelControler {
private MyJPanel myJpanel;
public JPanelControler() {
myJpanel = new MyJPanel();
myJpanel.createJLabel();
myJpanel.getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myJpanel.displayJPanel();
}
});
}
public MyJPanel getMyJpanel() {
return myJpanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("test");
frame.setSize(900, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
JPanelControler ctrl = new JPanelControler();
frame.add(ctrl.getMyJpanel());
frame.setVisible(true);
}
}
class MyJPanel extends JLayeredPane {
private static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia"
+ "/commons/thumb/f/fc/Gros_Perr%C3%A9.jpg/100px-Gros_Perr%C3%A9.jpg";
private JButton button;
private ArrayList<JLabel> labels;
// a JPanel that contains buttons,... I won't put this class here
private JPanel panel;
public MyJPanel() {
setLayout(null);
button = new JButton("X");
button.setBounds(600, 600, 50, 50);
add(button, JLayeredPane.DEFAULT_LAYER); // add to the bottom
}
public void createJLabel() {
labels = new ArrayList<>();
JLabel label;
try {
URL imgUrl = new URL(IMG_PATH); // ** added to make program work for all
BufferedImage image = ImageIO.read(imgUrl);
for (int i = 0; i < 2; i++) {
label = new JLabel(new ImageIcon(image));
label.setBounds(i * 100, 50, image.getWidth(), image.getHeight());
labels.add(label);
add(label);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void displayJPanel() {
panel = new JPanel();
panel.setLayout(null);
panel.setOpaque(false); // ** make sure can see through
JButton b = new JButton("Ok");
b.setBounds(0, 0, 100, 50);
JButton b2 = new JButton("Cancel");
b2.setBounds(0, 50, 100, 50);
panel.setBounds(150, 50, 100, 100);
panel.add(b);
panel.add(b2);
add(panel, JLayeredPane.PALETTE_LAYER); // add it above the default layer
refresh();
}
public void refresh() {
// invalidate(); // not needed
revalidate();
repaint();
}
public JButton getButton() {
return this.button;
}
}

Receive KeyEvents when JTextField is focused

I'm developing a game and I have a JFrame that receives in input the player name in a JTextField.
What I want is the possibility to close the window by either pressing a JButton or by pressing the ENTER key.
When the window opens the JTextField must have the focus (the cursor should appear in the component).
I already saw:
How do you make key bindings for a java.awt.Frame?
How do you make key binding for a JFrame no matter what JComponent is in focus?
but I have not solved the problem, there's probably something wrong in the focus management.
I tried the following code:
public class PlayerNameWindow extends JFrame implements KeyListener {
private String playerName;
private JLabel backgroundLabel;
private JLabel enterNameLabel;
private JButton confirmButton;
private JTextField nameField;
private Image background;
public PlayerNameWindow() {
initComponents();
}
private void initComponents() {
backgroundLabel = new JLabel();
enterNameLabel = new JLabel();
confirmButton = new JButton();
nameField = new JTextField();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 200));
setResizable(false);
getContentPane().setLayout(null);
addKeyListener(this);
enterNameLabel.setFont(new Font("Tahoma", 1, 18));
enterNameLabel.setForeground(new Color(255, 255, 255));
enterNameLabel.setText("Enter your name:");
getContentPane().add(enterNameLabel);
enterNameLabel.setBounds(40, 80, 160, 30);
confirmButton.setText("Confirm");
confirmButton.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
confirmButtonMouseClicked(evt);
}
});
confirmButton.setBounds(160, 150, 90, 25);
getContentPane().add(confirmButton);
getContentPane().add(nameField);
nameField.setBounds(220, 80, 140, 30);
getContentPane().add(backgroundLabel);
backgroundLabel.setBounds(0, 0, 400, 200);
pack();
setLocationRelativeTo(null);
}
private void confirmButtonMouseClicked(MouseEvent evt) {
confirmAction();
}
private void confirmAction() {
playerName = nameField.getText();
System.exit(0);
}
public String getPlayerName() {
return this.playerName;
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ENTER)
System.exit(0);
}
public void keyReleased(KeyEvent e) {
//do-nothing
}
public void keyTyped(KeyEvent e) {
//do-nothing
}
}
How can I do?
Thanks
add keyListener to the JTextField. in your code, nameField.addKeyListener(this);

Issues with JButtons and ActionEvent

For some reason, when I click my buttons, it makes it into the actionPerformed method, but the program can't match any of the buttons to an actionevent, so nothing works when any of my buttons are pressed. I took the code out of paintcomponent and put it in the constructor, but now the buttons don't show up. Can someone please help?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
//
public class game extends JFrame//header
{
private CardPanel mp;
private Font big = new Font("Verdana", Font.BOLD, 100);
private Font small = new Font("Verdana", Font.BOLD, 90);
private Font norm = new Font("Verdana", Font.PLAIN, 23);
private CardLayout cards;
private JButton back;
private boolean clairewang=false;
private boolean wangfam=false;
private boolean cl=false;
private JButton next;
private JButton instruction;
private JButton startb;
private JButton done;
private JTextArea title;
private Color c=new Color(186,225,200);
private int a=0;;
private JButton yes;
private JButton no;
private int x;
private int y;
private JButton claire= new JButton("PLAY!");
private JButton fambam=new JButton("PLAY!");
private JButton sickbob=new JButton("PLAY!");
private String pc="Play as Claire (medium)- an able bodied 20 yearold";
private String pfb="Play as a family (hard)- receive more waterper week.";
private String psb="Play as Bob (easy)- he is connected to thecity's water" ;
private String psb2="supply because he has brain cancer.";
public static void main(String [] args)
{
game b = new game();//create constructor
}
public game()//Bio constructor
{
//set everything for JFrame
setSize(900,600);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocation(0,0);
setResizable(false);//set to false
mp = new CardPanel();
cards = new CardLayout();
back = new JButton("BACK");
done= new JButton("DONE");
next = new JButton("NEXT");
next.setBounds(275,200, 315, 220);
Start beg = new Start();
instruct1 inst1 = new instruct1();
instruct2 inst2 = new instruct2();
choosepanel ch = new choosepanel();
sb1 sb= new sb1();
fb1 f1= new fb1();//FINISH THIS
fb2 f2= new fb2();
fb3 f3= new fb3();
fb4 f4= new fb4();
c1 s= new c1();
mp.setLayout(cards);
mp.add(beg,"start");
mp.add(inst1,"i1");
mp.add(inst2, "i2");
mp.add(ch,"choose");
mp.add(s, "c1");
mp.add(sb, "sb");
mp.add(f1, "fb1");
mp.add(f2, "fb2");
mp.add(f3, "fb3");
mp.add(f4, "fb4");
setContentPane(mp);
setVisible(true);
}
class CardPanel extends JPanel
{
public CardPanel()
{
}
}
class Start extends JPanel implements ActionListener
{
public Start()
{
setLayout(null);
startb = new JButton("START");
startb.setBounds(255,200, 315, 100);
instruction = new JButton("INSTRUCTIONS");
instruction.setBounds(255,320, 315, 100);
//make text area uneditable
instruction.addActionListener(this);
startb.addActionListener(this);
add(startb);
add(instruction);
}
public void paintComponent(Graphics g)
{
setBackground(c);
super.paintComponent(g); //import image
setFont(big);
g.setColor(Color.WHITE);
g.drawString("THIRST", 230,150);
// g.setColor(c);
// g.drawString("THIRST",235,153);
// g.setColor(Color.WHITE);//have loop that draws waves
for( y=0;y<600;y+=200){
for(x=0;x<800;x+=100){
g.drawArc(x,y, 100,50,0,-180);
}
}
for(y=100;y<600;y+=200){
for(x=-50;x<800;x+=100){
g.drawArc(x,y, 100,50,0,-180);
}
}
//for( y=0; y<600;x+=100){
// for(x=0; x<800;x+=50){
// g.drawArc(x, y, 50,50,0,-180);
// }
//}
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource()==instruction) {
cards.show(mp,"i1"); }
else if(evt.getSource()==startb){
cards.show(mp, "choose");
}
}
}
/* class instruct extends JPanel implements ActionListener
{//header
public instruct()
{
setLayout(null);
next = new JButton("NEXT");
next.setBounds(600,500,100,50);
//instruction.setBounds(225,500, 275, 575);
back = new JButton("BACK");
back.setBounds(100,500,100,50);
// instruction.setBounds(225,500, 375, 575);
next.addActionListener(this);
back.addActionListener(this);
add(next);
add(back);
}
public void paintComponent(Graphics g){
setBackground(c);
super.paintComponent(g);
setFont(big);
g.setColor(Color.WHITE);
g.drawString("THING0", 230,150);
//draw the instructions in the center using blackor white
}
public void actionPerformed(ActionEvent evt){
// if(((JButton)(evt.getSource()).getText()).equals("BACK"))
// cards.show(mp,"start");
// System.out.println("X");
// }
//if ((((JButton)(evt.getSource()).getText()).equals("NEXT")) ){
//cards.show(mp,"i1");
//System.out.println("X");
//}
if (evt.getSource()==next ){
cards.show(mp,"i1");
System.out.println("X");
}
else if (evt.getSource()==back) {
cards.show(mp,"start");
System.out.println("X");
}
}
} */
class instruct1 extends JPanel implements ActionListener{
public instruct1(){
setLayout(null);
next = new JButton("NEXT");
next.setBounds(600,500,100,50);
//instruction.setBounds(225,500, 275, 575);
back = new JButton("BACK");
back.setBounds(100,500,100,50);
next.addActionListener(this);
back.addActionListener(this);
add(next);
add(back);
}
public void paintComponent(Graphics g){
setBackground(c);
super.paintComponent(g); //import image
setFont(big);
g.setColor(Color.WHITE);
g.drawString("THING1", 230,150);
}
public void actionPerformed(ActionEvent evt){
if (evt.getSource()==back) {
cards.show(mp,"start"); }
else if(evt.getSource()==next){
cards.show(mp,"i2");
}
}
}
class instruct2 extends JPanel implements ActionListener{
public instruct2(){
setLayout(null);
done = new JButton("DONE");
back = new JButton("BACK");
back.addActionListener(this);
done.addActionListener(this);
done.setBounds(600,500,100,50);
//instruction.setBounds(225,500, 275, 575);
back.setBounds(100,500,100,50);
add(done);
add(back);
}
public void paintComponent(Graphics g){
setBackground(c);
super.paintComponent(g); //import image
setFont(big);
g.setColor(Color.WHITE);
g.drawString("THING2", 230,150);
}
public void actionPerformed(ActionEvent evt){
if (evt.getSource()==back) {
cards.show(mp,"i1"); }
else if(evt.getSource()==done){
cards.show(mp,"start");
}
}
}
class choosepanel extends JPanel implements ActionListener{
public choosepanel(){
setLayout(null);
sickbob.addActionListener(this);
fambam.addActionListener(this);
claire.addActionListener(this);
sickbob.setBounds(600,200,100,50);
claire.setBounds(600,300,100,50);
fambam.setBounds(600,400,100,50);
add(sickbob);
add(claire);
add(fambam);
//instruction.setBounds(225,500, 275, 575);
}
public void paintComponent(Graphics g){
setBackground(c);
super.paintComponent(g);
setFont(small);
g.setColor(Color.WHITE);
g.drawString("CHOOSE PLAYER", 0,150);
g.setFont(norm);
g.drawString(psb,50,225);
g.drawString(psb2,50,250);
g.drawString(pc,50,325);
g.drawString(pfb,50,425);
}
public void actionPerformed(ActionEvent evt){
if(evt.getSource()==claire){
cards.show(mp, "c1");
clairewang=true;
}
else if(evt.getSource()==sickbob){
cards.show(mp, "c1");
cl=true;}
else if(evt.getSource()==fambam){
cards.show(mp, "c1");
wangfam=true;
}
}
/* public boolean stuff(){
if(wangfam) return wangfam;
else if(cl)return cl;
else if(clairewang)return clairewang;
} */
}
class c1 extends JPanel implements ActionListener{
public void c1(){
/* setLayout(null);
next=new JButton("NEXT");
no=new JButton("NO");
yes=new JButton("YES");
yes.addActionListener(this);
no.addActionListener(this);
next.addActionListener(this);
yes.setBounds(100,200,100,50);
no.setBounds(300,300,100,50);
next.setBounds(700,400,100,50);
add(yes);
add(no);
add(next); */
next=new JButton("NEXT");
no=new JButton("NO");
yes=new JButton("YES");
yes.addActionListener(this);
no.addActionListener(this);
next.addActionListener(this);
yes.setBounds(100,200,100,50);
no.setBounds(300,200,100,50);
next.setBounds(700,500,100,50);
add(yes);
add(no);
add(next);
}
public void paintComponent(Graphics g){
setBackground(c);
super.paintComponent(g);
setLayout(null);
setFont(norm);
g.setColor(Color.WHITE);
g.drawString("Your flowers are wilting. Water your lawn?",20,100);
//print situation yn
//jbutton yes and j button no
g.fillRect(700, 75, 100, 400);//draw the bar that shows how much wateris left
g.fillArc(700,65,100,20,0,180);
g.fillArc(700,465,100,20,0,-180);
g.setColor(c);
g.fillRect(705,82, 90,390);
g.fillArc(705, 463, 90, 18, 0 , -180);
g.setColor(Color.WHITE);
g.fillRect(705,82, 90,a);
// if(clairewang)System.out.println(a);
if(wangfam)System.out.println("wangfam");
else if(cl)System.out.println("cl");
}
public void actionPerformed(ActionEvent evt){
System.out.println("stuff");
if(evt.getSource()==yes){
if(clairewang){
a=15;
System.out.println(a);}
else if(wangfam)a+=20;
else if(cl)a+=10;
//clairewang=true;
repaint();
}
else if(evt.getSource()==next){
cards.show(mp, "sb");
// cl=true;}
//yes gives an int a value
//no stays 0
}
}
}
}
Move the creation and init code out of paintComponent() into constructor
The code
next=new JButton("NEXT");
no=new JButton("NO");
yes=new JButton("YES");
yes.addActionListener(this);
no.addActionListener(this);
next.addActionListener(this);
yes.setBounds(100,200,100,50);
no.setBounds(300,200,100,50);
next.setBounds(700,500,100,50);
add(yes);
add(no);
add(next);
In fact on each repaint it recreates the buttons and readd them. Thus in actionPerformed() button state is changed (to show pressed state) and the button is recreated. And of course it != clicked one.

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