Attempting to change JTextFields Using Buttons - java

I am attempting to get the next set of values to display in the JTextFields after hitting the next button. I am new to programming so I am not really sure what I am missing. What I want to occur is when I hit the next button when the window displays the next set of values will now display in the appropriate JTextFields unfortunately what ends up happening is nothing. I have tried several different ways of getting this to work and so far nothing. I know it is not the button its self because if I change the actionPerformed next to say setTitle(“5000”) it will change the title within the window. Any help is appreciated.
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
public class GUI extends JFrame implements ActionListener {
JButton next;
JButton previous;
JButton first;
JButton last;
private JLabel itmNum = new JLabel("Item Number: ", SwingConstants.RIGHT);
private JTextField itemNumber;
private JLabel proNm = new JLabel ("Product Name: ", SwingConstants.RIGHT);
private JTextField prodName;
private JLabel yr = new JLabel("Year Made: ", SwingConstants.RIGHT);
private JTextField year;
private JLabel unNum = new JLabel("Unit Number: ", SwingConstants.RIGHT);
private JTextField unitNumber;
private JLabel prodPrice = new JLabel("Product Price: ", SwingConstants.RIGHT);
private JTextField price;
private JLabel restkFee = new JLabel("Restocking Fee", SwingConstants.RIGHT);
private JTextField rsFee;
private JLabel prodInValue = new JLabel("Product Inventory Value", SwingConstants.RIGHT);
private JTextField prodValue;
private JLabel totalValue = new JLabel("Total Value of All Products", SwingConstants.RIGHT);
private JTextField tValue;
private double toValue;
int nb = 0;
char x = 'y';
public GUI()
{
super ("Inventory Program Part 5");
setSize(800,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLookAndFeel();
first = new JButton("First");
previous = new JButton("Previous");
next = new JButton("Next");
last = new JButton("Last");
first.addActionListener(this);
previous.addActionListener(this);
next.addActionListener(this);
last.addActionListener(this);
Movies[] titles = new Movies[9];
titles [0] = new Movies(10001, "King Arthur", 25 , 9.99, 2004, .05);
titles [1] = new Movies(10002,"Tron", 25, 7.99, 1982, .05);
titles [2] = new Movies(10003, "Tron: Legacy",25,24.99,2010,.05);
titles [3] = new Movies(10004,"Braveheart", 25,2.50,1995,.05);
titles [4] = new Movies(10005,"Gladiator",25,2.50,2000,.05);
titles [5] = new Movies(10006,"CaddyShack SE",25,19.99,1980,.05);
titles [6] = new Movies (10007,"Hackers",25,12.50,1995,.05);
titles [7] = new Movies (10008,"Die Hard Trilogy",25,19.99,1988,.05);
titles [8] = new Movies (10009,"Terminator",25,4.99,1984,.05);
Arrays.sort (titles, DVD.prodNameComparator);
itemNumber.setText(Double.toString(titles[nb].getitemNum()));
prodName.setText(titles[nb].getprodName());
year.setText(Integer.toString(titles[nb].getYear()));
unitNumber.setText(Integer.toString(titles[nb].getunitNum()));
price.setText(Float.toString(titles[nb].getprice()));
rsFee.setText(Double.toString(titles[nb].getRestkFee()));
prodValue.setText(Double.toString(titles[nb].getprodValue()));
tValue.setText("2636");
setLayout(new GridLayout(8,4));
add(itmNum);
add(itemNumber);
add(proNm);
add(prodName);
add(yr);
add(year);
add(unNum);
add(unitNumber);
add(prodPrice);
add(price);
add(restkFee);
add(rsFee);
add(prodInValue);
add(prodValue);
add(totalValue);
add(tValue);
add(first);
add(previous);
add(next);
add(last);
setLookAndFeel();
setVisible(true);
}
public void updateFields()
{
itemNumber.getText();
prodName.getText();
year.getText();
unitNumber.getText();
price.getText();
rsFee.getText();
prodValue.getText();
tValue.getText();
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if (source == next)
{
nb++;
}
}
private void setLookAndFeel()
{
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
System.err.println("couln't use the system"+ "look and feel: " + e);
}
}
}

Your ActionListener only has one assignment
nb = 1;
and a repaint. This does not update the JTextFields with the values from your Movies array titles. You need to do this explicitly.
itemNumber.setText(Double.toString(titles[nb].getItemNum()));
...
To make this possible, you will need to make your Movies titles array a class member variable so that it can be accessed from your ActionListener.
Also you never actually change the value of nb in your ActionListener. As it's a "next" button, you will probably want to increment it:
nb++;
Side Notes:
Java uses camelcase which would make the method getitemNum getItemNum.
An ArrayList would give you more flexibility for adding Movie titles over an array which is fixed in size.

I think the logic of chaning JTextFields is inside the constructor of GUI class. So unless you are creating another object of GUI class, which I can see it is not being created. Your JTextFields will not be updated.
So basically to solve this problem you will have to move your logic of changing JTextFields inside another method like for example
public void updateFields(){
//place your logic code here
}
and then from actionPerformed method call this updateFields() method
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
if (source == next)
{
nb =1;
}
updateFields();
///repaint(); /// you don't need the repaint method
}
As per your question in the comments and as far as my understanding is concerned place your titles array outside the constructor, and do the following changes so it will look something like this:
private JTextField tValue;
private double toValue;
int nb = 0; //note initialize this to 0
Movies[] titles = new Movies[9];//this is the line that comes out of the Constructor
public GUI()
{
///inside the constructor do the following changes
for (int i = 0; i < titles.length; i ++)
{
toValue += (titles[i].gettotalVal());
}
//note I will be accessing the 0th position of the array assuming you need the contents of the first objects to be displayed
itemNumber = new JTextField(Double.toString(titles[0].getitemNum()));
prodName = new JTextField(titles[0].getprodName());
year = new JTextField(Integer.toString(titles[0].getYear()));
unitNumber = new JTextField (Integer.toString(titles[0].getunitNum()));
price = new JTextField (Float.toString(titles[0].getprice()));
rsFee = new JTextField (Double.toString(titles[0].getRestkFee()));
prodValue = new JTextField(Double.toString(titles[0].getprodValue()));
tValue = new JTextField ("2636");
nb = 0;
//if (nb == 0) you don't need a if statement
//{
next.addActionListener(this);
//}
///Now for the updateFields() method
public updateFields(){
nb++;
itemNumber.setText(Double.toString(titles[nb].getitemNum());
prodName.setText(titles[nb].getprodName());
year.setText(Integer.toString(titles[nb].getYear()));
unitNumber.setText(Integer.toString(titles[nb].getunitNum()));
price.setText(titles[nb].getprice()));
rsFee.setText(Double.toString(titles[nb].getRestkFee()));
prodValue.setText(Double.toString(titles[nb].getprodValue()));
}

Related

How do I place more than one JComponent on the same "line" on a confirm JOptionPane?

Here's my code:
public class PaymentDialog {
public static int show(Double value) {
JLabel total = new JLabel("Total: ");
JLabel totalValue = new JLabel(value.toString());
JLabel input = new JLabel("Entrada: ");
JTextField inputField = new JTextField();
JLabel change = new JLabel("Troco: ");
JLabel changeValue = new JLabel("1234");
JComponent[] components = new JComponent[] {
total,
totalValue,
input,
inputField,
change,
changeValue
};
int result = JOptionPane.showConfirmDialog(null, components, "Pagamento", JOptionPane.OK_CANCEL_OPTION);
return result;
}
}
Here's an image of it:
As you can see, each component occupies an entire line, which is atrocious. The label should be behind it's corresponding component, instead of above it.
How do I customize this layout behavior? If it's impossible, how could I create a custom JDialog that allows me to do it? (Since I don't want to create a JFrame to customize the layout properly, as it's not the same thing).
You can add any component to the option pane. So you can create your own panel and use any layout and add any components you want.
One problem is that the text field won't have focus. Focus will be on a button of the option pane.
If you want focus on the text field then check out the RequestFocusListener found in Dialog Focus. This will allow you to control which component on the panel gets focus when the option pane is displayed.
It also contains sample code for creating a panel with a GridLayout to display on the option pane.
I'll post the code for future humans:
public class PaymentDialog {
public static int show(Double value) {
JPanel componentPanel = new JPanel();
componentPanel.setLayout(new GridLayout(3, 2));
JLabel total = new JLabel("Total: ");
JLabel totalValue = new JLabel(value.toString());
JLabel input = new JLabel("Entrada: ");
JTextField inputField = new JTextField();
JLabel change = new JLabel("Troco: ");
JLabel changeValue = new JLabel("1234");
componentPanel.add(total);
componentPanel.add(totalValue);
componentPanel.add(input);
componentPanel.add(inputField);
componentPanel.add(change);
componentPanel.add(changeValue);
int result = JOptionPane.showConfirmDialog(null, new JComponent[]{componentPanel}, "Pagamento", JOptionPane.OK_CANCEL_OPTION);
return result;
}
}

Convert an incrementing/changing String value to existing incremental variable name of JButtons to modify their properties in java

Simplified: How to make String value to call specific existed JButton variable name in java?
I'm trying to make a non-ordinary Tic-Tac-Toe game...
Anyway, what I will post here is not really the whole concept of that. I just want to make it simple: I have 9 square jButtons named (3 by 3) (and maybe allow user to make 4x4, 5x5, 10x10 etc. via settings in future):
[markbox_00_00] / [markbox_00_01] / [markbox_00_02]
[markbox_01_00] / [markbox_01_01] / [markbox_01_02]
[markbox_02_00] / [markbox_02_01] / [markbox_02_02]
[btnSave] / [btnUndoActions]
where the first two digit represent the row and the next two is the column; and a save button (btnSave) and undo button(btnUndoActions).
Each markbox have default spring value of "0", when I click it turns "1"; and when I click "1" it turns "0". When you press undo button it will reset to last save.
Here is some of my simplified line of codes:
private byte markboxColLimit = 3, markboxRowLimit = 3, row, col;
private byte[][] saveNumber = new byte[markboxRowLimit][markboxColLimit];
private String buttonName;
public Astral_TicTacToe() {
initComponents();
/* I want something like this, but using a for loop based on markboxColLimit and
markboxRowLimit as limits */
markbox_00_00.setText("0");
markbox_00_01.setText("0");
markbox_00_02.setText("0");
markbox_01_00.setText("0");
markbox_01_01.setText("0");
markbox_01_02.setText("0");
markbox_02_00.setText("0");
markbox_02_01.setText("0");
markbox_02_02.setText("0");
/* I know the line below is wrong... what I'm trying is to avoid
* repetitiveness by looping and dynamically calling the variable
* name of JButtons, or in other ways...
*/
/* Attempting to make an alternative code from above (trying to make a loop instead) */
for(row = 0; row < markboxRowLimit; row++){
for(col = 0; col < markboxColLimit; col++){
buttonName = "markbox_0" + Byte.toString(row) + "_0" + Byte.toString(col);
buttonName.setText("0");
}
}
}
private void btnUndoActionsActionPerformed(java.awt.event.ActionEvent evt) {
markbox_00_00.setText(Byte.toString(saveNumber[0][0]));
markbox_00_01.setText(Byte.toString(saveNumber[0][1]));
markbox_00_02.setText(Byte.toString(saveNumber[0][2]));
markbox_01_00.setText(Byte.toString(saveNumber[1][0]));
markbox_01_01.setText(Byte.toString(saveNumber[1][1]));
markbox_01_02.setText(Byte.toString(saveNumber[1][2]));
markbox_02_00.setText(Byte.toString(saveNumber[2][0]));
markbox_02_01.setText(Byte.toString(saveNumber[2][1]));
markbox_02_02.setText(Byte.toString(saveNumber[2][2]));
}
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
saveNumber[0][0] = Byte.parseByte(markbox_00_00.getText());
saveNumber[0][1] = Byte.parseByte(markbox_00_01.getText());
saveNumber[0][2] = Byte.parseByte(markbox_00_02.getText());
saveNumber[1][0] = Byte.parseByte(markbox_01_00.getText());
saveNumber[1][1] = Byte.parseByte(markbox_01_01.getText());
saveNumber[1][2] = Byte.parseByte(markbox_01_00.getText());
saveNumber[2][0] = Byte.parseByte(markbox_02_00.getText());
saveNumber[2][1] = Byte.parseByte(markbox_02_01.getText());
saveNumber[2][2] = Byte.parseByte(markbox_02_02.getText());
}
private void markbox_00_00ActionPerformed(java.awt.event.ActionEvent evt) {
if("0".equals(markbox_00_00.getText()))
markbox_00_00.setText("1");
else
markbox_00_00.setText("0");
}
private void markbox_00_01ActionPerformed(java.awt.event.ActionEvent evt) {
if("0".equals(markbox_00_01.getText()))
markbox_00_00.setText("1");
else
markbox_00_00.setText("0");
}
....
private void markbox_02_02ActionPerformed(java.awt.event.ActionEvent evt) {
if("0".equals(markbox_00_00.getText()))
markbox_02_02.setText("1");
else
markbox_02_02.setText("0");
}
In short: how can I make String a specific variable name of JButton for calling/accessing/editing for their properties?
Example:
buttonName = markbox_01_02;
buttonName.setText("2");
is equavalent to markbox_01_02.getText("2");
I really appreciate the help, thank you...
P.S. I use to make JFrame in NetBeans Design (just click and drag the objects in palette window like JPanel, JButton, etc., so I don't type the code manually except making my own logical Method).
You probably need to redo your program and rephrase your question because it's kind of unclear where you're stuck that's why I wrote this answer as a Community Wiki.
The following program creates a GridLayout for the board and add 2 JButtons below it which contain "Save" and "Undo" buttons.
Whenever you press a button it will change it's text to 0 or 1 depending on the previous state of the button, and "Undo" button will undo last clic the same way, if it was 0 it will become 1 and viceversa.
I guess you should read How to write an ActionListener before copy-pasting this example, understand what it says and try to understand how this program works.
The logic to "Save" button is up to you 'cause I'm not sure what you wanna do there and I'm not gonna write all the code for you. This is made only for you to get an idea on how to handle events.
Also, the logic to end the game is left to you for the same reasons as the "Save" button.
I wish I knew how to record my screen in Ubuntu and save as GIF but here's a screenshot on how this program looks like:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TicTacToe implements ActionListener {
JFrame frame;
JButton buttons[];
JPanel pane, buttonPane;
boolean pressed[];
JButton save, undo;
int n = -1;
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
if(e.getSource() == buttons[i]) {
pressed[i] = !pressed[i];
buttons[i].setText(pressed[i] ? "1" : "0");
n = i;
break;
}
}
}
public TicTacToe () {
frame = new JFrame("Tic Tac Toe Game");
buttons = new JButton[9];
pane = new JPanel(new GridLayout(3, 3));
pressed = new boolean[9];
buttonPane = new JPanel(new FlowLayout());
save = new JButton("Save");
undo = new JButton("Undo");
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("0");
pressed[i] = false;
}
for (JButton b : buttons) {
b.addActionListener(this);
pane.add(b);
}
undo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (n == -1) {
return;
}
pressed[n] = !pressed[n];
buttons[n].setText(pressed[n] ? "1" : "0");
}
});
buttonPane.add(save);
buttonPane.add(undo);
frame.add(pane, BorderLayout.PAGE_START);
frame.add(buttonPane, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main (String args[]) {
new TicTacToe();
}
}

How to make String value to call specific existed JButton variable name in java?

So, I know there is this:
int number = Integer.parseInt("5");
String numtxt = Integer.toString(12);
double number = Double.parseDouble("4.5");
String numbertxt = Double.toString(8.2);
String letter = Character.toString('B');
char letter = "stringText".charAt(0);
so on...
but what I don't know how to make String value to call existed JButton variable name dynamically; is it even possible?
Let's say, I have 4 JButton called btn1, btn2, btn3 and btnFillNumber;
I create a String called buttonName;
package testing;
public class Testing extends javax.swing.JFrame {
String buttonName;
int num;
public Testing() {
initComponents();
}
#SuppressWarnings("unchecked")
// Generated Code <<<-----
private void btnFillNumberActionPerformed(java.awt.event.ActionEvent evt) {
for(num = 1; num <= 3; num++){
buttonName = "btn" + Integer.toString(num);
JButton.parseJButton(buttonName).setText(num);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
// Look and feel stteing code (optional) <<<-----
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Testing().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btn1;
private javax.swing.JButton btn2;
private javax.swing.JButton btn3;
private javax.swing.JButton btnFillNumber;
// End of variables declaration
}
I know there's no JButton.parseJButton(), I just don't want to make complicated explaination, I simple want a convertion from String to call JButton's variable name dynamically.
See this:
for(num = 1; num <= 3; num++){
buttonName = "btn" + Integer.toString(num);
JButton.parseJButton(buttonName).setText(num);
}
I want to make a loop using a String with
a fixed String value (btn) and
increment number after it (1, 2, 3...) and
make use to call a JButton.
I can just simply do this, but what if I got a 25 or more? So a loop what I wanted...
btn1.setText("1");
btn2.setText("2");
btn3.setText("3");
Note that the value of these JButtons are not necessarily incremental in some purpose.
Output:
My real development:
P.S. I use to make JFrame in NetBeans Design (just click and drag the objects in palette window like JPanel, JButton, etc., so I don't type the code manually except making my own logical Method; and I can't edit the code in grey background in Source View that was made automatically by Design View but in Design View itself. If you have tips and guide, I'll be happy to).
Use a Map:
private Map<String,JButton> buttonMap = new HashMap<String,JButton>();
In your constructor add your buttons:
buttonMap.add("btn1", btn1);
buttonMap.add("btn2", btn2);
buttonMap.add("btn3", btn3);
buttonMap.add("btn4", btn4);
And in your action Listener / Loop whatever make:
String buttonName = "btn1"; //should be parameter or whatever
JButton button = buttonMap.get(buttonName);
As an alternative you could just as well set up an array of JButton:
JButton[] buttons = new JButton[4];
button[0] = new JButton(); //btn1
button[1] = new JButton(); //btn2
button[2] = new JButton(); //btn3
button[3] = new JButton(); //btn4
And access it
JButton but = button[Integer.parseInt(buttonString)-1];
Or by utilizing the possibility of adding custom properties to UI elements (you'll need a JComponent for that)
getContentPane().putClientProperty("btn1", btn1);
and later retrieving whith
JButton but = (JButton)getContentPane().getClientProperty("btn1");
I agree with Kevin's comment. The best concrete Map<K,V> class is probably Hashtable<K,V>. You don't even need to create the button name, just associate an integer with it if they are all numbered (and if btnFillNumber can be 0).
Hashtable<Integer,JButton> buttonTable = new Hashtable<>();
// Fill buttonTable with buttons
JButton button = buttonTable.get(num);
if (button != null) {
// Do something with button
}
Because of autoboxing, you don't need to create Integer objects to query the hashtable, num can be an int primitive.

on button click update jttextfield and calculate with newly entered value?

In my Java GUI there are 4 JTextFields. The goal is to enter default values for 3 textfields (example .8 in code below) and calculate the value and display the calculation into the 4th textfield. The user should then be able to change the values of the numbers within the JTextField and then press the calculate button again to get the new values to recalculate and display them.
Problem: when the JTextfields are edited and the calculate button is pressed it does not calculate with the new numbers but instead with the old initial values.
JTextField S = new JTextField();
S.setText(".8");
String Stext = S.getText();
final double Snumber = Double.parseDouble(Stext);
.... *same setup for Rnumber*
.... *same setup for Anumber*
....
JButton btnCalculate_1 = new JButton("Calculate");
btnCalculate_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int valuec = (int) Math.ceil(((Snumber*Rnumber)/Anumber)/8);
String stringValuec = String.valueOf(valuec);
NewTextField.setText(stringCalc);
}
I have checked several posts and tried:
How Do I Get User Input from a TextField and Convert it to a Double?
Using JTextField for user input
for the basics. However whenever trying to adapt it to my code eclipse returns various errors.
use S.getText() inside the actionPerformed() method.
The code inside actionperformed block is invoked on the button press and the code outside it remains unaffected.
So once you run your code and insert values to text fields, it assigns the a value but it does not change the same when you change the value and press calculate button
try using This code.
class a extends JFrame implements ActionListener
{
JTextField t1,t2,t3;
a()
{
setLayout(null);
t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();
JButton B1 = new JButton("Calculate");
t3.setEditable(false);
t1.setBounds(10,10,100,30);
t2.setBounds(10,40,100,30);
t3.setBounds(10,70,100,30);
B1.setBounds(50, 110, 80, 50);
add(t1);
add(t2);
add(t3);
add(B1);
B1.addActionListener(this);
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new a();
}
#Override
public void actionPerformed(ActionEvent e)
{
double Snumber = Double.parseDouble(t1.getText());
double Rnumber = Double.parseDouble(t2.getText());
double Anumber = Snumber+Rnumber;
t3.setText(String.valueOf(Anumber));
}
}

Java - NullPointerException Issue

I have been working on a program and when I run it I get an error that says line 43 and 84 have a NullPointerException. This is the code. I have put comments where line 43 and 84 are. I am trying to make a word processor like Microsoft Word.
import javax.swing.*;
import java.awt.*;
public class Graphics {
// listing all the components
JFrame f1;
JPanel colorspanel;
JPanel sizepanel;
JPanel fontpanel;
JPanel mainpanel;
JTextField Maintextfield;
JLabel colorlabel;
JLabel sizelabel;
JLabel fontlabel;
JButton colorbuttons[];
JButton sizebuttons[];
JButton fontbuttons[];
Graphics() {
// making instances of panels
colorspanel = new JPanel();
sizepanel = new JPanel();
fontpanel = new JPanel();
mainpanel = new JPanel();
// setting the size of the panels
colorspanel.setSize(216, 144);
sizepanel.setSize(216, 144);
fontpanel.setSize(216, 144);
mainpanel.setSize(612, 756);
// making instances of button
colorbuttons = new JButton[9];
sizebuttons = new JButton[14];
fontbuttons = new JButton[9];
// setting content for buttons
// colorbuttons
colorbuttons[0].setBackground(Color.black);//line 43
colorbuttons[1].setBackground(Color.red);
colorbuttons[2].setBackground(Color.blue);
colorbuttons[3].setBackground(Color.yellow);
colorbuttons[4].setBackground(Color.green);
colorbuttons[5].setBackground(Color.gray);
colorbuttons[6].setBackground(Color.DARK_GRAY);
colorbuttons[7].setBackground(Color.ORANGE);
colorbuttons[8].setBackground(Color.pink);
colorbuttons[9].setBackground(Color.magenta);
// sizebuttons
sizebuttons[0].setText("8");
sizebuttons[1].setText("10");
sizebuttons[2].setText("12");
sizebuttons[3].setText("14");
sizebuttons[4].setText("16");
sizebuttons[5].setText("18");
sizebuttons[6].setText("20");
sizebuttons[7].setText("22");
sizebuttons[8].setText("24");
sizebuttons[9].setText("26");
sizebuttons[10].setText("28");
sizebuttons[11].setText("30");
sizebuttons[12].setText("32");
sizebuttons[13].setText("34");
sizebuttons[14].setText("36");
// fontbuttons
fontbuttons[0].setText("New Times Roman");
fontbuttons[1].setText("Blackadder ITC");
fontbuttons[2].setText("Andy");
fontbuttons[3].setText("Buxton Sketch");
fontbuttons[4].setText("Arial Black");
fontbuttons[5].setText("Comic Sans MS");
fontbuttons[6].setText("Old English Text MT");
fontbuttons[7].setText("SketchFlow Print");
fontbuttons[8].setText("Harlow Solid Italic");
fontbuttons[9].setText("Algerian");
f1.setVisible(true);
}
public static void main(String[] args){
Graphics graphics = new Graphics();//line 84
}
}
You allocate a new JButton array, but you don't allocate the elements therein:
colorbuttons = new JButton[9];
There should be a corresponding:
for (int i = 0; i < 9; i++) {
colorbuttons[i]= new JButton(...);
}
Otherwise, you're allocating space for the array of buttons, but never actually initializing each of the JButtons. Thus, colorbuttons[0] is null, and colorbuttons[0].blah() causes the NPE.
You created an array, but you never populated it with anything. You need to put buttons in the array. A NullPointerException means that you tried to reference something, but a null value was found, not an object with a method or property. For example
Object x = null;
x.toString(); // NPE
vs
Object x = new Object();
x.toString(); // we're in business
In your case, you created an array (over 2 lines; just create everything on one line IMHO), but never put the buttons in it. So when you call colorButtons[0].whatever you are trying to access whatever on the reference at index 0. But since you didn't put anything in the array, that reference is null.
Do something more like
JButton[] colorButtons = new JButton[9]; // initialize array
for (int i = 0; i < colorButtons.length; i++) {
JButton button = ... // initialize button each time thru
// do any common setup on the buttons
colorButtons[i] = button; // put the button in the array.
}
You didn't put anything into the colorbuttons array! Of-course it's null.
Here:
for(int i=0; i<colorbuttons.length; i++)
colorbuttons[i] = new JButton();
You JButton array is empty. You just declared it and nothing more.
Populate your array by adding buttons to it.
Something like this:
colorbuttons = new JButton[9];
for (int i = 0; i < 9; i++) {
//Your logic here
colobuttons[i] = new JButton();
}

Categories

Resources