I'm kind of new to java, so go easy. I'm trying to make a simple game where everytime you click a button it adds one to a variable. That all works fine, but i'm also trying to display the variable to my JFrame. This is where the trouble comes, I click the button, it does add one to my variable (I printed the variable to the console to be sure) but the JFrame isn't updating the variable. I should also note, when you first open the game, it opens a window allowing you to type a username, this is in a separate class, which contains my main method. Here is my code for my second window, the one with the problem:
import javax.swing.BorderFactory;
public class Game extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private String name;
public static int pennies = 0;
public static int dollars = 0;
public static int moneyAddRate = 1;
private JButton btnAddMoney = new JButton(new ImageIcon("C:\\Users\\Tanner\\git\\Money-Bags\\res\\coins\\oneCent.png"));
private Border emptyBorder = BorderFactory.createEmptyBorder();
public Game(String name) {
this.name = name;
createWindow();
}
private void createWindow() {
setTitle(name + "'s Economy");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnAddMoney.setBounds(329, 244, 96, 96);
btnAddMoney.setBorder(emptyBorder);
contentPane.add(btnAddMoney);
btnAddMoney.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addMoney();
}
});
JLabel lblPennies = new JLabel("You have " + pennies + " Pennies");
lblPennies.setBounds(10, 11, 152, 24);
contentPane.add(lblPennies);
JLabel lblDollars = new JLabel(dollars + " Dollars");
lblDollars.setBounds(10, 70, 152, 24);
contentPane.add(lblDollars);
JLabel lblAnd = new JLabel("&");
lblAnd.setBounds(10, 45, 61, 14);
contentPane.add(lblAnd);
setVisible(true);
}
private void addMoney() {
pennies += moneyAddRate;
System.out.println(pennies + " " + dollars);
contentPane.validate();
contentPane.repaint();
}
}
It isn't updating because you aren't updating any Component with the new pennies amount. Your addMoney() method should look something like this:
private void addMoney() {
pennies += moneyAddRate;
lblPennies.setText(String.format("You have %d pennies", pennies));
lblPennies.repaint();
}
Related
I am trying to making a calculator.
Here the user can add multiple JTextFields to take his/her desired input with just one button click.
Now I want that the user will take the input in multiple JTextFields added by him and on clicking the Result button will show the sum of all. But I am always getting 0 as output.
Code:
public class Button extends JFrame {
private JPanel contentPane;
private JButton btnAdd;
private JButton btnResult;
private JTextField resultField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Button frame = new Button();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Button() {
initComponents();
}
static JTextField field = null;
//static JTextField fields[] = new JTextField[10];
private static int y = 0;
ArrayList<String> arr = new ArrayList<String>();
int ans, sum = 0;
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 527, 414);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
field = new JTextField();
field.setBounds(45, y += 60, 284, 32);
field.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(field);
contentPane.revalidate();
contentPane.repaint();
}
});
btnAdd.setBounds(170, 341, 89, 23);
contentPane.add(btnAdd);
btnResult = new JButton("Result");
btnResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < arr.size(); i++) {
arr.add(field.getText());
sum += Integer.parseInt(arr.get(i));
}
resultField.setText(String.valueOf(sum));
}
});
btnResult.setBounds(383, 306, 89, 23);
contentPane.add(btnResult);
resultField = new JTextField();
resultField.setBounds(361, 275, 129, 20);
contentPane.add(resultField);
resultField.setColumns(10);
}
}
Please help how can I find the correct output?
Suggestions:
Again, when you create a data-entry text field, add it to the GUI and add it to an ArrayList of the data entry field type.
Then in the result button's ActionListener, iterate through this list using a for loop.
Inside of the for loop, get the entry field, get its text (via .getText() if using a JTextField), parse it to number via Integer.parseInt(...), and add it to a sum variable that is initialized to 0 prior to the for loop. Then display the result after the loop.
Also,
Best to use JSpinners that use a SpinnerNumberModel such as JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1)); instead of JTextField for number entry. This will limit the user to entering numbers only, and won't allow non-numeric text entry, a danger inherent in your current design.
Having to add your entry fields by button may be an over-complication
But if it is necessary, then best to add the spinners (or text fields if you must) to a JPanel that uses a proper layout manager, such a new GridLayout(0, 1) (variable number of rows, 1 column) and then add that to a JScrollPane so that you can see as many fields as has been entered.
If using a JSpinner, then you don't even need a "calculate result" button, since if you add a ChangeListener to each JSpinner, you can calculate the result on the fly whenever a spinner has had its data changed.
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Button2 extends JPanel {
private List<JSpinner> spinnerList = new ArrayList<>();
private JButton resultButton = new JButton("Result");
private JButton addEntryFieldBtn = new JButton("Add Entry Field");
private JTextField resultField = new JTextField(6);
private JPanel fieldPanel = new JPanel(new GridLayout(0, 1, 4, 4));
public Button2() {
resultField.setFocusable(false);
resultButton.addActionListener(e -> calcResult());
resultButton.setMnemonic(KeyEvent.VK_R);
addEntryFieldBtn.addActionListener(e -> addEntryField());
JPanel topPanel = new JPanel();
topPanel.add(addEntryFieldBtn);
topPanel.add(resultButton);
topPanel.add(new JLabel("Result:"));
topPanel.add(resultField);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(fieldPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(centerPanel);
scrollPane.setPreferredSize(new Dimension(300, 300));
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane);
}
private void calcResult() {
int sum = 0;
for (JSpinner spinner : spinnerList) {
sum += (int) spinner.getValue();
}
resultField.setText(String.valueOf(sum));
}
private void addEntryField() {
JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
spinner.addChangeListener(evt -> {
calcResult();
});
fieldPanel.add(spinner);
spinnerList.add(spinner);
revalidate();
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Button2 mainPanel = new Button2();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to make a text based adventure that runs in a jframe but when i run the program i get a NullPointer error on line 97 (first time i append console in the game method) and I have no idea how to fix it. I am relatively new to java so its probably something simple that I just don't know.
my code is here
package window;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Gui extends JFrame {
public JPanel contentPane;
public static JTextField input;
public static JButton send;
public static JTextArea console;
public static JTextArea invintory;
public static JTextArea stats;
static String i = "";
/**
* Launch the application.
*/
/**
* Create the frame.
*/
public Gui() {
//variables
int Gold = 20;
int Health = 100;
int MaxHealth = 100;
//variables end
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTextArea console = new JTextArea();
console.setBounds(10, 11, 281, 214);
contentPane.add(console);
input = new JTextField();
input.setBounds(10, 236, 281, 20);
contentPane.add(input);
input.setColumns(10);
JTextArea stats = new JTextArea();
stats.setBounds(301, 11, 123, 53);
contentPane.add(stats);
JTextArea invintory = new JTextArea();
invintory.setBounds(301, 75, 128, 137);
contentPane.add(invintory);
JButton send = new JButton("Send");
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String i = input.getText();
input.setText("");
stats.setText("");
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
});
send.setBounds(301, 224, 128, 32);
contentPane.add(send);
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
public static void game (JButton send, JTextArea console, JTextArea stats, JTextArea invintory, JTextField input, String i) {
//start
//START
//START
//START
//START
while (true) {
console.append("You wake up open feild, with vast amounts of wheet in every direction");
console.append("There is a path going in either direction what do you want to do");
console.append("\t1. Go left.");
console.append("\t2. Go right.");
while (i == "") {
}
if (i == "1") {
console.append("1");
break;
}
else if (i == "2") {
console.append("2");
break;
}
}
//END
//END
//END
//END
}
public static void main(String[] args) {
try {
Gui frame = new Gui();
frame.setVisible(true);
Gui.game(send, console, stats, invintory, input, i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In your global variable console is null
public static JTextArea console;
You initialized it in Gui method
JTextArea console = new JTextArea();
So here in Gui method your global console variable is not initialized, This creates a local variable console under Gui method.
To initialize global variable in Gui method you need to initialize this way
console = new JTextArea();
You did this mistake to all variables so edit your code this way
public Gui() {
//variables
int Gold = 20;
int Health = 100;
int MaxHealth = 100;
//variables end
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
console = new JTextArea();
console.setBounds(10, 11, 281, 214);
contentPane.add(console);
input = new JTextField();
input.setBounds(10, 236, 281, 20);
contentPane.add(input);
input.setColumns(10);
stats = new JTextArea();
stats.setBounds(301, 11, 123, 53);
contentPane.add(stats);
invintory = new JTextArea();
invintory.setBounds(301, 75, 128, 137);
contentPane.add(invintory);
send = new JButton("Send");
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String i = input.getText();
input.setText("");
stats.setText("");
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
});
send.setBounds(301, 224, 128, 32);
contentPane.add(send);
stats.append("Health: " + Health + "/" + MaxHealth + "\n");
stats.append("Gold: " + Gold);
}
I'm writing this code for university, to read the user input and calculate the charges (its a hospital bill)
But when I press calculate the JTextArea displays 0 as value
I'm very much a newbie so any guidance would be appreciated
the code is:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HospitalChargesCalculator extends JFrame implements ActionListener{
private JLabel hospitalStayLabel;
private JLabel medicationLabel;
private JLabel surgicalFeesLabel;
private JLabel labFeesLabel;
private JLabel rehabLabel;
private JLabel totalLabel;
private JTextField hospitalStayTF;
private JTextField medicationTF;
private JTextField surgicalFeesTF;
private JTextField labFeesTF;
private JTextField rehabTF;
private JTextArea totalChargesTA;
private JButton calculateB;
private JButton exitB;
public static final int WIDTH = 500;
public static final int HEIGHT = 350;
static int totalStayCharge;
static int totalMisc;
static int totalCharges;
static int totalDays;
static int totalMedication;
static int totalSurgical;
static int totalLab;
static int totalRehab;
public HospitalChargesCalculator() {
setTitle("Hospital Charges");
Container c = getContentPane();
setSize(WIDTH, HEIGHT);
c.setLayout(null);
hospitalStayLabel = new JLabel(" Number of days spent in hospital: ",
SwingConstants.LEFT);
medicationLabel = new JLabel(" Total Medication Charges: ",
SwingConstants.LEFT);
surgicalFeesLabel = new JLabel(" Total sugical charges : ",
SwingConstants.LEFT);
labFeesLabel = new JLabel(" Total lab fees: ",
SwingConstants.LEFT);
rehabLabel = new JLabel(" Total Rehab charges: ",
SwingConstants.LEFT);
totalLabel = new JLabel(" Total Charges: ",
SwingConstants.LEFT);
calculateB = new JButton("Calculate");
calculateB.addActionListener(this);
exitB = new JButton("Exit");
exitB.addActionListener(this);
hospitalStayTF = new JTextField();
medicationTF = new JTextField();
surgicalFeesTF = new JTextField();
labFeesTF = new JTextField();
rehabTF = new JTextField();
totalChargesTA = new JTextArea();
hospitalStayLabel.setSize(250, 30);
hospitalStayTF.setSize(200, 30);
medicationLabel.setSize(200, 30);
medicationTF.setSize(200, 30);
surgicalFeesLabel.setSize(200, 30);
surgicalFeesTF.setSize(200, 30);
labFeesLabel.setSize(200, 30);
labFeesTF.setSize(200, 30);
rehabLabel.setSize(200, 30);
rehabTF.setSize(200,30);
totalLabel.setSize(200, 30);
totalChargesTA.setSize(200,30);
calculateB.setSize(100, 30);
exitB.setSize(100, 30);
hospitalStayLabel.setLocation(30, 25);
hospitalStayTF.setLocation(250, 25);
medicationLabel.setLocation(30, 60);
medicationTF.setLocation(250, 60);
surgicalFeesLabel.setLocation(30, 95);
surgicalFeesTF.setLocation(250, 95);
labFeesLabel.setLocation(30, 130);
labFeesTF.setLocation(250, 130);
rehabLabel.setLocation(30, 165);
rehabTF.setLocation(250, 165);
totalLabel.setLocation(30, 250);
totalChargesTA.setLocation(250, 250);
calculateB.setLocation(70, 205);
exitB.setLocation(300, 205);
c.add(hospitalStayLabel);
c.add(hospitalStayTF);
c.add(medicationLabel);
c.add(medicationTF);
c.add(surgicalFeesLabel);
c.add(surgicalFeesTF);
c.add(labFeesLabel);
c.add(labFeesTF);
c.add(rehabLabel);
c.add(rehabTF);
c.add(totalLabel);
c.add(totalChargesTA);
c.add(calculateB);
c.add(exitB);
hospitalStayTF.addActionListener(this);
medicationTF.addActionListener(this);
surgicalFeesTF.addActionListener(this);
labFeesTF.addActionListener(this);
rehabTF.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformedGet(ActionEvent g)
{
totalDays = Integer.parseInt(hospitalStayTF.getText());
totalMedication = Integer.parseInt(medicationTF.getText());
totalSurgical = Integer.parseInt(surgicalFeesTF.getText());
totalLab = Integer.parseInt(labFeesTF.getText());
totalRehab = Integer.parseInt(rehabTF.getText());
}
public int CalcStayCharges()
{
int dailyCharge = 350;
totalStayCharge = totalDays * dailyCharge;
return totalStayCharge;
}
public int CalcMiscCharges()
{
totalMisc = (totalMedication + totalSurgical + totalLab + totalRehab);
return totalMisc;
}
public int CalcTotalCharges()
{
totalCharges = (totalStayCharge + totalMisc);
return totalCharges;
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Calculate"))
{
totalChargesTA.setText(String.valueOf(totalCharges));
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
public static void main(String[] args)
{
HospitalChargesCalculator hospCalc = new HospitalChargesCalculator();
}
}
if you press the button you simply execute actionPerformed(ActionEvent e), which only does totalChargesTA.setText(String.valueOf(totalCharges));. In order to get a value you should use any of your calculalationmethods before using the setText method.
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Calculate"))
{
totalCharges = CalcTotalCharges();
totalChargesTA.setText(String.valueOf(totalCharges));
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
it might be that you need to call some of the other methods aswell, if they are calculating the values that are used inside of CalcTotalCharges.
I cant comment yet, so here as an answer.
As said you dont actually call the function to calculate your total charges with totalChargesTA.setText(String.valueOf(totalCharges)); but instead try to directly access the variable totalCharges of your method CalcTotalCharges() (the method you should be calling here), this is only possible because you declared all your variables as static int so you can access them even in parts of your code where you dont actually want to access them.
Dont declare all your variables static, and you would have seen the error of not calling the methods. Think about which variables need to be static and reduce it to those.
Also dont declare all your variables you are going to use in just that one function in your class, inistead declare them in that function, so that you avoid the same error as with your static declarations.
-- Also, additionaly the answer provided by Subin Thomas that shows the principal error in your code, his solution wont work because he mixed up some of the functions and you also have to fix the function:
public int CalcTotalCharges()
{
totalCharges = (totalStayCharge + totalMisc);
return totalCharges;
}
Where you have the same kind of error to:
public int CalcTotalCharges()
{
totalCharges = (CalcStayCharges() + CalcMiscCharges());
return totalCharges;
}
EDIT: Actually you also have another error in the way you retrieve the values from you input textfields. Why did you use the method public void actionPerformedGet(ActionEvent g) ?
This wont work with your ActionListener. Instead copy the code in this function to your actionPerformed Method. Then it will actually work. For completeness here the working code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HospitalChargesCalculator extends JFrame implements ActionListener{
private JLabel hospitalStayLabel;
private JLabel medicationLabel;
private JLabel surgicalFeesLabel;
private JLabel labFeesLabel;
private JLabel rehabLabel;
private JLabel totalLabel;
private JTextField hospitalStayTF;
private JTextField medicationTF;
private JTextField surgicalFeesTF;
private JTextField labFeesTF;
private JTextField rehabTF;
private JTextArea totalChargesTA;
private JButton calculateB;
private JButton exitB;
public static final int WIDTH = 500;
public static final int HEIGHT = 350;
int totalDays;
int totalMedication;
int totalSurgical;
int totalLab;
int totalRehab;
public HospitalChargesCalculator() {
setTitle("Hospital Charges");
Container c = getContentPane();
setSize(WIDTH, HEIGHT);
c.setLayout(null);
hospitalStayLabel = new JLabel(" Number of days spent in hospital: ",
SwingConstants.LEFT);
medicationLabel = new JLabel(" Total Medication Charges: ",
SwingConstants.LEFT);
surgicalFeesLabel = new JLabel(" Total sugical charges : ",
SwingConstants.LEFT);
labFeesLabel = new JLabel(" Total lab fees: ",
SwingConstants.LEFT);
rehabLabel = new JLabel(" Total Rehab charges: ",
SwingConstants.LEFT);
totalLabel = new JLabel(" Total Charges: ",
SwingConstants.LEFT);
calculateB = new JButton("Calculate");
calculateB.addActionListener(this);
exitB = new JButton("Exit");
exitB.addActionListener(this);
hospitalStayTF = new JTextField();
medicationTF = new JTextField();
surgicalFeesTF = new JTextField();
labFeesTF = new JTextField();
rehabTF = new JTextField();
totalChargesTA = new JTextArea();
hospitalStayLabel.setSize(250, 30);
hospitalStayTF.setSize(200, 30);
medicationLabel.setSize(200, 30);
medicationTF.setSize(200, 30);
surgicalFeesLabel.setSize(200, 30);
surgicalFeesTF.setSize(200, 30);
labFeesLabel.setSize(200, 30);
labFeesTF.setSize(200, 30);
rehabLabel.setSize(200, 30);
rehabTF.setSize(200,30);
totalLabel.setSize(200, 30);
totalChargesTA.setSize(200,30);
calculateB.setSize(100, 30);
exitB.setSize(100, 30);
hospitalStayLabel.setLocation(30, 25);
hospitalStayTF.setLocation(250, 25);
medicationLabel.setLocation(30, 60);
medicationTF.setLocation(250, 60);
surgicalFeesLabel.setLocation(30, 95);
surgicalFeesTF.setLocation(250, 95);
labFeesLabel.setLocation(30, 130);
labFeesTF.setLocation(250, 130);
rehabLabel.setLocation(30, 165);
rehabTF.setLocation(250, 165);
totalLabel.setLocation(30, 250);
totalChargesTA.setLocation(250, 250);
calculateB.setLocation(70, 205);
exitB.setLocation(300, 205);
c.add(hospitalStayLabel);
c.add(hospitalStayTF);
c.add(medicationLabel);
c.add(medicationTF);
c.add(surgicalFeesLabel);
c.add(surgicalFeesTF);
c.add(labFeesLabel);
c.add(labFeesTF);
c.add(rehabLabel);
c.add(rehabTF);
c.add(totalLabel);
c.add(totalChargesTA);
c.add(calculateB);
c.add(exitB);
hospitalStayTF.addActionListener(this);
medicationTF.addActionListener(this);
surgicalFeesTF.addActionListener(this);
labFeesTF.addActionListener(this);
rehabTF.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public int CalcStayCharges()
{
int dailyCharge = 350;
int totalStayCharge = totalDays * dailyCharge;
return totalStayCharge;
}
public int CalcMiscCharges()
{
int totalMisc = (totalMedication + totalSurgical + totalLab + totalRehab);
return totalMisc;
}
public int CalcTotalCharges()
{
int totalCharges = (CalcStayCharges() + CalcMiscCharges());
return totalCharges;
}
public void actionPerformed(ActionEvent e)
{
totalDays = Integer.parseInt(hospitalStayTF.getText());
totalMedication = Integer.parseInt(medicationTF.getText());
totalSurgical = Integer.parseInt(surgicalFeesTF.getText());
totalLab = Integer.parseInt(labFeesTF.getText());
totalRehab = Integer.parseInt(rehabTF.getText());
if (e.getActionCommand().equals("Calculate"))
{
totalChargesTA.setText(CalcTotalCharges()+"");
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
public static void main(String[] args)
{
HospitalChargesCalculator hospCalc = new HospitalChargesCalculator();
}
}
OK, I am trying to create a GUI that has a JScrollPane that, through the JTextArea, will print out an array of ints, one line at a time. I am using some methods I created for an assignment to deal with the data, and have one of them working on the data in the following example, (I can't show the methods because it's homework that isn't due yet). The methods have been tested and work fine, so no need for them in this question. So far, either the text area will show up in the GUI, but not have the scroll pane attached to it, or only the jlabel will show up with the results of the work done via the method. Can someone have a look at my code and tell me what I am doing wrong, because I have gone over this like 50 times, and cannot get the GUI to behave.
public class MyClassName extends JFrame{
private JScrollPane myScroll;
private JTextArea myTextArea;
private JLabel myMean;
private JLabel myMedian;
private JLabel myMax;
private JLabel myMin;
private JLabel mySum;
private Container content;
private Font myFont;
private SpringLayout layout;
private MyClassName() {
this(500,300,"TEST TITLE");
}
private MyClassName(int width, int height, String title)
{
this.setVisible(true);
this.setTitle(title);
this.setSize(width, height);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiComponent();
}
public void guiComponent()
{
layout = new SpringLayout();
content = this.getContentPane();
int [] test = {50,37,43,12,8,16,32,44,78,92,1,3,66,34};
myTextArea = new JTextArea();
myScroll = new JScrollPane(myTextArea);
content.add(myScroll);
myMean = new JLabel("MEAN : " + MyClassName.mean(test));
for(int count : test)
{
String z = Integer.toString(count);
myTextArea.append('\n' + z);
}
myFont = new Font("Serrif", Font.BOLD, 30);
myMean.setFont(myFont);
content.add(myScroll);
layout.putConstraint(SpringLayout.WEST, myScroll, 20, SpringLayout.WEST, content);
layout.putConstraint(SpringLayout.NORTH, myScroll, 25, SpringLayout.NORTH, content);
content.add(myMean);
layout.putConstraint(SpringLayout.WEST, myMean, 20, SpringLayout.EAST, myScroll);
layout.putConstraint(SpringLayout.NORTH, myMean, 25, SpringLayout.NORTH, content);
}
public static double mean(int[] ar) {
double x = 0;
for (int i = 0; i < ar.length; i++) {
x += ar[i];
}
return x / ar.length;
}
public static void main(String[] args) {
MyClassName test2 = new MyClassName();
}
Your problem when you need to display the components in layout, to solve your problem add those three line after initialize 'myTextArea' component:
myTextArea.setColumns(20);
myTextArea.setRows(5);
getContentPane().setLayout(layout);
you maybe need to read this link about Layout.
Code is underneath. Basically what I'm trying to do is I have display going on in my JPanel of a JTextPane. I have a button that edits the value of the string that's supposed to be displayed in the JTextPane. I can't figure out how to update the JTextPane however. I've tried revalidate(), validate(), repaint(), none of those seemed to work.
The code is complete, it should be able to run.
import java.awt.Canvas;
public class windowBuild extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private int health = 20;
private int energy = 4;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
windowBuild frame = new windowBuild();
frame.setVisible(true);
}
});
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
if (which.equals("Claw")){
energy = energy-1;
System.out.println("Player one's dragon clawed the opponent. Dragon's energy is now at: "+ energy);}
else if (which.equals("Wait")){
System.out.println("Turn succesfully skipped");}
System.out.println(getEnergy());
}
}
public windowBuild() {
ButtonHandler bh;
System.out.println("Starting frame...");
bh = new ButtonHandler();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new TitledBorder(null, "Dragon Duel",
TitledBorder.CENTER, TitledBorder.TOP, null, Color.CYAN));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnClaw = new JButton("Claw");
btnClaw.setBounds(288, 511, 109, 39);
contentPane.add(btnClaw);
btnClaw.addActionListener(bh);
if (energy == 0)
btnClaw.setEnabled(false);
JButton btnWait = new JButton("Wait");
btnWait.setBounds(645, 511, 109, 39);
contentPane.add(btnWait);
btnWait.addActionListener(bh);
StringBuilder sb = new StringBuilder();
String strB = Integer.toString(health);
sb.append("H: ").append(strB).append("/20");
String healthString = sb.toString();
JTextPane txtpnH_1 = new JTextPane();
txtpnH_1.setEditable(false);
txtpnH_1.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH_1.setText(healthString);
txtpnH_1.setBounds(134, 511, 109, 39);
contentPane.add(txtpnH_1);
String strR = Integer.toString(energy);
String energyString = "E: ";
energyString += strR;
energyString += "/4";
JTextPane txtpnH = new JTextPane();
txtpnH.setEditable(false);
txtpnH.setText(energyString);
txtpnH.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH.setBounds(39, 511, 85, 39);
contentPane.add(txtpnH);
}
}
Thanks so much!!
Take the time to read through the Code Conventions for the Java Programming Language
Make use of appropriate layout managers, see A Visual Guide to Layout Managers and Using Layout Managers for more details
For what it's worth, use JTextField instead JTextPane, you're gaining little to no benefit by using JTextPane for what you seem to be trying to achieve. In fact, you might actually be better of us just using JLabel, seen as you don't want them to be editable
Avoid overriding top level containers, like JFrame, instead start with something like JPanel, build your UI on it and then deploy it to what ever top level container you want.
The problem you have is a reference issue. In the constructor of your windowBuild, you are defining all your UI components. This means that there is no way you can reference them anywhere else from with your program. Instead, make those components you need to reference else where instance fields.
public class WindowBuild extends JFrame {
//...//
private JTextPane txtpnH_1;
private JTextPane txtpnH;
//...//
public WindowBuild() {
//...//
txtpnH_1 = new JTextPane();
//...//
txtpnH = new JTextPane();
//...//
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
// Now you can use txtpnH_1.setText and txtpnH.setText
}
}