how do I create a public String from a JTextArea? - java

I'm creating an encryption method that takes input from a JTextArea, and I'm getting an error saying:
'Illegal modifier for parameter input; only final is permitted'
I have gone through many documentation websites and other articles, and I have found nothing. Here is my near-complete code:
Package lake. RAMBIT7;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import net.miginfocom.swing.MigLayout;
public class RAMBIT7 implements ActionListener {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RAMBIT7 window = new RAMBIT7();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public RAMBIT7() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setSize(800, 600); //1024x768, 800x600
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("RAMBIT7 Encryption Software 1.0.0");
frame.setResizable(false);
/**
* 'Encrypt' and 'Decrypt' buttons
*/
JButton encrypt = new JButton("Encrypt");
encrypt.addActionListener(this);
JButton decrypt = new JButton("Decrypt");
decrypt.addActionListener(this);
/**
* JMenuBar
*/
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu help = new JMenu("Help");
JMenuItem about = new JMenuItem("About");
JMenuItem license = new JMenuItem("License");
JMenuItem close = new JMenuItem("Exit");
file.add(close);
help.add(about);
help.add(license);
bar.add(file);
bar.add(help);
about.addActionListener(this);
license.addActionListener(this);
close.addActionListener(this);
frame.setJMenuBar(bar);
/**
* Text and input related stuff
*/
frame.getContentPane().setLayout(new MigLayout("", "[69px][71px,grow][]", "[23px][35.00][200px][][grow][]"));
frame.getContentPane().add(encrypt, "cell 0 0,alignx left,aligny top");
frame.getContentPane().add(decrypt, "cell 2 0,alignx right,aligny top");
JLabel lblCopyTextIn = new JLabel("Copy Text in here.");//JLabel
frame.getContentPane().add(lblCopyTextIn, "cell 1 1");
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, "cell 0 2 3 1,grow");
JTextArea textArea = new JTextArea();//JTextArea
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
JLabel lblOutputTextIn = new JLabel("Output text in RAMBIT7 encryption");//JLabel
frame.getContentPane().add(lblOutputTextIn, "cell 1 3");
JScrollPane scrollPane_1 = new JScrollPane();
frame.getContentPane().add(scrollPane_1, "cell 0 4 3 1,grow");
JTextArea textArea_1 = new JTextArea();//JTextArea_1
scrollPane_1.setViewportView(textArea_1);
textArea_1.setEditable(false);
textArea_1.setLineWrap(true);
JLabel lblRambitEncryptionMethod = new JLabel("RAMBIT7 Encryption Method"); //JLabel
frame.getContentPane().add(lblRambitEncryptionMethod, "cell 1 5");
public String input_0 = textArea.getText();//Error here
}
#Override
public void actionPerformed(ActionEvent e) {
String a = e.getActionCommand();
if(a.equalsIgnoreCase("encrypt")) {
System.out.println("Begin RAMBIT7 encryption.");
encryptRAMBIT7(input);
} else if(a.equalsIgnoreCase("decrypt")) {
System.out.println("Begin RAMBIT7 decryption.");
decryptRAMBIT7(input);
} else if(a.equalsIgnoreCase("about")) {
System.out.println("Opening Program Specs...");
JOptionPane.showMessageDialog(frame, "RAMBIT7 v1.0.0");
System.out.println("Program Specs Closed.");
} else if(a.equalsIgnoreCase("license")) {
System.out.println("Opening License...");
JOptionPane.showMessageDialog(frame, "You may not sell this program or say that any part of the code is yours.");
System.out.println("License closed.");
} else if(a.equalsIgnoreCase("exit")) {
System.out.println("Why, oh WHY CRUEL WORLD does that person have to close me?! I'm\na living thing too! Or maybe I'm an emotionless pig! NOOOOOOOO!");
System.exit(3);
}
}
}

You need to re-think your structure a bit:
Even if you could get the String out of the JTextArea on creation time, it would not help you one bit. When the JTextArea changes its display text, that String will not change since Strings are invariants.
Likewise a String field would not help, not unless it was dynamically bound to the JTextArea via a DocumentListener or something similar.
Instead make the JTextArea a private field and extract its String when needed.
If other classes need the text, then create a public method public String getTextAreaText() and return the text held by the JTextArea in that method.
public class RAMBIT7 implements ActionListener {
private JFrame frame;
private JTextArea textarea = new JTextArea();
// ....
private void initialize() {
// .....
// JTextArea textArea = new JTextArea();//JTextArea
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
and elsewhere:
if(a.equalsIgnoreCase("encrypt")) {
System.out.println("Begin RAMBIT7 encryption.");
encryptRAMBIT7(textarea.getText());

You just can't use the public keyword inside a method. Visibility modifiers are used to determine what members of each object can be accessed from outside, by other objects or classes. Things you declare inside of a method are not members of a class, but rather things that only exist in that method, so visibility modifiers make no sense there.

public String input_0 = textArea.getText();
Any variable declared inside a function is local to that function. Outside world don't know about that variable but the function itself. hence, access modifier public, private or protected are not applicable to local instance variable, such as input_0 here which is local to initialize(). Again, this code, is inside initialize() function, which is responsible for initializing your GUI component, creating them and adding them to the container, user input is yet to happen, so reading the text content of textArea is meaning less.

Related

Why won't main method print anything?

I've been trying to figure out what's wrong with my code. I have to build a GUI and there are no errors. The program builds successfully, but no GUI pops up. So in the main method, I commented out the GUI programming and added a simple System.out.println("hello"); but it does the same thing, i.e., it builds successfully, but does not print anything. Can someone please tell me what's wrong? Thanks!
/*
* To change this license header, choose License Headers in Project
Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import java.awt.*;
import javax.swing.*;
import java.awt.Event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI extends JFrame {
GridLayout g = new GridLayout(5, 2);
private JLabel baseIn = new JLabel("Base Input");
private JLabel heightIn = new JLabel("Height Input");
private JTextField base = new JTextField();
private JTextField height = new JTextField();
private JTextField area = new JTextField();
private JButton calc = new JButton("Calculate Area");
public GUI() {
super("Triangle Area Calculator");
setSize(500, 300);
setLayout(g);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener((ActionListener) this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5*bInput*hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
public static void main(String[] args) {
/*JFrame frame = new JFrame();
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);*/
System.out.println("hello world");
}
}
First, going back to the basic code...
public class GUI extends JFrame {
//...
public static void main(String[] args) {
JFrame frame = new JFrame();
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);
}
}
Will fail, because you can't add a window based component to a window. As a general rule of thumb, you should avoid overriding JFrame (and other top level containers) directly and favour something less complex, like JPanel
public class GUI extends JPanel {
//...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GUI());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Next...
calc.addActionListener((ActionListener) this);
The fact that you need to perform a cast in order to get the code to work is a clear sign that something else is wrong and this is likely to cause a runtime error and crash your program. Perhaps you should start by having a read of How to write a Action Listener and How to Use Buttons, Check Boxes, and Radio Buttons to get a better understanding of how the API works
This is further supported by making use of the #Override annotation, which should be used when ever you "think" you're implementing or overriding existing functionality...
#Override
public void actionPerformed(ActionEvent e) {
//...
}
This would then fail to compile, as you're not implementing any existing functionality. This functionality is described by the ActionListener interface which you are not implementing.
While you could implement this interface directly, I prefer to avoid doing so, as it exposes functionality that other classes shouldn't have access to and you run the risk of building a "god" method, which is never a good idea.
Instead, I prefer to make use of Java's Anonymous Classes, which provides a much better means for isolating functionality to single use case, for example...
calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
});
Runnable Example
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JPanel {
GridLayout g = new GridLayout(5, 2);
private JLabel baseIn = new JLabel("Base Input");
private JLabel heightIn = new JLabel("Height Input");
private JTextField base = new JTextField();
private JTextField height = new JTextField();
private JTextField area = new JTextField();
private JButton calc = new JButton("Calculate Area");
public GUI() {
setLayout(g);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
});
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GUI());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Netbeans properties...
Now, if all that still fails to net you a result, you need to make sure that your GUI class is configured as the "Main class".
Start by right clicking the Netbeans project node and select "Properties" (it's at the bottom).
From the "Projects Properties", select "Run" from the "Build" options down the left side.
Make sure that your GUI class is marked as the "Main Class", use "Browse" to find it if it's not
Try this
calc.addActionListener(new OptionButtonHandler());
I added one optionButtonHandler class which implements ActionListener. I checked on my IDE and I was able to get the area of the triangle.
private class OptionButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
}
In your case, GUI is not an ActionListener, so that will fail.
Can you right click on the file with the main method in Netbeans, you should see the run option there, select it. This would allow you set your main method. After this, subsequent clicks on the Green play Button should work.
You do not need to cast your Frame class to an ActionListener. Instead, make it implement the ActionListener interface and your code for the button action should work. But in future, its better to add logic to detect what component triggered the action.
I don't know, but how can you write this :
calc.addActionListener((ActionListener) this);
Your object (this) is a JFrame, you should add 'implements ActionListener' first, or create a separate implementation ...
Next error, you do :
GUI one = new GUI();
frame.getContentPane().add(one);
GUI extends JFrame, its a JFrame, you can't add a JFrame in another one !
I tested with add of 'implements ActionListener' and it runs, but some errors remains ;)
Copy/paste needs wisdom, hum ^^
EDIT
this code is not perfect (and very ugly) but it works for your example :
package com.mead.helmet.core;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class GUI extends JPanel implements ActionListener {
public static void main(final String[] args) {
JFrame frame = new JFrame("Triangle Area Calculator");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
GUI one = new GUI();
frame.getContentPane().add(one);
frame.pack();
frame.setVisible(true);
System.out.println("hello world");
}
GridLayout g = new GridLayout(5, 2);
private final JLabel baseIn = new JLabel("Base Input");
private final JLabel heightIn = new JLabel("Height Input");
private final JTextField base = new JTextField();
private final JTextField height = new JTextField();
private final JTextField area = new JTextField();
private final JButton calc = new JButton("Calculate Area");
public GUI() {
super();
setSize(500, 300);
setLayout(g);
add(baseIn);
add(heightIn);
add(base);
add(height);
add(area);
add(calc);
area.setEditable(false);
calc.addActionListener((ActionListener) this);
setVisible(true);
}
/**
*
* #param event
*/
#Override
public void actionPerformed(final ActionEvent e) {
try {
double bInput = Integer.valueOf(base.getText());
double hInput = Integer.valueOf(height.getText());
double aOutput = 0.5 * bInput * hInput;
area.setText("Area of your triangle is: " + aOutput);
} catch (NumberFormatException n) {
System.out.println(n.getMessage());
}
}
}

MouseListener inside loop isnt using updated variable values

I want to first apologize for my poor English.
I made some JPanels which I'm putting inside one JPanel and this last JPanel I'm putting it in one JScrollPane, each Jpanel has some JLabels that have text inside them. I've done that and everything is working until now, then I added a mouseListener to System.out.print the text inside the JLabels.
The texts are different, but on the console I'm getting the same text,
here's my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testa;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.event.*;
public class Test extends JFrame{ //see https://www.javatpoint.com/java-naming-conventions
private JLabel[] titles;
private JLabel[] descriptions;
private JPanel [] panels;
private JScrollPane jScrollPane1;
private JPanel bigPanel;
private final static int NUM_OF_RESULTS =10;
String identifier ;
String title;
String authors;
String resume;
String references;
public Test() throws IOException {
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000,500);
//jScrollPane1.setSize(1000, 500); and layouts. see following comments
bigPanel = new JPanel();
bigPanel.setBounds(30, 90, 950, 400);
//set layout to
GridLayout layout = new GridLayout(NUM_OF_RESULTS, 0);
bigPanel.setLayout(layout);
jScrollPane1 = new JScrollPane(bigPanel);
jScrollPane1.setBounds(30, 90, 950, 400);
getContentPane().add(jScrollPane1);
requetezQuery();
//pack(); //see https://stackoverflow.com/questions/22982295/what-does-pack-do
setVisible(true); //set visible typically comes last
}
public void requetezQuery() {
int actual=0;
titles = new JLabel[NUM_OF_RESULTS];
descriptions = new JLabel[NUM_OF_RESULTS];
panels = new JPanel[NUM_OF_RESULTS];
for(int i = 0; i<NUM_OF_RESULTS; i++){
title = "Title "+i;
resume = "Description "+i ;
titles[i]= new JLabel();
descriptions[i]= new JLabel();
panels[i]= new JPanel();
panels[i].setPreferredSize(new Dimension(250, 50));
panels[i].setLayout(new FlowLayout()); //FlowLayout is default for JPanel
titles[i].setText(title);
descriptions[i].setText(resume.substring(0, Math.min(resume.length(), 100))+"...");
titles[i].setForeground(Color.blue);
descriptions[i].setForeground(Color.black);
titles[i].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
System.out.println(title);
}
});
panels[i].add(titles[i]);
panels[i].add(descriptions[i]);
bigPanel.add(panels[i],i, 0);
}
}
public static void main(String args[]) throws IOException{
new Test();
}
}
I believe your reference to title refers to the last created title at runtime. What you can do to fix this is instead of printing the title, print the labels text. Try putting this inside of your mouseClicked method.
JLabel obj = (JLabel) me.getSource();
System.out.println(obj.getText());
Your mouse click event reference variable from outer class:
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
System.out.println(title); // This `title` is a reference of Test.title variable
}
});
So all of your MouseAdapter references the same title (whose value is replaced by each loop) -> System.out.println all prints the same last title.

Java / Blue j cant select anything else other than 1st item in combo box

Im using blue j for a project which is a java framework (not through my choice)
I cant get it to print out what seat they have chosen because it always selects the 1st value A1.
Its a seating plan that displays and image and a combo box in which you can select your seat for exmaple A1 and upon the button click save it prints out the seat you have chosen in a dialog box.
Help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.lang.String;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class SeatingChart extends JFrame
{
private JLabel infoLabel;
// Get the list of field names, used for ordering.
String[] ordering =
{"A1","A2","A3","A4",
"B1","B2","B3","B4",
"C1","C2","C3","C4","D1","D2","D3","D4"};
String chosenSeat;
String ticket= "1" ;
int ticketValue = Integer.parseInt(ticket);
/**
* Main method for starting the system from a command line.
*/
public static void main(String[] args)
{
SeatingChart gui = new SeatingChart();
}
/**
* Create a visual aspect and display its GUI on screen.
*/
public SeatingChart()
{
super("Choose Your seats");
makeFrame();
}
/**
* Quit function: quit the application.
*/
private void quit()
{
System.exit(0);
}
private void play()
{
JFrame frames = new JFrame("Sample frame");
frames.setSize(400, 400);
frames.setVisible(false);
frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(frames, "You have chosen the seat " +chosenSeat);
}
/**
* Create the complete application GUI.
*/
public void makeFrame ()
{
// the following makes sure that our application exits when
// the user closes its window
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) getContentPane();
contentPane.setBorder(new EmptyBorder(6, 10, 10, 10));
makeMenuBar(); //calls the menu bar method
// Create the center with image
JPanel centerPane = new JPanel();
{
centerPane.setLayout(new BorderLayout(8, 8));
JLabel image = new JLabel(new ImageIcon("SeatingChart.jpg"));
image.setSize (20,20);//dont work
centerPane.add(image, BorderLayout.NORTH);
centerPane.setBackground(Color.WHITE);
infoLabel = new JLabel("Please use the chart to select where you would like to sit and save it. Do this for how many tickets you have");
infoLabel.setHorizontalAlignment(SwingConstants.CENTER);
centerPane.add(infoLabel, BorderLayout.CENTER);
}
contentPane.add(centerPane, BorderLayout.EAST);
JPanel leftPane = new JPanel();
{
leftPane.setLayout(new BorderLayout(8, 8));
// Set up components for ordering the list
JPanel orderingPanel = new JPanel();
orderingPanel.setLayout(new BorderLayout());
orderingPanel.add(new JLabel("Choose your seat:"), BorderLayout.NORTH);
// Create the combo box.
JComboBox formatList = new JComboBox(ordering);
orderingPanel.add(formatList, BorderLayout.CENTER);
leftPane.add(orderingPanel, BorderLayout.NORTH);
formatList.setSelectedIndex(0);
chosenSeat = formatList.getSelectedItem().toString();
//formatList.removeItemAt(formatList.getSelectedIndex());
}
contentPane.add(leftPane, BorderLayout.CENTER);
JPanel toolbar = new JPanel();
{
toolbar.setLayout(new GridLayout(1, 0));
JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
play();
}
});
toolbar.add(button);
button = new JButton("Next");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// This button would allow the use to go to the next step
}
});
toolbar.add(button);
}
contentPane.add(toolbar, BorderLayout.SOUTH);
// building is done - arrange the components
pack();
// place this frame at the center of the screen and show
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(d.width/2 - getWidth()/2, d.height/2 - getHeight()/2);
setVisible(true);
}
/**
* Create the main frame's menu bar.
*/
private void makeMenuBar()
{
final int SHORTCUT_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu menu;
JMenuItem item;
// create the File menu
menu = new JMenu("File");
menubar.add(menu);
item = new JMenuItem("Quit");
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK));
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
quit();
}
});
menu.add(item);
}
}
You set the chosenSeat field immediately after creating the formatList combo box. At that moment, the user has not even had a chance to pick a seat and seat A1 is selected by default. If you set chosenSeat in the play method, it should reflect the seat picked by your user.
I think the new JFrame in the play method - as already mentioned by mKorbel - is not needed, since you can use the application frame (this) as the parent component for the call to the JOptionPane.showMessageDialog method:
private void play() {
// todo: frames is not needed.
//JFrame frames = new JFrame("Sample frame");
//frames.setSize(400, 400);
//frames.setVisible(false);
//frames.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chosenSeat = formatList.getSelectedItem().toString();
// todo: use the application frame as the parent.
//JOptionPane.showMessageDialog(frames, "You have chosen the seat " + chosenSeat);
JOptionPane.showMessageDialog(this, "You have chosen the seat " + chosenSeat);
}

How to reference JFrame

I have a problem which is most likely "simple" however I can't figure it out. I am trying to reference my current JFrame so that I can dispose of it, and create a new one, thus "resetting" the program, however I and having trouble figuring out how to reference the JFrame, I have tried, super, this and getParent(), but none of the seem to work. Thanks for any / all help. ^^
Here is my code:
Main Class, just sets up the Jframe and calls the class that creates everything:
public static void main(String args[]) {
JFrame window = new JFrame();
Director director = new Director(window, args);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.pack();
window.setVisible(true);
}
}
Class the creates everything:
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Director extends JFrame implements CollisionListener {
private BrickWall wall;
private JLabel gameTitle, gameScore, gameLives;
private JPanel controlPanel;
private JButton reset, quit;
private JRadioButton hard, normal, easy;
private int score = 6, lives = 5;
private ButtonGroup difficulty;
public Director(JFrame window, String[] args) {
window.getContentPane().add(makeGamePanel(), BorderLayout.CENTER);
window.getContentPane().add(gameControlPanel(), BorderLayout.NORTH);
}
public void collisionDetected(CollisionEvent e) {
wall.setBrick(e.getRow(), e.getColumn(), null);
}
private JComponent makeGamePanel() {
wall = new BrickWall();
wall.addCollisionListener(this);
wall.buildWall(3, 6, 1, wall.getColumns(), Color.GRAY);
return wall;
}
// Reset method I'm trying to dispose of the JFrame in.
private void reset() {
JFrame frame = new JFrame();
frame.getContentPane().add(makeGamePanel(), BorderLayout.CENTER);
frame.getContentPane().add(gameControlPanel(), BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private JComponent gameControlPanel() {
// CONTROL PANEL PANEL!
controlPanel = new JPanel();
gameTitle = new JLabel("Brickles");
gameScore = new JLabel("Score:" + " " + score);
gameLives = new JLabel("Lives:" + " " + lives);
reset = new JButton("Reset");
quit = new JButton("Quit");
hard = new JRadioButton("Hard", false);
normal = new JRadioButton("Normal", true);
easy = new JRadioButton("Easy", false);
difficulty = new ButtonGroup();
difficulty.add(hard);
difficulty.add(normal);
difficulty.add(easy);
controlPanel.setLayout(new GridLayout(4, 2));
controlPanel.add(gameTitle);
controlPanel.add(gameScore);
controlPanel.add(hard);
controlPanel.add(gameLives);
controlPanel.add(normal);
controlPanel.add(reset);
controlPanel.add(easy);
controlPanel.add(quit);
// Action Listener, where I'm caling the reset method.
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset();
}
});
return controlPanel;
}
}
You can refer to the "outer this" from a nested class with the following syntax:
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Director.this.reset();
}
});
Yes, you can refer to the outer class by specifying it with the class name as noted in DSquare's good answer (1+ to it), but I urge you not to fling JFrame's at the user as you're program is trying to do. I recommend:
Instead of opening and closing multiple JFrames, use only one JFrame as the main application's window.
If you need helper windows, such as modal windows to get critical information that is absolutely needed, before the program can progress, use modal dialogs such as JDialogs or JOptionPanes.
If you need to swap GUI's, instead of swapping JFrames, swap "views" inside the JFrame via a CardLayout.
Gear your code towards creating these JPanel views and not JFrames as it will make your Swing GUI's much more flexible and portable.

change jlabel with method

I am writing a small program that converts files, and I wanted to have a box pop up that asks the user to please wait while the program loops through and converts all the relevant files, but I am running into a small problem. The box that pops up should have a JLabel and a JButton, while the user is "waiting" I wanted to display a message that says please wait, and a disabled "OK" JButton, and then when its finished I wanted to set the text of the JLabel to let them know that It successfully converted their files, and give them a count of how many files were converted. (I wrote a method called alert that sets the text of the label and enables the button.) The problem is That while the program is running, the box is empty, the Label and the Button are not visible, when it finishes, label appears with the final text that I want and the button appears enabled. I am not sure exactly what is going on, I tried changing the modifiers of the JLabel and JButton several times but I cant seem to get it to work correctly. Here is the code for the box that pops up, any help is greatly appricated.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PleaseWait extends javax.swing.JFrame{
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel("Please Wait while I convert your files");
private static JButton OK = new JButton("OK");
public PleaseWait(){
// creates the main window //
JFrame mainWindow = new JFrame();
mainWindow.setTitle("Chill For A Sec");
mainWindow.setSize(width, height);
mainWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
mainWindow.add(mainLayout);
// sets everything visible //
mainWindow.setVisible(true);
}
public static void alert(){
OK.setEnabled(true);
String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + total + " files Converted");
}
}
Okay here's the issue. You are extending the JFrame . That means your class IS a JFrame.
When you create the PleaseWait frame you don't do anything to it. This is the empty box you are seeing. You are instead creating a different JFrame in your constructor. Remove your mainWindow and instead just use this. Now all of your components will be added to your PleaseWait object. That should fix your blank box issue.
You need an application to create your frame first. This is a simple example of such application.
import javax.swing.UIManager;
import java.awt.*;
public class Application {
boolean packFrame = false;
//Construct the application
public Application() {
PleaseWait frame = new PleaseWait();
//Validate frames that have preset sizes
//Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
}
else {
frame.validate();
}
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
frame.convert();
}
//Main method
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
e.printStackTrace();
}
new Application();
}
}
You have to slightly modify your frame to add controls to the content pane. You can do some work after frame is created, then call alert.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PleaseWait extends JFrame {
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel();
private static JButton OK = new JButton("OK");
BorderLayout borderLayout1 = new BorderLayout();
JPanel contentPane;
int count;
public PleaseWait(){
contentPane = (JPanel)this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(width, height));
this.setTitle("Chill For A Sec");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
OK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
contentPane.add(mainLayout);
}
public void convert(){
count = 0;
for (int i = 0; i <10; i++){
System.out.println("Copy "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
count++;
}
alert();
}
public void alert(){
OK.setEnabled(true);
// String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + count + " files Converted");
}
}

Categories

Resources