What am I doing wrong with this Java JPanel/JFrame/JButton? This is my program and right now I've been trying to be able to repaint it, but it won't work. Please help! I am a beginner with JPanel
and JFrame
. I'm only adding this sentence to allow it to post.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Clicks implements MouseListener
{
private static int clicks, clickersInt, clickersCost;
private static JButton clickersB, click;
private static JLabel clickersL, clicksL;
private static JPanel panel;
public static void main(String[] args)
{
JFrame clicksFrame=new JFrame ("Clicks");
clicksFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
clicks=0;
panel=new JPanel(new GridBagLayout());
click=new JButton("Click Me!");
clickersB=new JButton("Cost: 10");
clickersL=new JLabel("Clickers: "+Integer.toString(clickersInt));
clicksL=new JLabel("Clicks: "+Integer.toString(clicks));
click.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
clicks++;
clicksFrame.remove(panel);
clicksFrame.add(panel);
panel.validate();
panel.repaint();
}
});
clickersB.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(clicks>=clickersCost)
{
clickersInt++;
clicks-=clickersCost;
clickersCost*=2;
}
}
});
panel.add(click);
panel.add(clicksL);
panel.add(clickersL);
panel.add(clickersB);
clicksFrame.add(panel);
clicksFrame.setBackground(Color.CYAN);
clicksFrame.setVisible(true);
}
}
So, based on this little snippet...
click=new JButton("Click Me!");
clickersB=new JButton("Cost: 10");
clickersL=new JLabel("Clickers: "+Integer.toString(clickersInt));
clicksL=new JLabel("Clicks: "+Integer.toString(clicks));
click.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
clicks++;
clicksFrame.remove(panel);
clicksFrame.add(panel);
panel.validate();
panel.repaint();
}
});
I would suggest that what you really want to do is...
click.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
clicks++;
clicksL.setText("Clicks: "+Integer.toString(clicks));
}
});
You seem to be of the illusion that changing a variable will some how change another variable which is just a string of characters. As you've discovered, that's not how this works
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.