Changing text on a JLabel from another class - java

So, I have been trying to figure this out for a little bit and cannot figure out how to do it. I want one of my buttons in another class to change the text of a JLabel in the GUI class.
Here is the code from GUI class:`import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class GUI extends JFrame{
Container pane = getContentPane();
JButton guess = new JButton("Guess");
JButton gen = new JButton("Generate number");
JTextField userInput = new JTextField();
JLabel Numbers = new JLabel("Press generate to start.");
JLabel guessedNum = new JLabel("");
JLabel error = new JLabel("");
public void CreateGUI(){
final int WIDTH = 325;
final int HEIGHT = 200;
final int centerWIDTH = WIDTH / 4;
final int centerHEIGHT = HEIGHT / 4;
guessHandler guessHandle;
genHandler genHandle;
pane.setLayout(null);
guessHandle = new guessHandler();
guess.addActionListener(guessHandle);
genHandle = new genHandler();
gen.addActionListener(genHandle);
userInput.setBounds(centerWIDTH - 20, centerHEIGHT, 200, 20);
guess.setBounds(userInput.getX() - 35, (userInput.getY() + 25), 105, 50);
gen.setBounds((guess.getX() + 105), guess.getY(), 165, 50);
error.setBounds(70, 125, 300, 20);
Numbers.setBounds(90, 0, 300, 20);
guessedNum.setBounds(20, 25, 300, 20);
pane.add(userInput);
pane.add(guess);
pane.add(gen);
pane.add(Numbers);
pane.add(guessedNum);
pane.add(error);
setSize(WIDTH,HEIGHT);
setTitle("Number Guesser");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setLocation(350, 150);
}
}
And here the code from the button trying to change the JLabel "error":
`
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class guessHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
GUI gui = new GUI();
gui.changePOS(4, 50, 0, 300, 20);
gui.error.setText("HI from guessHandler.java");
}
}

First, add a getter with public access so your second class can access the field. Something like,
public JLabel getError() {
return error;
}
Or (as #MadProgrammer suggested in the comments, a mutator) like
public void setError(String txt) {
error.setText(txt);
}
Then modify your second class, and pass the instance of GUI to it in the constructor. Like,
public class guessHandler implements ActionListener{
private GUI gui;
public guessHandler(GUI gui) {
this.gui = gui;
}
public void actionPerformed(ActionEvent e) {
gui.changePOS(4, 50, 0, 300, 20);
gui.setError("HI from guessHandler.java");
}
}

Related

PaintComponent not showing up

i'm currently adding functionality and completing a Hang-Man game my programing teacher made.
I added a frame to enable the user to write their own word to play the game however i stumbled on the following problem.
The PaintComponent that is supposed to draw when the user guesses the wrong word does not work. it does not draw when i guess the wrong word. (right now the word to guess is set to "hello" but i am going to change it after PaintComponent works).
i have tried to put all the components including the object to a JPanel but after i tried to do that the JFrame did not show upp after i pressed the button (b).
should i try with JPanel again or can i do anything to solve it as it currently is. i would like to point out that my teachers original code does not have the components put into a JPanel, he only has a frame. However his class extends with JPanel.
Anny suggestions ?
package hangtest2;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class HangTest2 {
public static void main(String[] args) {
// frame intro skärm
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HangMan");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3,1));
//label till orden
JLabel intro = new JLabel();
String ord = "Valfri";
intro.setText(ord);
Font font = new Font("Verdana", Font.BOLD, 25);
intro.setFont(font);
//till att välja ord
JTextField field = new JTextField(10);
field.setFont(font);
JButton b = new JButton("ok");
b.setBounds(370, 300, 100, 30);
frame.add(intro);
frame.add(field);
frame.add(b);
frame.setBackground(Color.white);
frame.setSize(600, 400);
frame.setVisible(true);
// frame hang
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame2 = new JFrame("HangMan");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setLayout(null);
JPanel p2 = new JPanel();
p2.setLayout(null);
JLabel hang = new JLabel();
String firstinstruct = "Gissa genom att Mata in en bokstav ";
hang.setText(firstinstruct);
Font font2 = new Font("Verdana", Font.BOLD, 10);
hang.setFont(font2);
hang.setBounds(70, 100, 600,150 );
JTextField field2 = new JTextField();
field2.setVisible(true);
field2.setSize(300, 30);
field2.setLocation(60, 300);
field2.setVisible(true);
JButton b2 = new JButton("ok");
b2.setBounds(370, 300, 100, 30);
frame2.add(b2);
frame2.add(field2);
frame2.add(hang);
frame2.setBackground(Color.white);
frame2.setSize(600, 400);
DynamicHangTest2 object = new DynamicHangTest2(field, field2, b, b2, frame, frame2);
b.addActionListener(object);
field.addActionListener(object);
b2.addActionListener(object);
field2.addActionListener(object);
frame2.add(object);
frame2.setVisible(false);
}
}
The Dynamic Class
package hangtest2;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DynamicHangTest2 extends JPanel implements ActionListener, MouseListener {
private int error;
public static String a = "hello";
JFrame frame, frame2;
JButton b,b2;
JTextField field, field2;
public DynamicHangTest2(JTextField field, JTextField field2, JButton b, JButton b2, JFrame frame, JFrame frame2) {
this.frame = frame;
this.frame2 = frame2;
this.b = b;
this.b2 = b2;
this.field = field;
this.field2 = field2;
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX() + " " + e.getY());
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source.equals(b)) {
frame.setVisible(false);
frame2.setVisible(true);
}
if (source.equals(b2)) {
if (!a.contains(field2.getText())) {
error++;
frame2.repaint();
}
field2.setText("");
}
}
public void paintComponent(Graphics g) {
if (error == 1)
g.drawLine(10, 270, 500, 270);
if (error == 2) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
}
if (error == 3) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
}
if (error > 3) {
Font font = new Font("Verdana", Font.BOLD, 25);
g.setFont(font);
g.drawString("GAME OVER", 270, 170);
}
}
}

random number generator jframe

Working on a side project for a professor that wants a random number generator.
The program in its current state leaves a lot to be desired but I think I'm on the right track. However, I am stuck when it comes to using the text field, passing that data to my random number equation, and displaying it. Basically, the program isn't waiting for the user input to the text field.
We never made it past OOP in school so I need to pull out the big guns (you guys).
Here is what I am working with currently. The last bit at the end is the part that I am having issue with.
package RandomButton;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
public class GUI extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField ClassSize;
private JLabel label;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI() {
int x;
int max;
String strMax;
String strX;
Scanner kb = new Scanner(System.in);
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);
//Text field code
textField = new JTextField();
textField.setText("1");
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setBounds(10, 143, 414, 35);
contentPane.add(textField);
textField.setColumns(10);
//Randomize button code
JButton btnNewButton = new JButton("Randomize!");
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 40));
btnNewButton.setBounds(10, 196, 414, 54);
contentPane.add(btnNewButton);
//Label code
label = new JLabel();
label.setFont(new Font("Tahoma", Font.PLAIN, 70));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(10, 11, 414, 103);
contentPane.add(label);
//math code
Random num = new Random();
strMax = textField.getText();
max = Integer.parseInt(strMax);
x = num.nextInt(max) + 1;
strX = String.valueOf(x);
label.setText(strX);
}
}
What you need is to add an ActionListener, see javadoc here
Simple modification of the code, without bigger discussion, is to move up the code that simulate random numbers...
//Randomize button code
JButton btnNewButton = new JButton("Randomize!");
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 40));
btnNewButton.setBounds(10, 196, 414, 54);
contentPane.add(btnNewButton);
// the listener
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random num = new Random();
String strMax = textField.getText();
int max = Integer.parseInt(strMax);
int x = num.nextInt(max) + 1;
String strX = String.valueOf(x);
label.setText(strX);
}
} );

Open and Display File Data in JTextArea

I have run into a problem with what I thought was a pretty simple program. I simply want to use a GUI, click and button to display data in a text file. I seem to be close but am running into a problem I do not understand. If I leave the code the way it is here I get the error that highScores is not declared (symbol not found) for line 72. But if I try to declare highSchores the I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown" for line 69. Any idea what I am doing wrong and how I can fix it?
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class tetrisScores extends JFrame{
private JPanel contentPanel;
private JButton btnSearch;
private JButton btnLoad;
private JButton btnSort;
private JRadioButton firstSort;
private JRadioButton secondSort;
private JTextField searchInput;
private JTextArea output;
private String[] highScores;
private void add (Container con, Component widget, int left, int top, int width, int height) //creates variables for bounds
{
widget.setBounds(left, top, width, height); //sets setBounds to created variables
con.add(widget); //tells program container to use widget's bounds
}
tetrisScores()
{
contentPanel=(JPanel)getContentPane();
contentPanel.setLayout(null);
btnLoad = new JButton("Load File");
add(contentPanel, btnLoad, 10, 10, 360, 40);
searchInput = new JTextField("");
add(contentPanel, searchInput, 10, 60, 240, 40);
btnSearch = new JButton("Search");
add(contentPanel, btnSearch, 260, 60, 110, 40);
firstSort = new JRadioButton("Bubble Sort");
add(contentPanel, firstSort, 20, 110, 110, 40);
firstSort = new JRadioButton("Linear Sort");
add(contentPanel, firstSort, 140, 110, 110, 40);
btnSearch = new JButton("Sort");
add(contentPanel, btnSearch, 260, 110, 110, 40);
output = new JTextArea("");
add(contentPanel, output, 10, 160, 360, 150);
output.setEditable(false);
setTitle("High Scores");
setSize(500,500);
setLocation(new Point (150,150));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
btnLoad.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent add)
{
OpenFile();
for (int j = 0; j<10;j++)
{
output.append(highScores[j] + "/n");
}
}
});
}
public String [] OpenFile() throws IOException
{
FileReader fr = new FileReader("tetrishighscore.txt");
BufferedReader scoreReader = new BufferedReader (fr);
int numbLines = 10;
String[] textData = new String [numbLines];
int i;
for (i=0; i < numbLines; i++)
{
textData[i] = scoreReader.readLine();
}
scoreReader.close();
return textData;
}
public static void main (String [] args)
{
new tetrisScores();
}
}
The OpenFile() method throws an IOException, but it is never caught.
I have made some modifications:
highScores could be declared as a List (so you don't have to give the number of lines in advance)
the Exception is caught
the line break character is "\n", not "/n"
Some more modifications could be made, but this should work:
import java.awt.Component;
import java.awt.Container;
import java.util.List;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class TetrisScores extends JFrame {
private JPanel contentPanel;
private JButton btnSearch;
private JButton btnLoad;
private JButton btnSort;
private JRadioButton firstSort;
private JRadioButton secondSort;
private JTextField searchInput;
private JTextArea output;
private List<String> highScores = new ArrayList<>();
private void add(Container con, Component widget, int left, int top, int width, int height) // creates variables for
// bounds
{
widget.setBounds(left, top, width, height); // sets setBounds to created variables
con.add(widget); // tells program container to use widget's bounds
}
TetrisScores() {
contentPanel = (JPanel) getContentPane();
contentPanel.setLayout(null);
btnLoad = new JButton("Load File");
add(contentPanel, btnLoad, 10, 10, 360, 40);
searchInput = new JTextField("");
add(contentPanel, searchInput, 10, 60, 240, 40);
btnSearch = new JButton("Search");
add(contentPanel, btnSearch, 260, 60, 110, 40);
firstSort = new JRadioButton("Bubble Sort");
add(contentPanel, firstSort, 20, 110, 110, 40);
firstSort = new JRadioButton("Linear Sort");
add(contentPanel, firstSort, 140, 110, 110, 40);
btnSearch = new JButton("Sort");
add(contentPanel, btnSearch, 260, 110, 110, 40);
output = new JTextArea("");
add(contentPanel, output, 10, 160, 360, 150);
output.setEditable(false);
setTitle("High Scores");
setSize(500, 500);
setLocation(new Point(150, 150));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent add) {
try {
OpenFile();
for (int j = 0; j < highScores.size(); j++) {
output.append(highScores.get(j) + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void OpenFile() throws IOException {
FileReader fr = new FileReader("tetrishighscore.txt");
BufferedReader scoreReader = new BufferedReader(fr);
String line;
while((line = scoreReader.readLine()) != null) {
highScores.add(line);
}
scoreReader.close();
}
public static void main(String[] args) {
new TetrisScores();
}
}

i've tried to create a Java login script but my code doesnt work

i've been trying to make a login script in java, i've been looking around and i found an error that people said that my script doesnt work because i didn't use Scanners, i now added those but my script still does not work what can be the error?
package random;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import random.*;
public class core extends Window
{
/**
*
*/
private static final long serialVersionUID = 1L;
;
public static void main(String[] args) {
new Window().Create();
}
public void sqlstatement()
{
}
public static void succesfullLogin()
{
System.out.println("it worked!");
}
}
this is the Window.java file
package random;
import java.awt.ActiveEvent;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.*;
public class Window extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public void Gridbags(int height,int width)
{
}
public void Create()
{
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.setSize(600,500);
frame.setResizable(false);
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JLabel usernamelbl = new JLabel("username:");
JLabel passwordlbl = new JLabel("Password:");
JTextField userinput = new JTextField(10);
JTextField password = new JTextField(10);
password.setText("password");
userinput.setText("root");
usernamelbl.setBounds(160, 160, 80, 25);
userinput.setBounds(225, 160, 160, 25);
passwordlbl.setBounds(160, 190, 80, 25);
password.setBounds(225, 190, 160, 25);
login.setBounds(160, 230, 80, 25);
login.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
boolean active = true;
String mysqluser = "root";
String mysqlPass = "password";
#SuppressWarnings("resource")
Scanner userscan = new Scanner(userinput.getText());
// Scanner passScan = new Scanner(password.getText());
if(userscan.equals(mysqluser))
// && passScan.equals(mysqlPass))
{
if(active = true) {
core.succesfullLogin();
}
}
}
});
panel.add(password);
panel.add(login);
panel.add(userinput);
panel.add(usernamelbl);
panel.add(passwordlbl);
panel.add(logout);
frame.add(panel);
// frame.pack();
frame.setVisible(true);
}
}
userscan is of type Scanner. Comparing it with an string will always return false.
Simply comparing the strings worked for me.
if(userinput.getText().equals(mysqluser)&& password.getText().equals(mysqlPass))

repaint() method not calling paintComponent()

for my program I currently want to use the open button to open a JFileChooser and select an image and then draw it on the JPanel on the left side of the applet, I know that the file is being retrieved but when i go to repaint the graphics context nothing happens. Thanks in advance.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
public class FinalProject390 {
public static void main(String[] args) {
createAndShowGUI();
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Final Project");
f.setSize(1025, 520);
f.add(new GraphicsPanel());
f.add(new MainPanel());
f.setVisible(true);
}
}
class MainPanel extends JPanel implements ActionListener {
JButton openButton = new JButton("Open");
JButton newButton = new JButton("New");
JButton saveButton = new JButton("Save");
JButton saveAsButton = new JButton("Save As");
JButton drawLineButton = new JButton("Draw Line");
JButton drawRectangleButton = new JButton("Draw Rectangle");
JButton drawOvalButton = new JButton("Draw Oval");
JButton drawArcButton = new JButton("Draw Arc");
JButton extractPixelDataButton = new JButton("Extract Pixel Data");
JButton convoluteButton = new JButton("Convolute");
JTextField xPosStartField = new JTextField("x-Position Start");
JTextField yPosStartField = new JTextField("y-Position Start");
JTextField xPosEndField = new JTextField("x-Position End");
JTextField yPosEndField = new JTextField("y-Position End");
JTextField angleStartField = new JTextField("Angle Start");
JTextField angleSizeField = new JTextField("Angle Size");
public MainPanel() {
openButton.setBounds(660, 50, 100, 30);
openButton.addActionListener(this);
newButton.setBounds(780, 50, 100, 30);
saveButton.setBounds(900, 50, 100, 30);
drawLineButton.setBounds(660, 110, 160, 30);
drawRectangleButton.setBounds(840, 110, 160, 30);
drawOvalButton.setBounds(660, 155, 160, 30);
drawArcButton.setBounds(840, 155, 160, 30);
extractPixelDataButton.setBounds(660, 220, 160, 30);
convoluteButton.setBounds(840, 220, 160, 30);
xPosStartField.setBounds(660, 280, 100, 30);
yPosStartField.setBounds(660, 320, 100, 30);
xPosEndField.setBounds(660, 380, 100, 30);
yPosEndField.setBounds(660, 420, 100, 30);
angleStartField.setBounds(900, 280, 100, 30);
angleSizeField.setBounds(900, 320, 100, 30);
setLayout(null);
setBackground(Color.green);
setBounds(641, 0, 370, 480);
add(openButton);
add(newButton);
add(saveButton);
add(drawLineButton);
add(drawRectangleButton);
add(drawOvalButton);
add(drawArcButton);
add(extractPixelDataButton);
add(convoluteButton);
add(xPosStartField);
add(yPosStartField);
add(xPosEndField);
add(yPosEndField);
add(angleStartField);
add(angleSizeField);
}
#Override
public void actionPerformed(ActionEvent e) {
javax.swing.JFileChooser fileChooser = new JFileChooser();
BufferedImage bin = null, bi = null;
GraphicsPanel gPanel = new GraphicsPanel();
fileChooser.setCurrentDirectory(new File(System
.getProperty("user.home")));
int result = fileChooser.showOpenDialog(null);
if (result == javax.swing.JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: "
+ selectedFile.getAbsolutePath());
try {
bin = ImageIO.read(new File(selectedFile.getAbsolutePath()));
} catch (IOException e1) {
e1.printStackTrace();
}
gPanel.setImg(bin);
}
}
}
class GraphicsPanel extends JPanel {
BufferedImage bi = null, bin = null;
public GraphicsPanel() {
setLayout(null);
setBackground(Color.blue);
setSize(640, 480);
setLocation(0, 0);
}
public void setImg(BufferedImage b) {
this.bi = b;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi, 0, 0, null);
}
}
This looks like a homework assignment, so rather than an outright answer with code, instead please consider the following:
In your method createAndShowGUI() you instantiate a GraphicsPanel object and add it to a JFrame
In your actionPerformed() method, you instantiate another GraphicsPanel object (which is never added to the JFrame) and you call setImage().
Your image does not display because the GraphicsPanel control that has been added to your JFrame is not the same GraphicsPanel control that you set the image on.
I hope this will be enough to help you fix your code.

Categories