I am working on a Quiz app game (screenshot above). Each time the user clicks on the Next button, I want the timer to restart. Unfortunately this does not happen, the timer keeps ticking. I'm not sure why. What can I try to fix this?
final class Gui extends JFrame {
private Timer timer;
private JLabel timerLabel;
private void createWindow() {
display = new Display();
setLayout(new BorderLayout(3, 3));
add(display, BorderLayout.CENTER);
JPanel timerPanel = new JPanel();
timerPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
timerPanel.setBackground(new Color(0x00bcda));
add(timerPanel, BorderLayout.PAGE_START);
timerLabel = new JLabel("01:00", SwingConstants.RIGHT);
timerLabel.setFont(new Font("Arial", Font.BOLD, 20));
timerLabel.setHorizontalAlignment(JLabel.RIGHT);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 0;
timerLabel.setForeground(Color.black);
timerPanel.add(timerLabel, c);
timer = new Timer(1000, new ActionListener() {
int time = 60;
#Override
public void actionPerformed(ActionEvent e) {
time--;
timerLabel.setText(format(time / 60) + ":" + format(time % 60));
if (time == 0) {
timer = (Timer) e.getSource();
timer.stop();
}
}
});
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Quit")) {
System.exit(0);
} else if (cmd.equals("Start")) {
timer.start();
} else if (cmd.equals("Next")) {
timer.restart();
}
display.repaint();
}
}
}
Restart of timer provides no reinitialization of your time filed.
int time = 60; // here is your problem
To avoid this problem you need to recreate your timer and start it again. For example you can move your timer initialization in a separate method:
final class Gui extends JFrame {
private Timer timer;
private JLabel timerLabel;
private void createWindow() {
display = new Display();
setLayout(new BorderLayout(3, 3));
add(display, BorderLayout.CENTER);
JPanel timerPanel = new JPanel();
timerPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
timerPanel.setBackground(new Color(0x00bcda));
add(timerPanel, BorderLayout.PAGE_START);
timerLabel = new JLabel("01:00", SwingConstants.RIGHT);
timerLabel.setFont(new Font("Arial", Font.BOLD, 20));
timerLabel.setHorizontalAlignment(JLabel.RIGHT);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 0;
timerLabel.setForeground(Color.black);
timerPanel.add(timerLabel, c);
initTimer();
}
private void initTimer() {
timer = new Timer(1000, new ActionListener() {
int time = 60;
#Override
public void actionPerformed(ActionEvent e) {
time--;
timerLabel.setText(format(time / 60) + ":" + format(time % 60));
if (time == 0) {
timer = (Timer) e.getSource();
timer.stop();
}
}
});
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Quit")) {
System.exit(0);
} else if (cmd.equals("Start")) {
timer.start();
} else if (cmd.equals("Next")) {
timer.stop();
initTimer();
timer.start();
}
display.repaint();
}
}
}
Another possibility is to move your time field in your Gui class. In this case you need to reset this field on timer restart.
i am trying to build a JFrame with a swing Timer in a border layout that contains 2 JPanels, both having Timer that suppose to work together, but only one of them work. The timer in the toolbar panel doesnt work.
public class trygame extends JFrame implements ActionListener {
private JPanel _toolbar = new JPanel();
private Play game;
private Timer _timer;
private int _count = 0;
public trygame(Level lvl) {
super("Elemental Brick Breaker");
_timer = new Timer(1000,this);
_timer.start();
File jarPath=new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
String levelsPath=jarPath.getParentFile().getAbsolutePath();
String path = levelsPath + "\\src\\pics\\gameIcon.png";
ImageIcon icon = new ImageIcon(path);
this.setIconImage(icon.getImage());
setLayout(new BorderLayout());
JButton returnButton = new JButton("Return");
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5,5,5,5);
Dimension d = new Dimension(150,50);
returnButton.setPreferredSize(d);
returnButton.setMinimumSize(d);
_toolbar.add(returnButton,c);
_toolbar.setBackground(Color.black);
add(_toolbar, BorderLayout.SOUTH);
game = new Play(lvl.getBoard());
add(game, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(615,750);
setVisible(true);
setResizable(false);
game.setFocusable(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == _timer) {
_count++;
JLabel jlabel = new JLabel(" Timer: " + Integer.toString(_count));
int Destroyed = game.getDestroyed();
JLabel jlabel2 = new JLabel(" Destroyed: " + Integer.toString(Destroyed));
jlabel.setFont(new Font("Verdana",1,20));
jlabel2.setFont(new Font("Verdana",1,20));
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5,5,5,5);
Dimension d = new Dimension(150,50);
jlabel.setPreferredSize(d);
jlabel2.setMinimumSize(d);
_toolbar.add(jlabel,c);
_toolbar.add(jlabel2,c);
_toolbar.setBorder(new LineBorder(Color.BLACK));
}
}
}
I am making a simple project. It has login window like this
When the user click on button log in - it should "repaint" the window(it should seem to be happened in the same window) and then the window looks like this.
The problem is - I can't "repaint" the window - the only thing I can - it's create a new frame, so there actually are 2 frames totally.
How to make the whole thing in one same frame.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPane(Container pane)
{
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
pane.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
pane.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
JPanel panel = new JPanel();
JLabel label = new JLabel("Your login:");
panel.add(label);
JTextField textField = new JTextField(15);
panel.add(textField);
JButton loginButton = new JButton("log in");
panel.add(loginButton);
JButton exitButton = new JButton("exit");
panel.add(exitButton);
frame.add(panel, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
frame = null;
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
}
Use CardLayout.
This layout allows developers to switch between panels. It works by creating a "deck" panel that'll contain all of panels that'll potentially be displayed:
CardLayout layout = new CardLayout();
JPanel deck = new JPanel();
deck.setLayout(layout);
JPanel firstCard = new JPanel();
JPanel secondCard = new JPanel();
deck.add(firstCard, "first");
deck.add(secondCard, "second");
When you click on a button, that button's ActionListener should call show(Container, String), next(Container) or previous(Container) on the CardLayout to switch which panel is being displayed:
public void actionPerformed(ActionEvent e) {
layout.show(deck, "second");
}
One of the solutions
You can create two panels (one for each view) and add the required components to them. First, you add first panel to the frame (using frame.add(panel1)). If you want to show the second panel in the same window, you can delete first panel (using frame.remove(panel1)) and add the second panel (using frame.add(panel2)). At the end you've to call frame.pack().
This's your code with above solution:
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPanel2()
{
panel2.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
panel2.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
panel2.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
panel1 = new JPanel();
JLabel label = new JLabel("Your login:");
panel1.add(label);
JTextField textField = new JTextField(15);
panel1.add(textField);
JButton loginButton = new JButton("log in");
panel1.add(loginButton);
JButton exitButton = new JButton("exit");
panel1.add(exitButton);
frame.add(panel1, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
panel2 = new JPanel();
addComponentsToPanel2();
frame.remove(panel1);
frame.add(panel2);
//frame.repaint();
frame.pack();
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
private JPanel panel1;
private JPanel panel2;
}
My code below is a working code and I'd like to apologize for my not so short code. I have a problem with my buttons as they execute their action only once. My problem is that when I click the next button I have a validateText() method to check whether the textarea is empty or not. Here comes my problem.. when the panel goes back to the empty textarea the buttons on the left side will not work anymore. But when you close the program and run it again the button will work unless you click the next button with the empty textarea. Is there anyone who can point out my mistake?
package cardlayoutalignment;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class gridbaglayoutdemo {
JFrame Card = new JFrame();
FlowLayout flow = new FlowLayout(FlowLayout.RIGHT,2,2);
Border etch = BorderFactory.createEtchedBorder(Color.white,Color.gray);
Border margin = new EmptyBorder(10,10,10,10);
public static GridBagLayout grid = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
final static boolean shouldFill = true;
JPanel container;
JPanel divider = new JPanel();
JPanel bodypanel = new JPanel();
final JPanel buttonpanel = new JPanel();
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
JPanel panel_3 = new JPanel();
CardLayout cl = new CardLayout();
JTextArea text_2;
JTextArea text_3;
String change = "Finish";
final JButton btnNext;
final JButton btnBack;
int currentCard = 0;
int cardflag = 0;
AbstractAction backAction;
AbstractAction nextAction;
public gridbaglayoutdemo(){
Card.setVisible(true);
Card.setSize(605,333);
Card.setTitle("Tank Delivery");
Card.setResizable(false);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x=(int)((dimension.getWidth() - Card.getWidth())/2);
int y=(int)((dimension.getHeight() - Card.getHeight())/2);
Card.setLocation(x, y);
Card.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
bodypanel.setLayout(new BorderLayout());
divider.setLayout(new BorderLayout());
container = new JPanel(cl);
container.setLayout(cl);
cl.show(container, "1");
panel_1.setLayout(grid);
JLabel label_1 = new JLabel("Enter 1:");
label_1.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,0,0);
panel_1.add(label_1, c);
JComboBox box_1 = new JComboBox();
box_1.setPreferredSize(new Dimension(200,30));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10,10,0,0);
panel_1.add(box_1,c);
JLabel label = new JLabel("");
label.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 1;
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(10,0,0,0);
panel_1.add(label, c);
panel_2.setLayout(grid);
JLabel label_2 = new JLabel("Enter 2:");
label_2.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,0,0);
panel_2.add(label_2,c);
text_2 = new JTextArea();
text_2.setPreferredSize(new Dimension(200,30));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 20;
c.insets = new Insets(10,10,0,0);
panel_2.add(text_2,c);
JLabel label_22 = new JLabel("");
label_22.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 1;
c.gridx = 0;
c.gridy = 30;
c.insets = new Insets(10,0,0,0);
panel_2.add(label_22, c);
panel_3.setLayout(grid);
JLabel label_3 = new JLabel("Enter 3:");
label_3.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,0,0);
panel_3.add(label_3,c);
text_3 = new JTextArea();
text_3.setPreferredSize(new Dimension(200,30));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 20;
c.insets = new Insets(10,10,0,0);
panel_3.add(text_3,c);
JLabel label_33 = new JLabel("");
label_33.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 1;
c.gridx = 0;
c.gridy = 30;
c.insets = new Insets(10,0,0,0);
panel_3.add(label_33, c);
buttonpanel.setLayout(new FlowLayout(SwingConstants.RIGHT));
buttonpanel.setBorder(new EmptyBorder(0,10,0,0));
backAction = new AbstractAction("< Back") {
public void actionPerformed(ActionEvent e) {
currentCard--;
gridbaglayoutdemo.this.evaluateActions();
}
};
nextAction = new AbstractAction("Next >") {
public void actionPerformed(ActionEvent e) {
currentCard++;
gridbaglayoutdemo.this.evaluateActions();
}
};
buttonpanel.setLayout(new FlowLayout(SwingConstants.RIGHT));
buttonpanel.setBorder(new EmptyBorder(0,0,0,0));
btnBack = new JButton("< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.previous(container);
buttonpanel.repaint();
cardflag--;
if (cardflag==0)
{btnBack.setEnabled(false);}
if(cardflag<3)
{btnNext.setText("Next >");}
}
});
btnBack.setEnabled(false);
btnBack.setFont(new Font("Arial", Font.PLAIN, 20));
btnBack.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
btnBack.setPreferredSize(new Dimension(110, 40));
btnBack.setBackground(new Color(224,223,227));
buttonpanel.add(btnBack);
btnNext = new JButton("Next >");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.next(container);
buttonpanel.repaint();
cardflag++;
if(cardflag<3)
{btnBack.setEnabled(true);}
if(cardflag==2)
{btnNext.setText(change);}
if (cardflag==3)
{cl.show(container, "3");
JOptionPane.showMessageDialog(null, "DONE");
Window dialog = SwingUtilities.windowForComponent( btnNext );
dialog.dispose();
cardflag=0;
btnNext.setText("Next >");
}
validateText();
}
});
btnNext.setFont(new Font("Arial", Font.PLAIN, 20));
btnNext.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
btnNext.setPreferredSize(new Dimension(110, 40));
btnNext.setBackground(new Color(224,223,227));
btnNext.setVisible(true);
buttonpanel.add(btnNext);
final JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Window dialog = SwingUtilities.windowForComponent( btnCancel );
dialog.dispose();
}
});
btnCancel.setFont(new Font("Arial", Font.PLAIN, 20));
btnCancel.setFocusable(false);
btnCancel.setFocusTraversalKeysEnabled(false);
btnCancel.setFocusPainted(false);
btnCancel.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
btnCancel.setPreferredSize(new Dimension(110, 40));
btnCancel.setBackground(new Color(224,223,227));
buttonpanel.add(btnCancel);
JPanel numberpanel = new JPanel();
numberpanel.setPreferredSize(new Dimension(221,0));
numberpanel.setBorder(new EmptyBorder(10,0,0,10));
numberpanel.setBorder(BorderFactory.createEtchedBorder(Color.white,Color.gray));
numberpanel.setLayout(flow);
JButton button_7 = new JButton("7");
button_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonaction(e);
}
});
button_7.setActionCommand("7");
button_7.setFont(new Font("Arial", Font.PLAIN, 30));
button_7.setFocusable(false);
button_7.setFocusTraversalKeysEnabled(false);
button_7.setFocusPainted(false);
button_7.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
button_7.setPreferredSize(new Dimension(70, 70));
button_7.setBackground(new Color(224,223,227));
numberpanel.add(button_7);
JButton button_8 = new JButton("8");
button_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonaction(e);
}
});
button_8.setActionCommand("8");
button_8.setFont(new Font("Arial", Font.PLAIN, 30));
button_8.setFocusable(false);
button_8.setFocusTraversalKeysEnabled(false);
button_8.setFocusPainted(false);
button_8.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
button_8.setPreferredSize(new Dimension(70, 70));
button_8.setBackground(new Color(224,223,227));
numberpanel.add(button_8);
JButton button_9 = new JButton("9");
button_9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonaction(e);
}
});
button_9.setActionCommand("9");
button_9.setFont(new Font("Arial", Font.PLAIN, 30));
button_9.setFocusable(false);
button_9.setFocusTraversalKeysEnabled(false);
button_9.setFocusPainted(false);
button_9.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
button_9.setPreferredSize(new Dimension(70, 70));
button_9.setBackground(new Color(224,223,227));
numberpanel.add(button_9);
Card.add(bodypanel);
bodypanel.add(divider, BorderLayout.WEST);
divider.add(container, BorderLayout.NORTH);
container.add(panel_1, "1");
container.add(panel_2, "2");
container.add(panel_3, "3");
//container.add(panel_4, "4");
//container.add(p5.panel_5, "5");
//container.add(p6.panel_6, "6");
divider.add(buttonpanel, BorderLayout.SOUTH);
bodypanel.add(numberpanel, BorderLayout.EAST);
}
private void evaluateActions() {
((javax.swing.Action) backAction).setEnabled(currentCard > 0);
((javax.swing.Action) nextAction).setEnabled(currentCard < container.getComponentCount() - 1);
}
private void buttonaction(ActionEvent e){
try{
if(cardflag==1)
{text_2.append("" + e.getActionCommand());}
if(cardflag==2)
{text_3.append("" + e.getActionCommand());}
}catch(Exception IOe){}
}
private void validateText(){
if(cardflag==2)
{String text = text_2.getText();
if (text.isEmpty()==true)
{JOptionPane.showMessageDialog(null, "Text 2 is empty!");
cl.show(container, "2");
}
}
}
public static void main(String[] args){
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new gridbaglayoutdemo();
}
});
}
}
I don't know what are you doing but I just noticed one thing with the state of cardflag.
When the text field is empty and next button is clicked cardflag = 2 and now button is clicked then below action listener is called.
private void buttonaction(ActionEvent e) {
try {
if (cardflag == 1) {
text_2.append("" + e.getActionCommand());
}
if (cardflag == 2) {
text_3.append("" + e.getActionCommand());
^^^
//This should be text_2
}
} catch (Exception IOe) {
}
}
Well I figure it out now. Thanks to user3218114. Since I'm clicking the next button my cardflag is still adding up and because of that I needed to add -1 in my cardflag so that the number of my panel will stay the same and that I won't be needing any additional duplication of my code.
private void validateText(){
if(cardflag==2)
{String text = text_2.getText();
if (text.isEmpty()==true)
{JOptionPane.showMessageDialog(null, "Text 2 is empty!");
cl.show(container, "2");
cardflag--;
}
}
}
I wanted to ask that if an exception occurs, then display a certain String in the textfield. When I try using a try, catch IOException, it gives me an error that cannot have a catch in the same body as a try. This should probably be done in the action performed method.
GUI:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
try{
if (text.equals("="))
{
doMath math = new doMath();
b = b.replaceAll("\\s+", " ");
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
b+=" ";
display.setText(b);
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else if (text.equals("+") || text.equals("-") || text.equals("*") || text.equals("/"))
{
b += (" "+(text)+ " ");
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
}
catch(IOException o)
{display.setText(b);}
}
}
When I try using a try, catch IOException, it gives me an error that
cannot have a catch in the same body as a try
The error is self-explanatory. The following code is illegal:
try{
catch(Exception ex){
}
}
You want this:
try{
//stuff i need to do
} //close the try
catch(IOException ioex)
{
//log and recover
}
=UPDATE
Based on the code block below (the same that OP is talking about in case it is changed later) The actual error message that is being displayed is this:
Unreachable catch block for IOException. This exception is never
thrown from the try statement body GUI.java
The reason this occurs is that there is nothing that generates an IOException in your code, the only exception you can define without an explicit throw from one of your functions is the top level Exception.
public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display = new JTextField(20);
doMath math = new doMath();
String s = "";
String b= "";
//int counter;
JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;
JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
JButton Space;
public GUI()
{
super("Calculator");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout (2,1));
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 4));
buttonPanel.add(Num1 = new JButton("1"));
buttonPanel.add(Num2 = new JButton("2"));
buttonPanel.add(Num3 = new JButton("3"));
buttonPanel.add(Num4 = new JButton("4"));
buttonPanel.add(Num5 = new JButton("5"));
buttonPanel.add(Num6 = new JButton("6"));
buttonPanel.add(Num7 = new JButton("7"));
buttonPanel.add(Num8 = new JButton("8"));
buttonPanel.add(Num9 = new JButton("9"));
buttonPanel.add(Num0 = new JButton("0"));
buttonPanel.add(Clr = new JButton("C"));
buttonPanel.add(Eq = new JButton("="));
buttonPanel.add(Add = new JButton("+"));
buttonPanel.add(Sub = new JButton("-"));
buttonPanel.add(Mult = new JButton("*"));
buttonPanel.add(Div = new JButton("/"));
buttonPanel.add(Space = new JButton("Space"));
Num1.addActionListener(this);
Num2.addActionListener(this);
Num3.addActionListener(this);
Num4.addActionListener(this);
Num5.addActionListener(this);
Num6.addActionListener(this);
Num7.addActionListener(this);
Num8.addActionListener(this);
Num9.addActionListener(this);
Num0.addActionListener(this);
Clr.addActionListener(this);
Eq.addActionListener(this);
Add.addActionListener(this);
Sub.addActionListener(this);
Mult.addActionListener(this);
Div.addActionListener(this);
Space.addActionListener(this);
topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(display);
add(mainPanel);
mainPanel.add(topPanel, BorderLayout.NORTH);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
String text = source.getText();
try{
if (text.equals("="))
{
doMath math = new doMath();
b = b.replaceAll("\\s+", " ");
int result = math.doMath1(b);
String answer = ""+result;
display.setText(answer);
}
else if(text.equals("Space"))
{
b+=" ";
display.setText(b);
}
else if (text.equals("C"))
{
b = "";
display.setText(b);
}
else if (text.equals("+") || text.equals("-") || text.equals("*") || text.equals("/"))
{
b += (" "+(text)+ " ");
display.setText(b);
}
else
{
b += (text);
display.setText(b);
}
}
catch(IOException o)
{display.setText(b);}
}
}