What am I doing wrong with this Java JPanel/JFrame/JButton? - java

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

Related

Java GUI Real Time Word Counter

I was checking out the example projects that people do when starting to learn Java and GUI, I was faced with a bunch of word/letter count programs such as:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Counter extends JFrame implements ActionListener{
JLabel lb1,lb2;
JTextArea ta;
JButton b;
JButton pad,text;
Counter(){
super("Char Word Count Tool - JTP");
lb1=new JLabel("Characters: ");
lb1.setBounds(50,50,100,20);
lb2=new JLabel("Words: ");
lb2.setBounds(50,80,100,20);
ta=new JTextArea();
ta.setBounds(50,110,300,200);
b=new JButton("Count");
b.setBounds(50,320, 80,30);//x,y,w,h
b.addActionListener(this);
add(lb1);add(lb2);add(ta);add(b);
setSize(400,400);
setLayout(null);//using no layout manager
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b){
String text=ta.getText();
lb1.setText("Characters: "+text.length());
String words[]=text.split("\\s");
lb2.setText("Words: "+words.length);}
}
public static void main(String[] args) {
new Counter();
}}
But I don't want to count words whenever I click the button but in real-time so the values update each frame. Do I need to use multi-threading for this or it can be achieved without it?
You need to use a DocumentListener on the JTextArea instead of an ActionListener on a JButton.
void test() {
JTextArea textArea = new JTextArea();
textArea.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
recalculateWords();;
}
#Override
public void removeUpdate(DocumentEvent e) {
recalculateWords();
}
#Override
public void changedUpdate(DocumentEvent e) {
recalculateWords();
}
});
}
void recalculateWords() {
//Use your code from actionPerfomed here.
}

Two labels overlap each other when using the Radio Button Listener

I made a simple program where there are two radio buttons each with an action listener.
After pressing first button, a label is printed and the same thing happens with the other.
The problem is that both the labels overlap after pressing first and second button.
Edit-The previous label must be removed and then new label must be on the screen.
ex-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ckbxdm{
JFrame frame;
JRadioButton r1,r2;
ButtonGroup grp;
JLabel l1,l2;
void box(){
frame=new JFrame("Hello");
r1=new JRadioButton("Login");
r2=new JRadioButton("Signup");
grp=new ButtonGroup();
grp.add(r1);
grp.add(r2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.getContentPane().add(r1);
frame.getContentPane().add(r2);
r1.setBounds(100,120,100,20);
r2.setBounds(200,120,100,20);
frame.setBounds(100,100,500,500);
frame.setVisible(true);
r1.addActionListener(new listener1());
r2.addActionListener(new listener2());
}
class listener1 implements ActionListener{
public void actionPerformed(ActionEvent ae){
frame.getContentPane().repaint();
frame.getContentPane().revalidate();
l1=new JLabel("Login area");
frame.getContentPane().add(l1);
l1.setBounds(100,200,100,20);
}
}
class listener2 implements ActionListener{
public void actionPerformed(ActionEvent ae){
frame.getContentPane().repaint();
frame.getContentPane().revalidate();
l2=new JLabel("Signup area");
frame.getContentPane().add(l2);
l2.setBounds(100,200,100,20);
}
}
public void itemStateChanged(ItemEvent ie){
frame.repaint();
}
}
public class CheckboxDemo{
public static void main(String args[]){
ckbxdm obj=new ckbxdm();
obj.box();
}
}
In addition to the answer provided above, if you want to hide the other label, you can set its visibility to false and repaint the parent component. You can learn more from here. Note that calling the revalidate method here is unnecessary since you are not removing any component from the hierarchy.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ckbxdm{
JFrame frame;
JRadioButton r1,r2;
ButtonGroup grp;
JLabel l1,l2;
void box(){
frame=new JFrame("Hello");
r1=new JRadioButton("Login");
r2=new JRadioButton("Signup");
grp=new ButtonGroup();
grp.add(r1);
grp.add(r2);
l1=new JLabel("Login area");
l1.setBounds(100,200,100,20);
l1.setVisible(false);
frame.getContentPane().add(l1);
l2=new JLabel("Signup area");
l2.setBounds(100,200,100,20);
l2.setVisible(false);
frame.getContentPane().add(l2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.getContentPane().add(r1);
frame.getContentPane().add(r2);
r1.setBounds(100,120,100,20);
r2.setBounds(200,120,100,20);
frame.setBounds(100,100,500,500);
frame.setVisible(true);
r1.addActionListener(new listener1());
r2.addActionListener(new listener2());
}
class listener1 implements ActionListener{
public void actionPerformed(ActionEvent ae){
l2.setVisible(false);
l1.setVisible(true);
frame.getContentPane().repaint();
}
}
class listener2 implements ActionListener{
public void actionPerformed(ActionEvent ae){
l1.setVisible(false);
l2.setVisible(true);
frame.getContentPane().repaint();
}
}
public void itemStateChanged(ItemEvent ie){
frame.repaint();
}
}
public class CheckboxDemo{
public static void main(String args[]){
ckbxdm obj=new ckbxdm();
obj.box();
}
}
try to change ur "sign up position" in X-Ycooridantes direction, let say change following line of code l2.setBounds(100,200,100,20);
to
l2.setBounds(200,200,100,20);
and the same way for l1 change it to l1.setBounds(50,200,100,20);
, it will definitely work

Why won't my .isSelected() method work?

Well what i'm trying to do is change the text of the JRadioButton's when they're selected, i got them to change the color. I know I can do it by putting the code to change the text inside the dedicated event handling method specific to each button, but how do I do it so that I use A DIFFERENT event handling method that just changes the buttons? I already created one but it doesn't work, here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LessonTwenty extends JFrame implements ActionListener{
JRadioButton b1,b2;
JTextArea t1;
JScrollPane s1;
JPanel jp = new JPanel();
public LessonTwenty()
{
b1= new JRadioButton("green");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jp.setBackground(Color.GREEN);
}
});
b2= new JRadioButton("red");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jp.setBackground(Color.RED);
}
});
//Method to change the text of the JRadion Buttons, what i'm trying to make work
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(b1.isSelected()){
b1.setText("Welcome");
}
else if(b2.isSelected()){
b2.setText("Hello");
}
}
};
jp.add(b1);
jp.add(b2);
this.add(jp);
setTitle("Card");
setSize(700,500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String [ ] args){
new LessonTwenty();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
if i understand you right, you want do do something like this:
//Method to change the text of the JRadion Buttons, what i'm trying to make work
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(b1.isSelected()){
b1.setText("Welcome");
}
else if(b2.isSelected()){
b2.setText("Hello");
}
}
};
b1= new JRadioButton("green");
b1.addActionListener(al);
b2= new JRadioButton("red");
b2.addActionListener(al);
ie. you define one ActionListener which you use in all your objects.
The anonymous object you define in your original code does absolutely nothing, it just creates an ActionListener which nobody can ever access, since it is not assigned to any Button.
Maybe this could help
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == b1){
b1.setText("Welcome");
} else if(e.getSource() == b2){
b2.setText("Hello");
}
}
};

Action Event error

Why doesn't my program work? I want to use the borderlayout, and each button to do different thing. I did a lot of research but I am still getting errors, and just am lost.
thank you for your help in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Guard10 {
public static void main(String[] args)
{
new Guard10()
}
public Guard10()
{
JFrame myFrame = new JFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setTitle("Show BorderLayout");
myFrame.setSize(300, 200);
myFrame.setLocationRelativeTo(null);
// Add buttons to the frame
JButton labelButton = new JButton ("one");
labelButton.addActionListener(new LabelListener()
{
#Override
public void actionPerformed (ActionEvent event)
{
System.out.println ("You clicked it!");
}
});
////////////
JButton button2 = new JButton ("two");
button2.addActionListener(new Button2Listener()
{
#Override
public void actionPerformed (ActionEvent event)
{
System.out.println ("YAY!");
}
}
myFrame.add(labelButton,BorderLayout.SOUTH);
myFrame.add(button2,BorderLayout.NORTH)
myFrame.setVisible(true);
}
}
You simply forgot some semicolons and brackets. The corrected code below is working. Also, use a standard ActionListener if you do nothing but overriding actionPerformed.
public class Guard10 {
public static void main(String[] args)
{
new Guard10();
}
public Guard10()
{
JFrame myFrame = new JFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setTitle("Show BorderLayout");
myFrame.setSize(300, 200);
myFrame.setLocationRelativeTo(null);
// Add buttons to the frame
JButton labelButton = new JButton ("one");
labelButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent event)
{
System.out.println ("You clicked it!");
}
});
////////////
JButton button2 = new JButton ("two");
button2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed (ActionEvent event)
{
System.out.println ("YAY!");
}
});
myFrame.add(labelButton,BorderLayout.SOUTH);
myFrame.add(button2,BorderLayout.NORTH);
myFrame.setVisible(true);
}
}
If you try to compile you get all the errors in the stacktrace. Just look at the lines to find out what is wrong. I'd also advice you to use an IDE like Eclipse or IntelliJ Idea, they will mark syntax errors before compiling while you type the code.

Cancel button never gets enabled

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.lang.Thread;
public class Lthread extends JPanel{
private JTextField acctTF;
private JTextField pinTF;
private JButton cancelB;
private JLabel balanceL;
private JButton searchB;
public Lthread() {
buildGUI();
hookupEvents();
}
private void buildGUI() {
JLabel acctL=new JLabel("Account Number:");
JLabel pinL=new JLabel("PIN:");
acctTF=new JTextField(12);
pinTF=new JTextField(4);
JPanel dataEntryP=new JPanel();
dataEntryP.setLayout(new FlowLayout(FlowLayout.CENTER));
dataEntryP.add(acctL);
dataEntryP.add(acctTF);
dataEntryP.add(pinL);
dataEntryP.add(pinTF);
searchB=new JButton("Search");
cancelB=new JButton("Cancel Search");
cancelB.setEnabled(false);
JPanel innerButtonP=new JPanel();
innerButtonP.setLayout(new GridLayout(1,-1,5,5));
innerButtonP.add(searchB);
innerButtonP.add(cancelB);
JPanel buttonP=new JPanel();
buttonP.setLayout(new FlowLayout(FlowLayout.CENTER));
buttonP.add(innerButtonP);
JLabel balancePrefixL=new JLabel("Account Balance: ");
balanceL=new JLabel("BALANCE UNKNOWN");
JPanel balanceP=new JPanel();
balanceP.setLayout(new FlowLayout(FlowLayout.CENTER));
balanceP.add(balanceL);
JPanel northP=new JPanel();
northP.setLayout(new GridLayout(-1,1,5,5));
northP.add(dataEntryP);
northP.add(buttonP);
northP.add(balanceP);
setLayout(new BorderLayout());
add(northP,BorderLayout.NORTH);
}
private void hookupEvents() {
searchB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
search(ae);
}
});
cancelB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cancelSearch(ae);
}
});
}
private void search(ActionEvent ae) {
searchB.setEnabled(false);
cancelB.setEnabled(true);
balanceL.setText("SEARCHING...");
String acct=acctTF.getText();
String pin=pinTF.getText();
String bal=lookupBalance(acct,pin);
setBalance(bal);
}
private String lookupBalance(String acct,String pin) {
try {
Thread.sleep(5000);
return "1,234.56";
} catch(Exception exc) {
return "search cancelled";
}
}
private void setBalance(String newBalance) {
balanceL.setText(newBalance);
cancelB.setEnabled(false);
searchB.setEnabled(true);
}
private void cancelSearch(ActionEvent ae) {
System.out.println("in cancelSearch");
}
public static void main(String args[]) {
Lthread Lt=new Lthread();
JFrame f=new JFrame("Balance Lookup-Can't cancel");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setContentPane(Lt);
f.setSize(400,150);
f.setVisible(true);
}
}
As soon as we click search,cancel should get enabled,but it does not get enabled, why?
Another thing is label balanceL should display SEARCHING. When search is clicked but that is also not displayed. Why?
You're doing all the work (well, sleeping) in the UI thread. That's stopping all the rest of the UI from updating, processing events etc.
You should offload your work (the searching/sleeping) to a background thread, using SwingWorker to marshall any UI calls back to the UI thread. (You can't touch UI components from a non-UI thread.)
A search for "swing threads" gives loads of hits for tutorials etc, if you want more information. In particular, you probably want to read the Java Tutorial trail on threading in Swing.
because the eventdispatcher thread is blocked in the search() function. it should never be blocked. use SwingUtilities.invokeLater().
for your problem change search method to
private void search(ActionEvent ae) {
searchB.setEnabled(false);
cancelB.setEnabled(true);
balanceL.setText("SEARCHING...");
final String acct=acctTF.getText();
final String pin=pinTF.getText();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
String bal=lookupBalance(acct,pin);
setBalance(bal);
}
});
}

Categories

Resources