So I would consider myself to be a beginner programmer, but something as simple as getting a button to do something once clicked is fairly easy, right? I'll paste the code first then ask the question.
/*
* Created By Vili Milner
*/
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class MainView extends JFrame implements ActionListener {
private long cookieBalance = 0;
private String stringBalance = Long.toString(cookieBalance);
private JLabel balance = new JLabel(stringBalance);
public MainView(){
display();
}
public void display(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setTitle("Cookie Clicker");
setSize(300, 200);
GridLayout gridOneTwo = new GridLayout(1, 2);
GridLayout gridOneTen = new GridLayout(1, 10);
GridLayout gridOneThree = new GridLayout(1, 3);
Panel mainPanel = new Panel();
mainPanel.setLayout(gridOneTwo);
Panel upgradePanel = new Panel();
upgradePanel.setLayout(new BoxLayout(upgradePanel, BoxLayout.Y_AXIS));
JButton upgradeButtonOne = new JButton("UPGRADE 1");
JButton upgradeButtonTwo = new JButton("UPGRADE 2");
JButton upgradeButtonThree = new JButton("UPGRADE 3");
JButton upgradeButtonFour = new JButton("UPGRADE 4");
JButton upgradeButtonFive = new JButton("UPGRADE 5");
upgradePanel.add(upgradeButtonOne);
upgradePanel.add(upgradeButtonTwo);
upgradePanel.add(upgradeButtonThree);
upgradePanel.add(upgradeButtonFour);
upgradePanel.add(upgradeButtonFive);
mainPanel.add(upgradePanel);
Panel displayPanel = new Panel();
displayPanel.setLayout(new BoxLayout(displayPanel, BoxLayout.Y_AXIS));
displayPanel.add(balance);
mainPanel.add(displayPanel);
Panel cookiePanel = new Panel();
cookiePanel.setLayout(gridOneThree);
JButton cookieButton = new JButton("COOKIE");
cookieButton.setActionCommand("cookie");
cookieButton.addActionListener(this);
cookiePanel.add(cookieButton);
JLabel emptyLabelOne = new JLabel(" ");
JLabel emptyLabelTwo = new JLabel(" ");
displayPanel.add(cookiePanel);
displayPanel.add(emptyLabelOne);
displayPanel.add(emptyLabelTwo);
add(mainPanel);
}
#Override
public void actionPerformed(ActionEvent click) {
String action = click.getActionCommand();
if (action.equals("cookie")){
cookieBalance++;
}
}
}
Continuing, I can get the button to do anything except make the display label go up by 1. In other words, the button itself does work, but for some reason the label isn't changing. I believe this is a fairly simple mistake, I just can't seem to find it. So my question is: why is the label not changing once I increment the value?
Repeating what has been said in the comments, The JLabel balance is not being updated with the value, It simply reflects the value of what cookieBalance originally was.
Rather than simply incrementing the variable, you should call:
#Override
public void actionPerformed(ActionEvent click) {
String action = click.getActionCommand();
if (action.equals("cookie")){
balance.setText(String.valueOf(++cookieBalance));
}
}
Related
I have to display a map containing two columns and the size is dynamic. I am currently displaying it in a panel, but the problem is I cannot start each row of the map in the new line, rather it depends on the frame size of the display. Here is the full code:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.awt.BorderLayout;
import java.awt.Image;
public class P05 {
private JLabel label;
private JLabel label1;
private JLabel label3;
private JTextField tf;
private JPanel panel;
public P05() {
JFrame frame = new JFrame("Search result and score");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
JPanel buttonPane = new JPanel();
label = new JLabel("Search Result: ");
label1 = new JLabel();
label3 = new JLabel("Score: ");
tf=new JTextField(10);
tf.setBounds(10,10, 150,20);
JButton button = new JButton("Search");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
label1.setText("The input query is " + text);
panel.removeAll();
panel.add(label);
panel.add(label3);
int i = 0;
Map < String, Double> map = new HashMap < String, Double> ();
map.put("Jennifer Anniston", 31.0);
map.put("brad_pit", 29.0);
map.put("Angelina Jolie", 30.0);
map.put("badley", 21.0);
map.put("Leonardo Decaprio", 43.0);
map.put("Kate Winslet", 41.0);
map.put("Julia Roberts", 40.0);
map.put("Emma Watson", 34.0);
map.put("Mayim Bialik", 28.0);
map.put("Cobie Smulders", 28.0);
for(String item:map.keySet()) {
JTextField t1[] = new JTextField[12];
t1[i] = new JTextField(20);
t1[i].setText(item );
panel.add(t1[i]);
JTextField t2[] = new JTextField[12];
t2[i] = new JTextField(5);
t2[i].setText(Double.toString(map.get(item)));
panel.add(t2[i]);
i++;
}
panel.add(label1);
panel.revalidate();
}
});
buttonPane.add(tf);
buttonPane.add(button);
panel = new JPanel();
frame.add(buttonPane, BorderLayout.NORTH);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new P05();
}
The output looks like somewhat this:
The quick and dirty solution right now is for me to set the frame size of lower width and it will come in a new line, but in that case, if the text field contains a value with many characters it will not show the whole text. So need a solution to add a new line after each row.
So i have three panels that i have three different buttons for to change them each to their respective colors. I need to add a fourth button that will return all three panels to their original default light gray color. I add this "reset" button and it only changes the first panel back. What am i doing wrong?
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PanelDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
private JPanel redPanel;
private JPanel whitePanel;
private JPanel bluePanel;
public static void main(String[] args)
{
PanelDemo gui = new PanelDemo();
gui.setVisible(true);
}
public PanelDemo()
{
super("Panel Demonstration");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel biggerPanel = new JPanel();
biggerPanel.setLayout(new GridLayout(1, 3));
redPanel = new JPanel();
redPanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(redPanel);
whitePanel = new JPanel();
whitePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(whitePanel);
bluePanel = new JPanel();
bluePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(bluePanel);
add(biggerPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.LIGHT_GRAY);
buttonPanel.setLayout(new FlowLayout());
JButton redButton = new JButton("Red");
redButton.setBackground(Color.RED);
redButton.addActionListener(this);
buttonPanel.add(redButton);
JButton whiteButton = new JButton("White");
whiteButton.setBackground(Color.WHITE);
whiteButton.addActionListener(this);
buttonPanel.add(whiteButton);
JButton blueButton = new JButton("Blue");
blueButton.setBackground(Color.BLUE);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
JButton resetButton = new JButton("Reset");
resetButton.setBackground(Color.LIGHT_GRAY);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
add(buttonPanel, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if (buttonString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else if (buttonString.equals("Reset"))
redPanel.setBackground(Color.LIGHT_GRAY);
else if (buttonString.equals("Reset"))
bluePanel.setBackground(Color.LIGHT_GRAY);
else if (buttonString.equals("Reset"))
whitePanel.setBackground(Color.LIGHT_GRAY);
else
System.out.println("Unexpected error.");
}
}
Here was your problem. You had if else's on each panel for the reset. Compare the code below to what you have. It was just a simple logic issue.
public void actionPerformed(ActionEvent e) {
String buttonString = e.getActionCommand();
if (buttonString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else if (buttonString.equals("Reset")) {
redPanel.setBackground(Color.LIGHT_GRAY);
bluePanel.setBackground(Color.LIGHT_GRAY);
whitePanel.setBackground(Color.LIGHT_GRAY);
}
else
System.out.println("Unexpected error.");
And a couple of suggestions.
Don't extend JFrame. Just use an instance of it. It's better technique.
Put the following as the last statement in your constructor. It will center the panel on your screen.
setLocationRelativeTo(null);
// or when using a frame instance.
frame.setLocationRelativeTo(null);
I am simply making a user interface and all i want it to do after the button is pressed is display thanks... I am pretty new to this but from what i see there are no errors? I have tried playing around with the set visible and to no avail...Any help is great thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class GuiApp1 {
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Pizza Toppings");
panel.setBorder(border);
JLabel label1 = new JLabel("Enter name below:");
panel.add(label1);
JTextField field = new JTextField(20);
panel.add(field);
JCheckBox check = new JCheckBox("Car0");
panel.add(check);
check = new JCheckBox("Car1");
panel.add(check);
check = new JCheckBox("Car2");
panel.add(check);
check = new JCheckBox("Car3");
panel.add(check);
check = new JCheckBox("Car4");
panel.add(check);
JButton button = new JButton("Submit");
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
listPanel.add(listLbl);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
}
});
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The reason for the vegetables panel not appearing is simple: Xou never add ist to the contentPane.
For the code to function properly you need to add/remove the panels in the ActionListener of the button:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
if (listPanel.isVisible()) {
contentPane.remove(panel); // Vegetables are visible, so remove the Cars
contentPane.add(listPanel, BorderLayout.CENTER); // And add the Vegetables
} else {
contentPane.remove(listPanel); // Vice versa
contentPane.add(panel, BorderLayout.CENTER);
}
}
});
Then, you need to move the ActionListener below the contentPane declaration and make it final.
Also you should consider putting the different checkboxes is different variables, so you can read the state of them. If you don't want to have so many variables hanging you could put them into an array.
JCheckBox[] checks = new JCheckbox[5];
checks[0] = new JCheckBox("Car0");
panel.add(checks[0]);
...
I'm starting my adventure with programming and I've got one problem. I try make a simple calculator using awt. I can't go further because I don't know, how to change one variable - textField initialized in MainFrame. I want to change it in actionPerformed. Here's my code and I'll be grateful if You'll give me some guidance. Thanks!
package starter;
import java.awt.EventQueue;
public class Starter {
public Starter () {
EventQueue.invokeLater(new Runnable (){
#Override
public void run () {
new MainFrame();
System.out.println();
}
});
}
public static void main(String[] args) {
new Starter();
}
}
MainFrame
package starter;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainFrame extends JFrame {
private JTextField textField = new JTextField();
DigitActionListener digitPressed = new DigitActionListener();
public MainFrame() {
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(true);
setSize(350, 400);
setLayout (new GridLayout (6, 4, 3, 3));
JButton buttonClear = new JButton("Clear"); buttonClear.addActionListener(digitPressed);
JButton button0 = new JButton ("0"); button0.addActionListener(digitPressed);
JButton button1 = new JButton ("1"); button1.addActionListener(digitPressed);
JButton button2 = new JButton ("2"); button2.addActionListener(digitPressed);
JButton button3 = new JButton ("3"); button3.addActionListener(digitPressed);
JButton button4 = new JButton ("4"); button4.addActionListener(digitPressed);
JButton button5 = new JButton ("5"); button5.addActionListener(digitPressed);
JButton button6 = new JButton ("6"); button6.addActionListener(digitPressed);
JButton button7 = new JButton ("7"); button7.addActionListener(digitPressed);
JButton button8 = new JButton ("8"); button8.addActionListener(digitPressed);
JButton button9 = new JButton ("9"); button9.addActionListener(digitPressed);
JButton multiplicationButton = new JButton ("*"); multiplicationButton.addActionListener(digitPressed);
JButton divisionButton = new JButton ("/"); divisionButton.addActionListener(digitPressed);
JButton additionButton = new JButton ("+"); additionButton.addActionListener(digitPressed);
JButton substructionButton = new JButton ("-"); substructionButton.addActionListener(digitPressed);
JButton equalsButton = new JButton ("="); equalsButton.addActionListener(digitPressed);
JButton commaButton = new JButton ("."); commaButton.addActionListener(digitPressed);
add (buttonClear);
add (new JLabel (""));
add (new JLabel (""));
JPanel textPanel = new JPanel();
textPanel.setLayout(new BorderLayout());
textPanel.add(textField, BorderLayout.CENTER);
this.add(textPanel);
add(button7);
add(button8);
add(button9);
add(divisionButton);
add(button4);
add(button5);
add(button6);
add(multiplicationButton);
add(button1);
add(button2);
add(button3);
add(additionButton);
add(commaButton);
add(button0);
add(equalsButton);
add(substructionButton);
}
public JTextField getTextField() {
return textField;
}
public void setTextField(String text) {
textField.setText(text);
}
}
DigitActionListener
package starter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DigitActionListener implements ActionListener {
int size = 0;
char[] tab = new char[size];
public void pain (Graphics g, String s){
g.drawString(s, 20, 10);
}
#Override
public void actionPerformed(ActionEvent e) {
//Object source = e.getSource();
String command = e.getActionCommand();
if ("button0".equals(command)) {
tab[size] = 0;
String eq = String.valueOf(tab[size]);
MainFrame mainFrame = new MainFrame();
mainFrame.setTextField(eq);
size++;
}
}
}
Your problem is here:
if ("button0".equals(command)) {
tab[size] = 0;
String eq = String.valueOf(tab[size]);
MainFrame mainFrame = new MainFrame();
mainFrame.setTextField(eq);
size++;
}
You're creating a new MainFrame object and changing its state, but understand that this will have no effect on the completely distinct displayed MainFrame object and will not change its state whatsoever (will not change what is displayed within its JTextField). There are a variety of possible solutions, but it all boils down to understanding what Java references are, and calling methods on the appropriate reference, here the appropriate MainFrame object. A simple solution could be for to pass the MainFrame object into your listener via a listener constructor, and then call the methods on this reference.
For example:
class DigitActionListener implements ActionListener {
private MainFrame mainFrame;
int size = 0;
char[] tab = new char[size];
public DigitActionListener(MainFrame mainFrame) {
this.mainFrame = mainFrame;
}
public void pain (Graphics g, String s){
g.drawString(s, 20, 10);
}
#Override
public void actionPerformed(ActionEvent e) {
//Object source = e.getSource();
String command = e.getActionCommand();
if ("button0".equals(command)) {
tab[size] = 0;
String eq = String.valueOf(tab[size]);
// MainFrame mainFrame = new MainFrame(); // **** no, don't do this
mainFrame.setTextField(eq);
size++;
}
}
}
and then within MainFrame itself, do something like:
// pass *this* or the current MainFrame instance, into the DigitalActionListener
DigitActionListener digitPressed = new DigitActionListener(this);
Other issues -- learn to use and then use arrays and ArrayLists, as this can help you simplify your code, and thus make program improvement and debugging much easier.
im having a little trouble with this GUI. Im new to making GUI's so if its something basic im sorry for asking. I cant seem to find the answer to my problem anywhere on google.
The problem im having is when i click on any of the buttons i get an error when any one of the textfields are left empty. here is my code so far
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
public class MainGUI extends JFrame implements ActionListener{
ArrayList<Object> list;
JTextField name, surname, age, height, weight;
JComboBox<String> sportList, gender;
JButton btnSave;
JButton btnExit;
JButton btnclrtxt;
/**
* #param args
*/
public MainGUI() {
super("Adding members");
this.setLayout(new BorderLayout());
JPanel panel = new JPanel(new FlowLayout());
name = new JTextField(10);
surname = new JTextField(10);
age = new JTextField(10);
height = new JTextField(5);
weight = new JTextField(10);
gender = new JComboBox<String>(new String[] { "Male", "Female" });
sportList = new JComboBox<String>(new String[] { "Football",
"HandBall", "BasketBall", "Rugby", "Hockey", "Tennis" });
panel.add(new JLabel("Name:"));
panel.add(name);
panel.add(new JLabel("Surname:"));
panel.add(surname);
panel.add(new JLabel("Age:"));
panel.add(age);
panel.add(new JLabel("Gender:"));
panel.add(gender);
panel.add(new JLabel("Height:"));
panel.add(height);
panel.add(new JLabel("Weight:"));
panel.add(weight);
panel.add(new JLabel("Sport Speciality:"));
panel.add(sportList);
btnSave = new JButton("Save member");
panel.add(btnSave);
btnSave.addActionListener(this);
btnclrtxt = new JButton("Clear text");
panel.add(btnclrtxt);
btnclrtxt.addActionListener(this);
btnExit = new JButton("Exit");
panel.add(btnExit);
btnExit.addActionListener(this);
this.pack();
this.add(panel);
this.setSize(400, 300);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new MainGUI();
}
public void actionPerformed(ActionEvent e) {
String namestr = name.getText().toLowerCase();
String surnameStr = surname.getText().toLowerCase();
int ageNum = Integer.parseInt(age.getText().toLowerCase());
double heightNum = Double.parseDouble(height.getText().toLowerCase());
double weightNum = Double.parseDouble(weight.getText().toLowerCase());
String sportsStr = sportList.getSelectedItem().toString();
String genderStr = gender.getSelectedItem().toString();
if(e.getSource()==btnSave) {
list = new ArrayList<Object>();
list.add("Name is "+namestr);
list.add("Surname is "+surnameStr);
list.add("Age is "+ageNum);
list.add("Height is "+heightNum);
list.add("Weight is "+weightNum);
list.add("Sport "+sportsStr);
list.add("Gender "+genderStr);
FileRead.writeFile(list);
System.out.println("Done!");
}
if(e.getSource()==btnExit) {
dispose();
System.exit(0);
}
if(e.getSource()==btnclrtxt) {
name.setText("");
surname.setText("");
age.setText("");
height.setText("");
weight.setText("");
}
}
}
wotking, but you don't test if JTextField.isEmpty, then parsing throws correct exception, instead of that to use
JFormattedTextField with NumberFormatter, then default valur is 0 (zero)
JSpinner with SpinnerNumberModel, then default valur is 0 (zero)
add DocumentFilter to plain JTextField with filtering non_numeric chars, but still required to test if JTextField.isEmpty()
I suspect this is because of these fields:
int ageNum = Integer.parseInt(age.getText().toLowerCase());
double heightNum = Double.parseDouble(height.getText().toLowerCase());
double weightNum = Double.parseDouble(weight.getText().toLowerCase());
The parsing will throw an exception if any of these fields is empty, or contains an incorrect value; make sure you check they contain a (valid) value. Use a JFormattedTextField, for example.