The code below works as such:
User clicks the run button
Program reads the file from designated location
Program removes content from <script> </script>, including tags themselves
Program returns edited text into JTextArea called textArea
I've tried making it a global variable since it's in two different classes. The run down is that once the user clicks the "run button", the text area initialised in the GUI class will update.
public class GUI{
static JTextArea textArea;
public GUI() {
JFrame frame = new JFrame();
textArea = new JTextArea(5,30);
JButton runButton = new JButton("Remove JS");
JButton importButton = new JButton("Import File");
JPanel panel = new JPanel();
runButton.addActionListener(new runApp());
runButton.setBounds(100, 100, 100, 80);
importButton.addActionListener(new importFile());
importButton.setBounds(100, 100, 80, 60);
panel.setBorder(BorderFactory.createEmptyBorder(300, 300 , 150, 150));
panel.setLayout(new GridLayout(0, 1));
panel.add(textArea);
panel.add(runButton);
panel.add(importButton);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("JavaScript Extractor");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new GUI();
}
}
class runApp implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
RemoveScript run = new RemoveScript();
try {
File fileObject = new File("C:\\Users\\coker\\Documents\\readJS.txt");
Scanner reader = new Scanner(fileObject);
while(reader.hasNextLine()) {
String output = reader.nextLine();
textArea.setText(run.removeScript(output));
}
reader.close();
}catch(FileNotFoundException e) {
System.out.println("An error has occured.");
e.printStackTrace();
}
}
}
3 options:
Make your listener class an inner class of GUI, then it will have access to all fields of it's outer class (no need for static in that case)
Keep the 2 classes completely separate, and pass a reference to the text field to the listener (e.g. via constructor parameter).
access the static field via GUI.textArea
Related
Hi I'm working on a program and I faced a problem when I choose some settings from JDialog then click "ok", which is that the setting didn't save but come back to the original settings.
PS : I'm not English speaker so maybe you observe some mistakes in my text above.
picture
enter image description here
class DrawingSettingWindow extends JDialog {
public DrawingSettingWindow() {
this.setTitle("Drawing Setting Window");
this.setSize(550, 550);
this.setLocationRelativeTo(null);
this.setModal(true);
this.setLayout(new GridLayout(4, 1));
JLabel selectColorText = new JLabel("Select Drawing Color");
colorsList = new JComboBox(colors);
JPanel panel1 = new JPanel();
panel1.add(selectColorText);
panel1.add(colorsList);
add(panel1);
JLabel selectStyleText = new JLabel("Select Drawing Style");
JPanel panel2 = new JPanel();
normal = new JRadioButton("Normal");
normal.setSelected(true);
filled = new JRadioButton("Filled");
ButtonGroup bg = new ButtonGroup();
bg.add(normal);
bg.add(filled);
panel2.add(selectStyleText);
panel2.add(normal);
panel2.add(filled);
add(panel2);
JButton ok = new JButton("OK");
add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
this.pack();
this.setVisible(true);
}
The information is there, you just have to extract it from the dialog after the user is done using it. I would give the code above at least two new methods, one a public getColor() method that returns colorsList.getSelectedItem();, the color selection of the user (I'm not sure what type of object this is, so I can't show the method yet). Also another one that gets the user's filled setting, perhaps
public boolean getFilled() {
return filled.isSelected();
}
Since the dialog is modal, you'll know that the user has finished using it immediately after you set it visible in the calling code. And this is where you call the above methods to extract the data.
In the code below, I've shown this in this section: drawingSettings.setVisible(true);
// here you extract the data
Object color = drawingSettings.getColor();
boolean filled = drawingSettings.getFilled();
textArea.append("Color: " + color + "\n");
textArea.append("Filled: " + filled + "\n");
}
For example (see comments):
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class UseDrawingSettings extends JPanel {
private JTextArea textArea = new JTextArea(20, 40);
private DrawingSettingWindow drawingSettings;
public UseDrawingSettings() {
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new ShowDrawSettings()));
setLayout(new BorderLayout());
add(new JScrollPane(textArea));
add(topPanel, BorderLayout.PAGE_START);
}
private class ShowDrawSettings extends AbstractAction {
public ShowDrawSettings() {
super("Get Drawing Settings");
}
#Override
public void actionPerformed(ActionEvent e) {
if (drawingSettings == null) {
Window win = SwingUtilities.getWindowAncestor(UseDrawingSettings.this);
drawingSettings = new DrawingSettingWindow(win);
}
drawingSettings.setVisible(true);
// here you extract the data
Object color = drawingSettings.getColor();
boolean filled = drawingSettings.getFilled();
textArea.append("Color: " + color + "\n");
textArea.append("Filled: " + filled + "\n");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
UseDrawingSettings mainPanel = new UseDrawingSettings();
JFrame frame = new JFrame("UseDrawingSettings");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class DrawingSettingWindow extends JDialog {
private static final String TITLE = "Drawing Setting Window";
private JComboBox<String> colorsList;
private JRadioButton normal;
private JRadioButton filled;
// not sure what colors is, but I'll make it a String array for testing
private String[] colors = {"Red", "Orange", "Yellow", "Green", "Blue"};
public DrawingSettingWindow(Window win) {
super(win, TITLE, ModalityType.APPLICATION_MODAL);
// this.setTitle("Drawing Setting Window");
this.setSize(550, 550); // !! this is not recommended
this.setLocationRelativeTo(null);
this.setModal(true);
this.setLayout(new GridLayout(4, 1));
JLabel selectColorText = new JLabel("Select Drawing Color");
colorsList = new JComboBox(colors);
JPanel panel1 = new JPanel();
panel1.add(selectColorText);
panel1.add(colorsList);
add(panel1);
JLabel selectStyleText = new JLabel("Select Drawing Style");
JPanel panel2 = new JPanel();
normal = new JRadioButton("Normal");
normal.setSelected(true);
filled = new JRadioButton("Filled");
ButtonGroup bg = new ButtonGroup();
bg.add(normal);
bg.add(filled);
panel2.add(selectStyleText);
panel2.add(normal);
panel2.add(filled);
add(panel2);
JButton ok = new JButton("OK");
add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
this.pack();
// this.setVisible(true); // this should be the calling code's responsibility
}
public Object getColor() {
return colorsList.getSelectedItem();
}
public boolean getFilled() {
return filled.isSelected();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Foo");
}
}
Side notes:
I've changed your class's constructor to accept a Window parameter, the base class for JFrame, JDialog, and such, and have added a call to the super's constructor. This way, the dialog is a true child window of the calling code (or you can pass in null if you want it not to be).
I recommend not making the dialog visible within its constructor. It is the calling code's responsibility for doing this, and there are instances where the calling code will wish to not make the dialog visible after creating it, for example if it wanted to attach a PropertyChangeListener to it before making it visible. This is most important for modal dialogs, but is just good programming practice.
I didn't know the type of objects held by your combo box, and so made an array of String for demonstration purposes.
My code is messy so you might not be able to follow it, but I am trying to make a YouTube to MP3 converter.
It opens up a JPanel for the user to type in the YouTube URL. When I try to get the text from the JTextField, I had to make my method return a value so i can use the value in my other class, and I think that is causing my code not to work.
If someone could help me out, that would be great. I am really new to Java coding and I'm not sure why I chose such a complicated program, but I almost have it done. This is the last part then the cosmetics and cleaning up the code starts :)
My code:
public class Bank_Statement extends JFrame {
// width & height of window
private static final int WIDTH = 500;
private static final int HEIGHT = 500;
public static final Keys text = null;
final ActionListener convertButtonHandler = null;
static Scanner console = new Scanner(System.in);
static String M1;
public static String Bank_Statement1() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
JPanel buttonPane = new JPanel();
buttonPane.add(skinny);
JButton skinny2 = new JButton("Paste");
JPanel buttonPane2 = new JPanel();
buttonPane2.add(skinny2);
JTextField text;
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
JTextField text2 = new JTextField("----------------------------------------WAIT LIST----------------------------------------");
JPanel textPane2 = new JPanel();
textPane2.add(text2);
JFrame frame = new JFrame("Youtube Converter");
frame.setSize(WIDTH, HEIGHT);
frame.add(textPane, BorderLayout.WEST);
frame.add(buttonPane2, BorderLayout.CENTER);
frame.add(buttonPane, BorderLayout.EAST);
frame.add(textPane2, BorderLayout.PAGE_END);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return text.getText();
}
public static void main(String[] args) {
Bank_Statement recObject = new Bank_Statement();
}
}
class ButtonListener implements ActionListener {
ButtonListener() {}
public void actionPerformed(ActionEvent e) {
WebDriver driver = new HtmlUnitDriver();
driver.get("http://www.youtubeinmp3.com/");
String J = Bank_Statement.Bank_Statement1();
driver.findElement(By.id("video")).sendKeys(J + Keys.ENTER);
driver.findElement(By.id("download")).click();
String L= driver.getCurrentUrl();
System.out.println(L);
try {
Runtime.getRuntime().exec(new String[] {"cmd", "/c","start chrome " + L});
} catch (IOException e1) {
e1.printStackTrace();
}
driver.quit();
}
}
return text.getText();
Will be executed right after the Windows appears. It does not wait until the user enters some text.
Try the following:
public class Bank_Statement extends JFrame {
private JTextField text;
public static Bank_Statement bank_statement;
public Bank_Statement() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
...
frame.setVisible(true);
}
public String getText(){
return text.getText();
}
public static void main(String[] args) {
bank_statement = new Bank_Statement();
}
}
class ButtonListener implements ActionListener {
ButtonListener() {}
public void actionPerformed(ActionEvent e) {
String J = Bank_Statement.bank_statement.getText();
System.out.println(J);
}
}
I removed a few lines in the middle to keep it compact. I hope it is clear, ask otherwise. The design is quite bad, but I didn't want to change to mutch of your code.
Well, first of all, I assume this is your constructor for the Bank_Statement class
public static String Bank_Statement1() {
//create/set labels
JButton skinny = new JButton("Convert");
skinny.addActionListener(new ButtonListener());
JPanel buttonPane = new JPanel();
buttonPane.add(skinny);
JButton skinny2 = new JButton("Paste");
JPanel buttonPane2 = new JPanel();
buttonPane2.add(skinny2);
JTextField text;
text = new JTextField(" ");
JPanel textPane = new JPanel();
textPane.add(text);
JTextField text2 = new JTextField("----------------------------------------WAIT LIST----------------------------------------");
JPanel textPane2 = new JPanel();
textPane2.add(text2);
JFrame frame = new JFrame("Youtube Converter");
frame.setSize(WIDTH, HEIGHT);
frame.add(textPane, BorderLayout.WEST);
frame.add(buttonPane2, BorderLayout.CENTER);
frame.add(buttonPane, BorderLayout.EAST);
frame.add(textPane2, BorderLayout.PAGE_END);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
return text.getText();
}
This is an incorrect use of a constructor.
In this case, your constructor should be declared as:
public static Bank_Statement(){
//constructor code goes here
}
then you can declare a getter method for your JTextField value like so:
public String getText(){
return text.getText();
}
then you should be able to call that method (getText) in any method once the object is instantiated. Like this:
public static void main(String[] args){
//just an example...you wouldn't really want to do this
Bank_Statement recObject = new Bank_Statement();
recObject.getText();
}
But overall this solution is not a "good" fix because there are many other ways to do it that are considered better. This will simply fix your error you are having. I would look into understanding classes and objects better before you continue. :)
I am making a Log in window, so after enter username, password and click login button it will direct you to another frame, which is my GUI that use to insert, retrieve, update, and delete database. However, after click, it displayed nothing. Thank you! Here is my code:
It should redirect to GUI like this:
Login
public class Log extends JFrame {
public static void main(String[] args) {
Log frameTabel = new Log();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
Log() {
super("Login Autentification");
setSize(300, 200);
setLocation(500, 280);
panel.setLayout(null);
txuser.setBounds(70, 30, 150, 20);
pass.setBounds(70, 65, 150, 20);
blogin.setBounds(110, 100, 80, 20);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin() {
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = txuser.getText();
String ppaswd = pass.getText();
if ( puname.equals("test") && ppaswd.equals("12345") ) {
CarSearch regFace = new CarSearch();
// regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,
"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
Here is the CarSearch
public class CarSearch {
public static void main(String[] args) {
MainPanel logoPanel = new MainPanel();
JFrame frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
First of all, I don't encourage the use of multiple frames, instead you should use a CardLayout, how ever. Your CarSearch class doesn't do anything, it only has static main method, which you never call.
I would change the class so it has a constructor which initialises the class and a method you can call so you can control when you want to the window shown
public class CarSearch {
private MainPanel logoPanel;
private JFrame frame;
public CarSearch() {
logoPanel = new MainPanel();
frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
}
public void show() {
frame.pack();
frame.setVisible(true);
}
}
Now, having said that, I'd strongly encourage you to use a CardLayout.
Start by creating a LoginPanel and a CarSearchPanel, then you can add each to the same frame and use the CardLayout to switch between them as needed
For (a slight over the top) example
If that is what you want to do then in your CarSearch class should be a JFrame and in your main method you should have CarSearch frame = new CarSearch("Cars Search") instead of JFrame frame = new JFrame("Cars Search"). Then introduce a method public void authenticated() which should contain the code for enabling the other tabs. Also your initialisation should have all the tabs other than the login tab disabled.
Now in your method public void actionlogin() in your validation condition if ( puname.equals("test") && ppaswd.equals("12345") ) you should have CarSearch frame = (CarSearch)getRootPane(); and after that you could call frame.authenticated(); which will disable the login tab and enable the other tabs.
So I am attempting to create a login screen that prompts the user with a text box and 2 buttons (Login and Cancel). When the user hits login, I want the value of the JTextField to be stored in a variable or at least be usable. When I attempt to do anything with the playerNameTxt.getText() method, I get an error as if playerNameTxt doesn't exist.
public class GUI extends JPanel implements ActionListener {
protected JTextField playerNameTxt;
public GUI() {
JTextField playerNameTxt = new JTextField(20);
JLabel playerNameLbl = new JLabel("Enter Player Name");
JButton loginBtn = new JButton("Login");
loginBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
loginBtn.setHorizontalTextPosition(AbstractButton.LEFT);
loginBtn.setMnemonic(KeyEvent.VK_D);
loginBtn.setActionCommand("login");
loginBtn.addActionListener(this);
loginBtn.setToolTipText("Click this to Login");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.setVerticalTextPosition(AbstractButton.BOTTOM);
cancelBtn.setHorizontalTextPosition(AbstractButton.RIGHT);
cancelBtn.setMnemonic(KeyEvent.VK_M);
cancelBtn.setActionCommand("cancel");
cancelBtn.addActionListener(this);
cancelBtn.setToolTipText("Click this to Cancel");
add(playerNameLbl);
add(playerNameTxt);
add(loginBtn);
add(cancelBtn);
}
public void actionPerformed(ActionEvent e) {
if ("login".equals(e.getActionCommand())) {
System.out.println(playerNameTxt);
} else {
System.exit(0);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("-- Munitions Login --");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(400, 200);
GUI newContentPane = new GUI();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You firstly declare the field outside of the constructor, then you declare it inside the constructor again, so that it will be deleted after the constructor returns and the GUI was destroyed, and it will not be usable for your class after the constructor has finished. You should change this line:
JTextField playerNameTxt = new JTextField(20);
to this:
playerNameTxt = new JTextField(20);
In your constructor, you aren't referencing the instance variable playerNameTxt - you're making a new local variable. You should change JTextField playerNameTxt = new JTextField(20); to playerNameTxt = new JTextField(20); (or this.playerNameTxt = new JTextField(20);) to properly initialize the variable. You should then be able to call methods on it without warnings or errors, assuming everything else is correct.
I'm trying to write a piece of code that when I check one of the two checkboxes, it will change the message that appears when I then select the button.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FirstWindow extends JFrame{
String message;
public static void main(String[] args){
//the string to show the message for button 1
message = "goodjob \n";
//all of the main window
JFrame frame = new JFrame("heading");
frame.setVisible(true);
frame.setSize(600,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//makes seperate panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel(new GridBagLayout());
//set of buttons
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
//makes an ACTION LISTENER, which tells the button what to do when
//it is pressed.
button1.addActionListener(new ActionListener(){
//the command to button
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, message);
}
});
//for panel adds buttons
panel1.add(button1);
panel1.add(button2);
//set of checkboxes
JCheckBox checkBox = new JCheckBox("Option1");
JCheckBox checkBox2 = new JCheckBox("Option2");
//adds text if the box is checked
if (checkBox.isSelected())
{
message += "you picked option 1";
}
if (checkBox2.isSelected())
{
message += "you picked option 2";
}
//for panel2 adds checkboxes
panel2.add(checkBox);
panel2.add(checkBox2);
//makes a new label, text area and field
JLabel label = new JLabel("This is a label");
JTextArea textArea = new JTextArea("this is a text area");
JTextField textField = new JTextField("text field");
//makes an invisible grid
GridBagConstraints grid = new GridBagConstraints();
grid.insets = new Insets(15, 15, 15, 15);
//sets the the coordinates 0,0. adds the label, and sets position
grid.gridx = 0;
grid.gridy = 0;
panel3.add(label, grid);
//sets the the coordinates 0,1. adds the textArea, and sets position
grid.gridx = 0;
grid.gridy = 1;
panel3.add(textArea, grid);
//sets the the coordinates 0,2. adds the text field, and sets position
grid.gridx = 0;
grid.gridy = 2;
panel3.add(textField, grid);
//adds each PANEL to the FRAME and positions it
frame.add(panel1, BorderLayout.SOUTH);
frame.add(panel3, BorderLayout.CENTER);
frame.add(panel2, BorderLayout.NORTH);
}
}
The error message I'm receiving is:
"FirstWindow.java:12: error: non-static variable message cannot be referenced from a static context
message = "goodjob \n";"
for lines 12, 37, 53, 57. I've tried declaring the String variable in the main but then I will just receive the error:
"FirstWindow.java:38: error: local variables referenced from an inner class must be final or effectively final JOptionPane.showMessageDialog(null, message);"
How to solve this problem?
Make the message field static:
static String message;
Your main class is static (as it has to be). This means you don't have an instance of your class. But the field message is currently not static, this means it only exists as part of an instance. Since you don't have an instance you can't access it.
As a side note: I strongly suggest you get someone to code review this code. There is a lot to learn. Consider submitting it to Code Review.
The problem here is, you declared non-static variable String message outside of public static void main() which is a static method.
So there are three possible solutions
Declare string message inside the main method
public static void main(String []args){
String message = "goodjob \n";
Based on the answers above, you can change String message to static
static String message;
public static void main(String []args){
message = "goodjob \n";
Create an object of class FirstWindow and then access the String message
FirstWindow sampleFirst = new FirstWindow();
sampleFirst.message = "goodjob \n";
I recommend you to create a constructor and avoid the use of static variable in this case:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class FirstWindow extends JFrame{
private String message;
FirstWindow (){
super("heading");
//the string to show the message for button 1
message = "goodjob \n";
//all of the main window
// remove this: JFrame frame = new JFrame("heading");
// remove this: frame.setVisible(true);
// change frame.setSize(600,400); by:
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// the rest of your code with the JFrame instantiation
// ...
//adds each PANEL to the FRAME and positions it
// here also change frame.add(... by just add(... as follows
add(panel1, BorderLayout.SOUTH);
add(panel3, BorderLayout.CENTER);
add(panel2, BorderLayout.NORTH);
}
public static void main(String[] args){
new FirstWindow().setVisible(true);
}
}