Accessing Jtextfield from outer action listener - java

I am trying to access JTextField text namely 'searchBox' from outer action listener created in outer class.
GUI:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyFrame extends JFrame
{
public int stat1_var;
public int stat2_var;
public int stat3_var;
public String stat4_var;
private int statX_bound = 50;
private int statY_bound = 280;
public String url;
/*
* #param width The width of the frame.
* #param height The height of the frame.
* #param title The title of the frame.
*/
public MyFrame(int width, int height, String title, int stat1_var, int stat2_var, int stat3_var, String stat4_var)
{
this.stat1_var = stat1_var; //threading var
this.stat2_var = stat2_var; //spiders var
this.stat3_var = stat3_var; //results var
this.stat4_var = stat4_var; //other var
initUI(width, height, stat1_var, stat2_var, stat3_var, stat4_var);
this.setSize(width,height); //set frame size
this.setTitle(title); //set frame title
this.setVisible(true); //set visible
this.setResizable(false); //disable resizable frame
}
private void initUI(int width, int height, int stat1_var, int stat2_var, int stat3_var, String stat4_var)
{
ImageIcon ic = new ImageIcon("background.jpg");//background image source
JDesktopPane dp = new JDesktopPane(); //create desktop pane
JLabel lbl = new JLabel(ic); //create label
JPanel transparentPanel = new JPanel(); //create a JPanel
lbl.setBounds(0, 0, width, height); //bounds for the background
transparentPanel.setOpaque(false);
transparentPanel.setBounds(0, 0, width, height);//bounds for the panel
transparentPanel.setLayout(null);//default layout
setLayeredPane(dp);
JTextField searchBox = new JTextField("http://", 40); //keyword search box
searchBox.setEditable(true);
searchBox.setBounds(250, 130, 300, 25);
searchBox.setToolTipText("Enter domain to be crawled");
transparentPanel.add(searchBox);
searchBox.setActionCommand("url");
searchBox.addActionListener(new listeners(this));
JButton crawlBtn = new JButton("Crawl"); // search button
crawlBtn.addActionListener(new listeners(this));
crawlBtn.setBounds(555, 130, 80, 25);
crawlBtn.setActionCommand("crawl");
crawlBtn.setToolTipText("crawl domain");
transparentPanel.add(crawlBtn);//end
JTextField searchBox2 = new JTextField("", 40); //crawl url search box
searchBox2.setEditable(true);
searchBox2.setBounds(250, 160, 300, 25);
searchBox2.setToolTipText("enter your keywords");
transparentPanel.add(searchBox2); //end
JButton jumpBtn = new JButton("Jump!"); // search button
jumpBtn.addActionListener(new listeners(this));
jumpBtn.setBounds(555, 160, 80, 25);
jumpBtn.setActionCommand("crawl");
jumpBtn.setToolTipText("crawl domain");
transparentPanel.add(jumpBtn);//end
JLabel stat1 = new JLabel("Threads: " + stat1_var); //stat labels
stat1.setToolTipText("Threads");
stat1.setBounds(statX_bound, statY_bound, 300, 25);
statY_bound += 25; //place the label one place below
transparentPanel.add(stat1);
JLabel stat2 = new JLabel("Spiders: " + stat2_var); //stat labels
stat2.setToolTipText("Spiders");
stat2.setBounds(statX_bound, statY_bound, 300, 25);
statY_bound += 25; //place the label one place below
transparentPanel.add(stat2);
JLabel stat3 = new JLabel("Results found: " + stat3_var);
stat3.setToolTipText("Results found");
stat3.setBounds(statX_bound, statY_bound, 300, 25);
statY_bound += 25; //place the label one place below
transparentPanel.add(stat3);
JLabel stat4 = new JLabel("Status: " + stat4_var);
stat4.setToolTipText("Status");
stat4.setBounds(statX_bound, statY_bound, 300, 25);
statY_bound += 25; //place the label one place below
transparentPanel.add(stat4);
dp.add(lbl,new Integer(50));
dp.add(transparentPanel,new Integer(350));
setDefaultCloseOperation(EXIT_ON_CLOSE); //close the app if close button clicked
} //end constructor
public void paint(Graphics g)
{
super.paint(g); //call superclass' paint method
g.setColor(Color.BLACK);
} //end method paint
} //end class MyFrame
And this is the outer class listener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.io.File;
public class listeners implements ActionListener
{
private MyFrame myframe;
public listeners(MyFrame myframe){
this.myframe = myframe;
//String source = e.getSource();
}
public void actionPerformed(ActionEvent event) {
String action = event.getActionCommand();
if (action == "url")
{
myframe.url = searchBox.getText(); //<----- I am trying to obtain this from the gui
}
}
}
I am trying to obtain the searchBox text value(arrows above) to the url variable from GUI class. Can anyone please help me with this? I have been looking for the solution for 3 hours now...

Use getSource to obtain a reference to the JTextField
JTextField searchBox = (JTextField) e.getSource();

Declare your JTextField variable as instance var. (outside of initUI method) and create getter method. Then call it in your listeners class:
myframe.url = myframe.getSearchBox().getText();;
Other sidenotes:
Name your classes properly. Names of classes begin with upper cases.
Do not extend your class with JFrame if you are not going to override some methods or to define new methods.
DON'T use absolute positioning for swing components! Use proper layout manager.

Related

I keep getting NullPointerException in my second class in like 90(marked) when im trying to run my 3rd class (Wallpaper) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I keep getting that error no matter what variables I change, and I was wondering If I might of messed up somewhere along my lines.
This is my main class
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class menu implements ActionListener {
/*public static JCheckBox check;
public static JCheckBox check1;*/
public static JPanel panel;
public static JFrame frame;
public static JButton Wallpaper;
public static JButton tile;
public static JButton trim;
public static void main(String[] args) {
panel = new JPanel();
frame = new JFrame();
frame.setSize(350, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(555,318);
frame.add(panel);
Border dash = BorderFactory.createLineBorder(Color.BLACK);
//create the MainMenu title
JLabel MainMenu = new JLabel(" MainMenu");
MainMenu.setBounds(30, 10, 80, 25);
MainMenu.setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.black));
MainMenu.setForeground(Color.black);
panel.add(MainMenu);
//creates the wallpaper button
Wallpaper = new JButton("Wallpaper");
Wallpaper.setBounds(20,40,100,25);
Wallpaper.addActionListener(new menu());
panel.add(Wallpaper);
//creates the tile button
tile = new JButton("Tile");
tile.setBounds(20,70,100,25);
panel.add(tile);
//creates the trim button
trim = new JButton("Trim");
trim.setBounds(20,100,100,25);
trim.addActionListener(new menu());
panel.add(trim);
panel.setLayout(null);
frame.setVisible(true);
//i was playing around do not mind that :)
/* check = new JCheckBox();
check.setBounds(130, 30, 100, 25);
panel.add(check);
check1 = new JCheckBox();
check1.setBounds(130, 50, 100, 25);
panel.add(check1);
check2 = new JCheckBox();
check2.setBounds(130, 70, 100, 25);
panel.add(check2);
*/
}
#Override
public void actionPerformed(ActionEvent e) {
//makes the Trim button actully do something
if (e.getSource() == Wallpaper){
WallpaperCalculator.Wallpaper();
}
if (e.getSource() == trim) {
TrimCalculator.Trim();
}
}
}
Here is my second class where I keep getting the error on line 90
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TrimCalculator implements ActionListener {
private static JTextField lengthText;
private static JTextField widthText;
private static JButton button;
private static JLabel total;
private static JLabel walls;
private static JTextField wallsText;
public static void Trim() {
//creates the gui it self
JPanel panel = new JPanel();
panel.setLayout(null);
JFrame frame = new JFrame();
frame.setSize(350,300);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocation(555,318);
frame.add(panel);
//sets the title
JLabel title = new JLabel();
title.setBounds(10, 20, 300, 25);
title.setText("Trim Calculator");
panel.add(title);
//sets the lengths title
JLabel length = new JLabel();
length.setBounds(10,55,300,25);
length.setText("Length Input");
panel.add(length);
//creates a field for the length text input
lengthText = new JTextField();
lengthText.setBounds(120,55,90,25);
panel.add(lengthText);
//creates a width text label
JLabel width = new JLabel();
width.setBounds(10,80,300,25);
width.setText("Width Input");
panel.add(width);
//created a field for the width text input
widthText = new JTextField();
widthText.setBounds(120,80,90,25);
panel.add(widthText);
//makes a field to set a text box so people can see where the total will be
JLabel totalAmount = new JLabel();
totalAmount.setBounds(10,150,300,25);
totalAmount.setText("Total Amount:");
panel.add(totalAmount);
//makes a field to present the answer
total = new JLabel();
total.setBounds(125, 150, 90,25);
panel.add(total);
walls = new JLabel("Walls");
walls.setBounds(10,105,90,25);
panel.add(walls);
wallsText = new JTextField();
wallsText.setBounds(120,105,90,25);
panel.add(wallsText);
//makes a button to get the two lengths and start the multiplication process
button = new JButton();
button.setBounds(10,130,90,25);
button.setText("Find");
button.setForeground(Color.CYAN);
button.addActionListener(new TrimCalculator());
panel.add(button);
frame.setVisible(true);
}
//gets the button and changes it from a string into a int so it can be calculated
#Override
public void actionPerformed(ActionEvent e) {
String lengthAmount = lengthText.getText();<— line that the error is throwing me to
String widthAmount = widthText.getText();
String wallAmount = wallsText.getText();
//changes the strings into a double
double length = Double.parseDouble(lengthAmount);
double width = Double.parseDouble(widthAmount);
double wallz = Double.parseDouble(wallAmount);
// adds the two sides together
double sides = length + width;
//multiplies sides1 by 2 to get preTotal
double preTotal = sides * 2;
//gets total2 and divides it by 8 to get the final total
double Total = preTotal/8;
//times the total by the walls given.
double newTotal = Total * wallz;
//changes the double variable newTotal into a string
String f = String.valueOf(newTotal);
//makes the button actually print the amount of trim needed
if (e.getSource() == button){
total.setText(f+" ft");
}
}
}
And here is my last class that's where I click the button to try to get an answer but it send me to TrimCalculator for some reason?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WallpaperCalculator implements ActionListener {
private static JTextField lengthText2;
private static JTextField heightText;
private static JButton button2;
private static JLabel total;
public static void Wallpaper() {
JPanel panel = new JPanel();
panel.setLayout(null);
JFrame frame = new JFrame();
frame.setSize(350,300);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocation(555,318);
frame.add(panel);
//sets the title
JLabel title = new JLabel();
title.setBounds(10, 20, 300, 25);
title.setText("Wallpaper Calculator");
title.setForeground(Color.BLUE);
panel.add(title);
//sets the lengths title
JLabel length = new JLabel();
length.setBounds(10,55,300,25);
length.setText("Length Input");
panel.add(length);
//creates a field for the length text input
lengthText2 = new JTextField();
lengthText2.setBounds(120,55,90,25);
panel.add(lengthText2);
//creates a width text label
JLabel height = new JLabel();
height.setBounds(10,80,300,25);
height.setText("height Input");
panel.add(height);
//created a field for the width text input
heightText = new JTextField();
heightText.setBounds(120,80,90,25);
panel.add(heightText);
//makes a field to set a text box so people can see where the total will be
JLabel totalAmount = new JLabel();
totalAmount.setBounds(10,150,300,25);
totalAmount.setText("Total Amount:");
panel.add(totalAmount);
//makes a field to present the answer
total = new JLabel();
total.setBounds(125, 150, 90,25);
panel.add(total);
//makes a button to get the two lengths and start the multiplication process
button2 = new JButton();
button2.setBounds(10,130,90,25);
button2.setText("Find");
button2.setForeground(Color.blue);
button2.addActionListener(new TrimCalculator());
panel.add(button2);
frame.setVisible(true);
}
//gets the button and changes it from a string into a int so it can be calculated
#Override
public void actionPerformed(ActionEvent c) {
String lengthAm = lengthText2.getText();
String heightAm = heightText.getText();
//changes the strings into a double
double length = Double.parseDouble(lengthAm);
double height = Double.parseDouble(heightAm);
// multiplies the two sides
double sidesTotal = length * height;
//divides the sidesTotal to get Total
double Total = sidesTotal / 40;
System.out.println(Total);
//changes the double variable newTotal into a string
String f = String.valueOf(Total);
//makes the button actually print the amount of trim needed
if (c.getSource() == button2){
total.setText(f+" ft");
}
}
}
Thank you again for the help!
I figured it out, but for those that do get the NullPointerException error, if you have many class, then quote/* */ one class all the way out and see where it might be duplicated, if you ever copy and paste code.

Can I add JLabels into an array? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I want to clean up my code and I was wondering if I could put these JLabels into an ArrayList.
This is going to be used for a do-while loop in which the collisions of my player will be checked.
Below is the GamePane class. This code has the moving player in it and has the code for the collisions. This is where I create the ArrayList:
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
/**
* This class Holds the game pane that has the moving player. It also contains
* the GamePane
*
* #author 602052004
*
*/
public class GamePane extends JPanel implements ActionListener, KeyListener {// *change GamePane to GamePane
// This is were the game screen is made and the player is created.
private static final long serialVersionUID = 1L;
JLabel player = new JLabel();
JLabel finish = new JLabel();
// This is were the JLabels for the walls are created
//JLabel wall1 = new JLabel();
//ArrayList<JLabel> array = new ArrayList<>();
ArrayList<JLabel> array = new ArrayList<>();
array.add(wall1);
JLabel wall1 = new JLabel();
JLabel wall2 = new JLabel();
JLabel wall3 = new JLabel();
JLabel wall4 = new JLabel();
JLabel wall5 = new JLabel();
JLabel wall6 = new JLabel();
JLabel wall7 = new JLabel();
JLabel wall8 = new JLabel();
JLabel wall9 = new JLabel();
JLabel wall10 = new JLabel();
JLabel wall11 = new JLabel();
JLabel wall12 = new JLabel();
JLabel wall13 = new JLabel();
JLabel wall14 = new JLabel();
JLabel wall15 = new JLabel();
JLabel wall16 = new JLabel();
JLabel wall17 = new JLabel();
JLabel wall18 = new JLabel();
JLabel wall19 = new JLabel();
JLabel wall20 = new JLabel();
JLabel wall21 = new JLabel();
JLabel wall22 = new JLabel();
JLabel wall23 = new JLabel();
JLabel wall24 = new JLabel();
int playerSpeed = 5;
int FPS = 40;
private final Set<Integer> keys = new HashSet<>();
// The keys set holds the keys being pressed
public static void main(String[] args) {
// Open the GUI window
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// Create a new object and
// run its go() method
new GamePane().go();
}
});
}
GamePane() {
// Run the parent class constructor
super();
// Allow the panel to get focus
setFocusable(true);
// Don't let keys change the focus
}
/**
* The frame that shows my game. It contains the game frame which holds my
* JPanel GameStage and ButtonPane.
*/
protected void go() {
setLayout(new CardLayout());
// Setup the window
JFrame GameFrame = new JFrame();
// Add this panel to the window
GameFrame.setLayout(new CardLayout());
GameFrame.add(this, "main");
GameFrame.setContentPane(this);
// Set's the window properties
GameFrame.setTitle("main");
GameFrame.setSize(800, 600);
GameFrame.setLocationRelativeTo(null);
GameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GameFrame.setVisible(true);
GameFrame.add(new ButtonPane(GameFrame), "buttons");
// Creates the new JPanel that will hold the game.
JPanel gamestage = new JPanel();
gamestage.setBackground(Color.darkGray);
GameFrame.add(gamestage, "game");
gamestage.setLayout(null);
// *Move the setup of the player and the timer under the walls
// Get a sample of collisions going so that i can do it over the weekend
// Setup the movable box
player.setBounds(25, 25, 20, 20);
player.setVisible(true);
player.setBackground(Color.cyan);
// Opaque makes the background visible
player.setOpaque(true);
// Setup the key listener
addKeyListener(this);
// Null layout allows moving objects!!!
gamestage.add(player);
// Set the timer
Timer tm = new Timer(1000 / FPS, this);
tm.start();
wall1.setBounds(10, 15, 10, 480);
wall1.setVisible(true);
wall1.setBackground(Color.white);
wall1.setOpaque(true);
gamestage.add(wall1);
wall2.setBounds(10, 10, 755, 10);
wall2.setVisible(true);
wall2.setBackground(Color.white);
wall2.setOpaque(true);
gamestage.add(wall2);
// wall3.setBounds(x, y, width, height);
wall3.setBounds(10, 100, 100, 10);
wall3.setVisible(true);
wall3.setBackground(Color.white);
wall3.setOpaque(true);
gamestage.add(wall3);
wall4.setBounds(100, 60, 10, 40);
wall4.setVisible(true);
wall4.setBackground(Color.white);
wall4.setOpaque(true);
gamestage.add(wall4);
wall5.setBounds(70, 60, 35, 10);
wall5.setVisible(true);
wall5.setBackground(Color.white);
wall5.setOpaque(true);
gamestage.add(wall5);
wall6.setBounds(60, 100, 10, 90);
wall6.setVisible(true);
wall6.setBackground(Color.white);
wall6.setOpaque(true);
gamestage.add(wall6);
wall7.setBounds(10, 230, 60, 10);
wall7.setVisible(true);
wall7.setBackground(Color.white);
wall7.setOpaque(true);
gamestage.add(wall7);
wall8.setBounds(60, 230, 10, 65);
wall8.setVisible(true);
wall8.setBackground(Color.white);
wall8.setOpaque(true);
gamestage.add(wall8);
wall9.setBounds(60, 290, 125, 10);
wall9.setVisible(true);
wall9.setBackground(Color.white);
wall9.setOpaque(true);
gamestage.add(wall9);
wall10.setBounds(175, 300, 10, 45);
wall10.setVisible(true);
wall10.setBackground(Color.white);
wall10.setOpaque(true);
gamestage.add(wall10);
wall11.setBounds(130, 335, 45, 10);
wall11.setVisible(true);
wall11.setBackground(Color.white);
wall11.setOpaque(true);
gamestage.add(wall11);
wall12.setBounds(10, 335, 70, 10);
wall12.setVisible(true);
wall12.setBackground(Color.white);
wall12.setOpaque(true);
gamestage.add(wall12);
wall13.setBounds(10, 435, 60, 10);
wall13.setVisible(true);
wall13.setBackground(Color.white);
wall13.setOpaque(true);
gamestage.add(wall13);
wall14.setBounds(10, 385, 230, 10);
wall14.setVisible(true);
wall14.setBackground(Color.white);
wall14.setOpaque(true);
gamestage.add(wall14);
wall15.setBounds(60, 390, 10, 50);
wall15.setVisible(true);
wall15.setBackground(Color.white);
wall15.setOpaque(true);
gamestage.add(wall15);
wall16.setBounds(230, 290, 10, 155);
wall16.setVisible(true);
wall16.setBackground(Color.white);
wall16.setOpaque(true);
gamestage.add(wall16);
wall17.setBounds(10, 485, 750, 10);
wall17.setVisible(true);
wall17.setBackground(Color.white);
wall17.setOpaque(true);
gamestage.add(wall17);
wall18.setBounds(70, 180, 60, 10);
wall18.setVisible(true);
wall18.setBackground(Color.white);
wall18.setOpaque(true);
gamestage.add(wall18);
wall19.setBounds(120, 180, 10, 55);
wall19.setVisible(true);
wall19.setBackground(Color.white);
wall19.setOpaque(true);
gamestage.add(wall19);
}
public boolean areColliding(JLabel a, JLabel b) {
return a.getBounds().intersects(b.getBounds());
}
/**
* this method makes the player move. It takes the players speed and subtracts
* or adds the player speed to the current position of the player. It also
* figures out were the player is at currently aswell.
*
* #param arg0
*/
#Override
public void actionPerformed(ActionEvent arg0) {
// Move up if W is pressed
if (keys.contains(KeyEvent.VK_W)) {
player.setLocation(player.getX(), player.getY() - playerSpeed);
}
// Move right if D is pressed
if (keys.contains(KeyEvent.VK_D)) {
player.setLocation(player.getX() + playerSpeed, player.getY());
}
// Move down if S is pressed
if (keys.contains(KeyEvent.VK_S)) {
player.setLocation(player.getX(), player.getY() + playerSpeed);
}
// Move left if A is pressed
if (keys.contains(KeyEvent.VK_A)) {
player.setLocation(player.getX() - playerSpeed, player.getY());
}
// Check for collisions
if (areColliding(wall1, player)) {
// Reposition the target
int newX = (int) (25);
int newY = (int) (25);
player.setLocation(newX, newY);
}else
// Check for collisions
if (areColliding(wall2, player)) {
// Reposition the target
int newX = (int) (25);
int newY = (int) (25);
player.setLocation(newX, newY);
}else
// Check for collisions
if (areColliding(wall3, player)) {
// Reposition the target
int newX = (int) (25);
int newY = (int) (25);
player.setLocation(newX, newY);
}
}
#Override
public void keyPressed(KeyEvent e) {
// Add the key to the list
// of pressed keys
if (!keys.contains(e.getKeyCode())) {
keys.add(e.getKeyCode());
}
}
#Override
public void keyReleased(KeyEvent e) {
// Remove the key from the
// list of pressed keys
keys.remove((Integer) e.getKeyCode());
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Below is the ButtonPane class. It controls the screen switching. The two screens that switch are the GamePane and the ButtonPane. The GamePane contains the walls and all the code to run the game. The ButtonPane class is as follows:
/**
* This pane contains the button and sets up the button pane
*/
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonPane extends JPanel {
private JButton startBTN;// Calls the JButton
JFrame game;
public ButtonPane(JFrame g) {
game = g;
setLayout(new GridBagLayout());
setBackground(Color.gray);// Sets the menu stages color blue
startBTN = new JButton("Start");// Creates a new button
add(startBTN);// Adds the button on the startStage
startBTN.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (game.getContentPane().getLayout() instanceof CardLayout) {
CardLayout layout = (CardLayout) getParent().getLayout();
layout.show(game.getContentPane(), "game");
}
}
});
}
}
You could initialize an ArrayList with JLabels in a for-loop like this:
ArrayList<JLabel> array = new ArrayList<>();
for (int i = 0, i < numberOfLabels, i++)
{
array.add(new JLabel());
}
To retrieve an element from the ArrayList, just use:
array.get(elementIndex);
If you want to put already created JLabels into an ArrayList, you can do:
array.add(labelObject);
for each JLabel object you want in the ArrayList.
You can use ArrayList to store your JLabel
But you will have struggle when add an already-exist JLabel to your arraylist (because, when you got it back you don't know which index to access).
The better way to keep track of your JLabel is to create a map, you often need to specify text for your JLabel so you can use it to identify your JLabel:
Map<String, JLabel> map = new HashMap<>();
map.put(your-label-name, new JLabel(your-label-name));
If you know your label is going to duplicated, then add prefix to your JLabel key.

How to use two Layout Managers simultaneously?

I'm completely new to Layout Managers, but i want to create a table. I have a window that is set.Resizable(false) and doesn't have a layout manager, with 1 image and two text items placed using coordinates. I would like to keep these items using absolute layout, while creating my table underneath (using GridLayout I assume)
If it helps, here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Canvas;
import javax.swing.JFrame;
import java.awt.Dimension;
class DisplayItems extends JFrame implements ActionListener
{
//text
private static JLabel TechforTeachingTitle;
private static JLabel TechforTeachingSubTitle;
//images
private static JLabel Logo;
//buttons
private static final int BUTTON_WIDTH = 100;
private static final int BUTTON_HEIGHT = 30;
public static void main(String[] args)
{
DisplayItems ProjectFrame = new DisplayItems();
ProjectFrame.setVisible(true); // Display the frame
}
public DisplayItems( )
{
//font properties
Font TitleFont = new Font("Serif", Font.BOLD, 80);
Font subFont = new Font("Serif", Font.BOLD, 40);
// set the frame properties
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Inventory system");
setSize(900, 700);
setLocationRelativeTo(null);
setResizable(false);
// set the content pane properties
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(Color.decode("#FDF3E7"));
//set text properties
TechforTeachingTitle = new JLabel();
TechforTeachingTitle.setText("Tech For Teaching");
TechforTeachingTitle.setBounds(200, 30, 900, 95);
TechforTeachingTitle.setForeground(Color.decode("#8f8f8f"));
TechforTeachingTitle.setFont(TitleFont);
contentPane.add(TechforTeachingTitle);
TechforTeachingSubTitle = new JLabel();
TechforTeachingSubTitle.setText("View items");
TechforTeachingSubTitle.setBounds(400, 90, 900, 95); //left, top, length, height
TechforTeachingSubTitle.setForeground(Color.decode("#799177")); //7E8F7C (slightly less green)
TechforTeachingSubTitle.setFont(subFont);
contentPane.add(TechforTeachingSubTitle);
//set image properties
Logo = new JLabel(new ImageIcon("SmallLogo.png"));
Logo.setBounds(10,20,179,178); // //left, top, width, height
contentPane.add(Logo);
Logo.setVisible(true);
// Logo.addMouseListener(new MouseAdapter()
// {
// public void mouseClicked(MouseEvent e) {
// setVisible(false);
//
// FinalProject FP = new FinalProject();
// FP.setVisible(true);
// }
// });
//set button properties
}
public void actionPerformed(ActionEvent event) // Actions
{
}
}

Compiler Warning class uses unchecked or unsafe operations

My code is currently working fine, but whenever i compile, i get the Warning
C:\Users\etc\etc\FinalProject\AddItem.java uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details.
Should I do something about it, and if so, what? if my debugging is right, it appears to be caused by the content pane properties.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Canvas;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.io.*;
class AddItem extends JFrame implements ActionListener
{
//text
private static JLabel TechforTeachingTitle;
private static JLabel TechforTeachingSubTitle;
//images
private static JLabel Logo;
//buttons
private JButton submitButton;
private static final int BUTTON_WIDTH = 100;
private static final int BUTTON_HEIGHT = 30;
//variables
public static void main(String[] args)
{
AddItem ProjectFrame = new AddItem();
ProjectFrame.setVisible(true); // Display the frame
//for combobox
//new AddItem().setVisible(true);
}
public AddItem ( )
{
//font properties
Font TitleFont = new Font("Serif", Font.BOLD, 80);
Font subFont = new Font("Serif", Font.BOLD, 40);
// set the frame properties
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Inventory system");
setSize(900, 700);
setLocationRelativeTo(null);
setResizable(true);
// set the content pane properties
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(Color.decode("#FDF3E7"));
//set text properties
TechforTeachingTitle = new JLabel();
TechforTeachingTitle.setText("Tech For Teaching");
TechforTeachingTitle.setBounds(200, 30, 900, 95);
TechforTeachingTitle.setForeground(Color.decode("#8f8f8f"));
TechforTeachingTitle.setFont(TitleFont);
contentPane.add(TechforTeachingTitle);
TechforTeachingSubTitle = new JLabel();
TechforTeachingSubTitle.setText("Add an item");
TechforTeachingSubTitle.setBounds(400, 90, 900, 95); //left, top, length, height
TechforTeachingSubTitle.setForeground(Color.decode("#799177")); //7E8F7C (slightly less green)
TechforTeachingSubTitle.setFont(subFont);
contentPane.add(TechforTeachingSubTitle);
//set image properties
Logo = new JLabel(new ImageIcon("SmallLogo.png"));
Logo.setBounds(10,20,179,178); // //left, top, width, height
contentPane.add(Logo);
Logo.setVisible(true);
Logo.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
setVisible(false);
FinalProject FP = new FinalProject();
FP.setVisible(true);
}
});
//set button properties
//for combobox
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(null); //ONLY PROBLEM WITH THIS IS GETTING THE SCREEN TO APPEAR AT CORRECT SIZE
String[] values = {"Computer", "Monitor", "Keyboard"};
final JComboBox b = new JComboBox(values);
b.setEditable(true);
add(b);
b.setBounds(300, 300, 100, 50); //this works
add(b);
submitButton = new JButton("Submit");
submitButton.setBounds(700,600, BUTTON_WIDTH, BUTTON_HEIGHT);
submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String item=b.getSelectedItem().toString();
}
});
contentPane.add(submitButton);
//pack(); //not quite sure what this is for, but it makes the window tiny, so i commented it out
setLocationRelativeTo(null); //positions window center on screen
}
public void actionPerformed(ActionEvent event) // Actions
{
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
}
}
you get the warning here I think:
final JComboBox b = new JComboBox(values);
to avoid this you have the following possibilities:
add SupressWarning above the JComboBox
#SuppressWarnings("unchecked")
final JComboBox b = new JComboBox(values);
or add SupressWarning above your method
#SuppressWarnings("rawtypes")
public AddItem ( )
or my favourite add the generic:
final JComboBox<Object> b = new JComboBox<Object>(values);

Java, BorderLayout.CENTER, getting the width and height of the JPanel

I am using Swing and AWT (for the listeners) to make a small program. I have a problem concerning getting the size of my JPanel (the class named Chess).
My Layout:
public class Main extends JFrame implements MouseListener, ActionListener{
Chess chessPanel = new Chess ();
JButton newGameButton = new JButton ("New Game");
JButton loadGameButton = new JButton ("Load Game");
JButton saveGameButton = new JButton ("Save Game");
JButton exitButton = new JButton ("Exit");
public static void main (String [] args) {
new Main();
}
Main () {
super ("Chess");
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setSize(dim);
setLocation(0,0);
setUndecorated(true);
chessPanel.addMouseListener(this);
add(chessPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
newGameButton.addActionListener(this);
loadGameButton.addActionListener(this);
saveGameButton.addActionListener(this);
exitButton.addActionListener(this);
buttonPanel.add(newGameButton);
buttonPanel.add(loadGameButton);
buttonPanel.add(saveGameButton);
buttonPanel.add(exitButton);
add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
// ... Code ...
}
As you can see by the code, I have one JPanel in the CENTER, which takes nearly all the screen. In the bottom I have another JPanel (SOUTH), which has a row of buttons.
What I need is the size that the JPanel in the CENTER takes. When I call the getWidth(), getHeight() or getBounds() methods inherited from JPanel, they all return 0, because of the BorderLayout.
Any idea how to get the real values?
PS: The screen always takes up the entire screen, and will never be resized, if that helps.
You're likely calling getWidth before the JPanel has been rendered, and so it will be 0. The solution is to get the size after rendering, for instance after pack() or setVisible(true) has been called on the root container that holds this JPanel.
Also, I recommend against calling setSize() on anything since most of the standard layout managers observe the preferred size of a component, not the size, and when you call pack() telling the layout managers to do their thing, the set sizes are usually ignored. You may want to make your JPanel that is in the center set its own size by overriding its setPreferredSize method if it needs to be a certain size. Then let the JFrame and its held containers set the bet fit size based on the their layout managers when you call pack.
e.g.,
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
Chess chessPanel = new Chess();
JButton newGameButton = new JButton("New Game");
JButton loadGameButton = new JButton("Load Game");
JButton saveGameButton = new JButton("Save Game");
JButton exitButton = new JButton("Exit");
public static void main(String[] args) {
new Main();
}
Main() {
super("Chess");
add(chessPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(newGameButton);
buttonPanel.add(loadGameButton);
buttonPanel.add(saveGameButton);
buttonPanel.add(exitButton);
System.out.printf("chessPanel Size before rendering: %s%n", chessPanel.getSize());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(buttonPanel, BorderLayout.SOUTH);
pack();
System.out.printf("chessPanel Size after rendering: %s%n", chessPanel.getSize());
setLocationRelativeTo(null);
setVisible(true);
}
// ... Code ...
}
#SuppressWarnings("serial")
class Chess extends JPanel {
private static final int CHESS_WIDTH = 600;
private static final int CHESS_HEIGHT = CHESS_WIDTH;
private static final int MAX_ROW = 8;
private static final int MAX_COL = 8;
private static final Color LIGHT_COLOR = new Color(240, 190, 40);
private static final Color DARK_COLOR = new Color(180, 50, 0);
#Override
public Dimension getPreferredSize() {
return new Dimension(CHESS_WIDTH, CHESS_HEIGHT);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int panelWidth = getWidth();
int panelHeight = getHeight();
int sqrWidth = panelWidth / MAX_ROW;
int sqrHeight = panelHeight / MAX_COL;
for (int row = 0; row < MAX_ROW; row++) {
for (int col = 0; col < MAX_COL; col++) {
Color c = (row % 2 == col % 2) ? LIGHT_COLOR : DARK_COLOR;
g.setColor(c);
int x = (row * panelWidth) / MAX_ROW;
int y = (col * panelHeight) / MAX_COL;
g.fillRect(x, y, sqrWidth, sqrHeight);
}
}
}
}

Categories