I am not sure what I am doing wrong. I am trying to create 4 buttons using the arrays and passing the method to the Set Panel class. When I run it I only get one button. Any help would be great. Essentially what I want is a Panel with four buttons, through the use of Methods.
public class SetButtons extends JButton implements ActionListener {
JButton [] buttonArray = new JButton[4];
JButton exitBtn, newGameBtn, checkBtn, clearBtn;
Font myFont = new Font("ink free", Font.BOLD,22);
public SetButtons(){
this.exitBtn = new JButton("Exit");
this.newGameBtn = new JButton("New Game");
this.checkBtn = new JButton("Check Answer");
this.clearBtn = new JButton("Clear");
this.buttonArray[0] = exitBtn;
this.buttonArray[1] = newGameBtn;
this.buttonArray[2] = checkBtn;
this.buttonArray[3] = clearBtn;
for (int i = 0; i < 4; i++){
this.buttonArray[i].addActionListener(this);
this.buttonArray[i].setFont(myFont);
this.buttonArray[i].setFocusable(false);
this.buttonArray[i].setLayout(new FlowLayout());
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this){
System.exit(0);
}
}
}
import javax.swing.*;
import java.awt.*;
public class SetPanel extends JPanel {
Font myFont = new Font("ink free", Font.BOLD,22);
SetLabels labels;
SetButtons exitButton;
SetPanel(){
SetButtons btn = new SetButtons();
this.add(btn);
this.setBackground(Color.darkGray);
this.setLayout(new FlowLayout());
}
}
I'm trying to build a chessclock to learn and I'm stuck with the code below. I'll use the actionListener like this. When "White" button is pressed, blackTime will decrement one every second, when "Black" button is pressed whiteTime will decrement one every second.
Right now my problem is to find a way to decrement time each second. I saw some questions like this and they talked about Timer class. I never used it and my understanding is it requires an ActionListener. I'm already using one so do I add another somehow or is there a simpler way?
Thanks!
public class ChessClock extends JFrame implements ActionListener {
JPanel p;
JButton b1,b2;
JLabel l1;
public ChessClock(){
super();
this.setVisible(true);
this.setSize(600,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int whiteTime = 59;
int blackTime = 59;
p = new JPanel(new GridBagLayout());
b1 = new JButton("White");
b2 = new JButton("Black");
l1 = new JLabel("00:" + whiteTime + " - " + "00:" + blackTime, SwingConstants.CENTER);
l1.setFont(new Font("Serif", Font.PLAIN, 85));
b1.setPreferredSize(new Dimension(200,100));
b2.setPreferredSize(new Dimension(200,100));
b1.addActionListener(this);
b2.addActionListener(this);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(40,40,40,40);
p.add(b1,c);
p.add(b2,c);
this.add(p, BorderLayout.SOUTH);
this.add(l1, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e){ //will later be used to switch between whiteTime - blackTime
String s = e.getActionCommand();
if(s == "White")
s = s;
if(s == "Black")
s = s;
}
}
From Java Docs,
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(blackTurn)
black--;
else if(whiteTurn)
white--;
}
};
new Timer(delay, taskPerformer).start();
I think in general you should avoid using Thread.sleep() and use the built in timer class! A while loop with Thread.sleep() will hold up the thread and wait, while timer will not.
So yes, create another action performed!
How about a:
While(condition){
Thread.sleep(1000);
if(//White button pressed){
blackTime--;
}else{
whiteTime--;
}
It will wait 1s before doing the code below.
So I am relatively new to Java and trying to create a checkers game using JButtons for the board and for the pieces. However I cannot seem to be able to remove a JButton via the ActionListener. Any advice would be appreciated.
public static void main(String[] args) {
checkersBeBitchin begin = new checkersBeBitchin();
}
public checkersBeBitchin(){
box.setLayout(new BorderLayout());
makeBoard();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(600,600);
setTitle("Checkers");
}
private void makeBoard() {
JPanel board = new JPanel();
board.setLayout(new GridLayout(8,8));
for (int i=0; i<8; i++){
for (int j=0; j<8; j++) {
squares[i][j] = new JButton();
ActionListener actionListener = new Board();
squares[i][j].addActionListener(actionListener);
if((i%2 != 0 && j%2 !=0) ||(i%2==0 && j%2 == 0) ){
squares[i][j].setBackground(Color.black);
pieceTracker[i][j]=0;
//System.out.println("Black"+i+","+j); debugging
if(i<3){
int blue = 1;
Icon piece = new ImageIcon(getClass().getResource("/resources/piece.png"));
JButton button = new JButton(piece);
//squares[i][j].setRolloverIcon("image dir") to make it prettier down the road.
squares[i][j].add(button);
pieceTracker[i][j]=blue;
ActionListener Listener = new Blue();
button.addActionListener(Listener);
}
else if (i>4){
int red=-1;
Icon piece = new ImageIcon(getClass().getResource("/resources/piece2.png"));
JButton button = new JButton(piece);
squares[i][j].add(button);
pieceTracker[i][j]=red;
ActionListener Listener = new Red();
button.addActionListener(Listener);
//squares[i][j].setRolloverSelectedIcon("/resources/piece2alt.png");
}
}
else{
squares[i][j].setBackground(Color.white);
pieceTracker[i][j]=0;
//System.out.println("White"+i+","+j); //debugging
}
board.add(squares[i][j]);
}
}
box.add(board, BorderLayout.CENTER);
}
private class Blue implements ActionListener{
public void actionPerformed (ActionEvent e){
System.out.println("You sexy Blue beast.");
Object x = e.getSource();
System.err.println(x);
squares.remove(x);
squares.remove? Should it read squares.remove(x)? Can we see the definition of squares? Is it an array? You must remove the button from the BOARD not the square, e.g. board.remove(x)
There is a one J Frame in which i have put 2 panels & the Card layout is given to the both panels
by image J Frame having 2 panels one is
panel pane >>Where i an going to call panel1, panel2, panel3 where all that 3 panels have some controls like JtextField, jComboBox etc.
button pane >> in this the panel have button next & back when next is pressed (if panel pane Showing panel1 then) panel1 controls to be get validate
like that etc
code is as follow
package Code;
/**
*
* #author Rohini
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class InvoicePage extends JFrame implements ActionListener{
JLabel newInvoic, invoiceNol, invoiceNo;
JButton clinfoNext, payentryNext, termentryNext;
JButton clinfoBack, payentryBack, termentryBack;
JPanel buttonPane, clinfoBPane, payentryBPane, termentryBPane;
JPanel panelpane, client_info, invoice_entry, term_entry;
Container c = this.getContentPane();
CardLayout cardmain, cardbutton;
Font head = new Font("Times New Roman",Font.BOLD,20);
Font subheadb = new Font("Times New Roman",Font.BOLD,14);
Font subheadp = new Font("Times New Roman",Font.PLAIN,14);
public InvoicePage() throws HeadlessException {
super("Thane Bharat Sahakari Bank : New Invoice");
// initialization of variables
cardmain = new CardLayout();
cardbutton = new CardLayout();
newInvoic = new JLabel("New Invoice");
invoiceNol = new JLabel("Invoice No");
invoiceNo = new JLabel("DB Value of id");
clinfoNext = new JButton(" Next > > ");
payentryNext = new JButton(" Next > > ");
termentryNext = new JButton(" Next > > ");
clinfoBack = new JButton(" < < Back ");
payentryBack = new JButton(" < < Back ");
termentryBack = new JButton(" < < Back ");
buttonPane = new JPanel(cardbutton);
clinfoBPane = new JPanel(null);
payentryBPane = new JPanel(null);
termentryBPane = new JPanel(null);
panelpane = new JPanel(cardmain);
client_info = new clientInfo();
invoice_entry = new discription();
term_entry = new termentry();
// setting properties of variabels
panelpane.add(client_info,"Client_info");
panelpane.add(invoice_entry,"invoice_entry");
panelpane.add(term_entry,"term_entry");
buttonPane.add(clinfoBPane,"clinfoBpane");
buttonPane.add(payentryBPane,"payentryBPane");
buttonPane.add(termentryBPane,"termentryBPane");
clinfoBPane.add(clinfoBack);
clinfoBPane.add(clinfoNext);
payentryBPane.add(payentryBack);
payentryBPane.add(payentryNext);
termentryBPane.add(termentryBack);
termentryBPane.add(termentryNext);
newInvoic.setFont(head);
invoiceNol.setFont(subheadb);
invoiceNo.setFont(subheadp);
clinfoNext.addActionListener(this);
payentryNext.addActionListener(this);
termentryNext.addActionListener(this);
clinfoBack.addActionListener(this);
payentryBack.addActionListener(this);
termentryBack.addActionListener(this);
// setting Bounds
Bounds(0,0);
// Adding Components
c.add(newInvoic);
c.add(invoiceNol);
c.add(invoiceNo);
c.add(buttonPane);
c.add(panelpane);
// Form properties
cardbutton.show(buttonPane,"clinfoBpane");
cardmain.show(panelpane,"Client_info") ;
c.setLayout(null);
c.setBackground(Color.WHITE);
//clinfoBPane.setBackground(Color.WHITE);
this.setResizable(true);
this.setVisible(true);
setDefaultCloseOperation(3);
System.out.println("");
}
public void Bounds( int i, int j ){
if(i == 0){
newInvoic.setBounds(250,0,150,30);
invoiceNol.setBounds(400,30,100,25);
invoiceNo.setBounds(500,30,100,25);
buttonPane.setBounds(0,410,610,50);
panelpane.setBounds(0,50,610,350);
clinfoNext.setBounds(430,5,150,30);
clinfoBack.setBounds(25,5,150,30);
this.setSize(625,505);
this.setLocation(300,150);
}
else if(i == 1){
newInvoic.setBounds(350,0,150,30);
invoiceNol.setBounds(600,30,100,25);
invoiceNo.setBounds(700,30,100,25);
buttonPane.setBounds(0,440,830,50);
panelpane.setBounds(0,50,815,390);
if(j == 0){
payentryNext.setBounds(640,5,150,30);
payentryBack.setBounds(30,5,150,30);
}
else if(j == 1){
termentryNext.setBounds(640,5,150,30);
termentryBack.setBounds(30,5,150,30);
}
this.setSize(830,525);
this.setLocation(200,100);
}
else{
}
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == clinfoNext){
cardbutton.show(buttonPane,"payentryBPane");
cardmain.show(panelpane,"invoice_entry") ;
Bounds(1,0);
}
else if(ae.getSource() == clinfoBack){
this.dispose();
Mainfrm mf = new Mainfrm();
mf.setVisible(true);
}
else if((ae.getSource() == payentryNext)){
Bounds(1,1);
cardbutton.show(buttonPane,"termentryBPane");
cardmain.show(panelpane,"term_entry") ;
}
else if(ae.getSource() == payentryBack){
Bounds(0,0);
cardbutton.show(buttonPane,"clinfoBpane");
cardmain.show(panelpane,"Client_info") ;
}
else if(ae.getSource() == termentryBack){
cardbutton.show(buttonPane,"payentryBPane");
cardmain.show(panelpane,"invoice_entry") ;
Bounds(1,0);
}
else if(ae.getSource() == termentryNext){
JOptionPane.showConfirmDialog(this,"Are you sure that the invoice is over","Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, 0);
}
else{
}
}
public static void main(String []avi){
new InvoicePage();
}
}
yes!! i got the answer
actually the outside panel variables are need to be have a public scope
&
(see above code)
JPanel panelpane, client_info, invoice_entry, term_entry;
i have created the instance of JPanel & initiate it with the outside panel i.e
client_info = new clientInfo();
invoice_entry = new discription();
term_entry = new termentry();
instead of that the panels are doing
JPanel panelpane, client_info, invoice_entry, term_entry;
by trying this problem get solve
JPanel panelpane;
clientInfo client_info;
discription invoice_entry;
by this we can able to give the actionListner
I got a little problem with a JOptionPane which I use to warn user if wrong input is found. It works correct first time. But when I close down the JFrame which calls for that JOptionPane, and open it again it will this time call for it twice. And it will stack for every close down I do.
I have tried to look for the problem without any luck. I can provide the code, but it is quite large though.
Third EDIT: I have found and solved the problem now.
Ok, I provided the code I use. I have cut it down so it only show the necessary one. I dont think it will compile, but this is how I use the addActionListener();
public class BorderLayoutDemo extends JFrame implements ActionListener {
private JButton button1 = new JButton("L?gg till kund");
private JButton button2 = new JButton("Ta bort kund");
private JButton button3 = new JButton("Visa kund");
private JButton button4 = new JButton("Lista alla kunder");
private JButton button5 = new JButton("Avsluta");
private JButton button6 = new JButton("Change");
private JTextArea TextWindow = new JTextArea("Hej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\nHej\n");
private JScrollPane scrollPane = new JScrollPane(TextWindow); //l?gger in TextWindow s? att det f?r en scroll-bar
private JPanel aPanel = new JPanel();
private JFrame aFrame = new JFrame();
private JTextField aTextfield1 = new JTextField();
private JTextField aTextfield2 = new JTextField();
private JButton aButton1 = new JButton("L?gg till kund");
private JButton aButton2 = new JButton("St?ng");
public BorderLayoutDemo() {
setTitle("Bankregister");
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
panel.setLayout(new GridLayout(6,1,55,5)); //row, cols, hgap, vgap
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button5.addActionListener(this);
button6.addActionListener(this);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
panel.add(button6);
JPanel panel2 = new JPanel();
panel2.add(panel);
add(panel2,BorderLayout.WEST);
add(scrollPane,BorderLayout.CENTER);
setJMenuBar(menu());
setSize(600,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void addCustomer(boolean status) {
if(status) {
aFrame.setTitle("L?gg till kund");
aFrame.setSize(200,300);
aFrame.setLayout(new GridLayout(3,1));
aPanel.setLayout(new GridLayout(2,1)); //rad, kolumn
aPanel.add(aTextfield1);
aPanel.add(aTextfield2);
aButton1.addActionListener(this);
aButton2.addActionListener(this);
System.out.println("Foo!!!!!!!!!!!!!");
aFrame.add(aPanel);
aFrame.add(aButton1);
aFrame.add(aButton2);
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setLocationRelativeTo(null);
aFrame.setVisible(true);
}
else {
aFrame.setVisible(false);
}
}
public static void main(String[] args) {
new BorderLayoutDemo();
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1) {
setEnabled(false);
addCustomer(true);
}
//IFs f?r addCustomer();
else if(e.getSource() == aButton1) {
if((aTextfield1.getText().isEmpty() || aTextfield2.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "You miss to fill out the fields");
}
else {
JOptionPane.showMessageDialog(null, "Added");
Kund kund = new Kund(aTextfield1.getText(),aTextfield2.getText());
setEnabled(true);
register.add(kund);
}
}
else if(e.getSource() == aButton2) {
setEnabled(true);
addCustomer(false);
}
Sounds like you are adding the "validation listener" every time you open the JFrame. So check your "addListenerXXX" code to make sure it is only added/created once.
Which also leads to the question why are you using a JFrame for this? Typically an application has a single JFrame. Then, if you need a window to enter data you create a JDialog.
By passing null as the first parameter of that method you are creating a default JFrame that the JOptionPane uses as its parent component and not the JFrame you have created in your code. If you provide more detail in your question I'm sure someone here will provide you with a much more detailed answer.