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. :)
Related
I made a JFrame with JTextField, JPanel and a button in which the user inputs a value and after clicking the button, it will generate multiple labels based on the users input, but the JLabel doesnt appear. am i doing it wrong?
this is the coding for the button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String s = jTextField1.getText();
int noSub = Integer.valueOf(s);
addData(noSub);
}
and this is the method to add JLabel.
public void addData(int a){
jPanel1.removeAll();
int num = a;
JLabel jLabel[] = new JLabel[num];
for(int i=0;i<num;i++){
jLabel[i]=new JLabel();
jLabel[i] = new JLabel("Label "+i);
jPanel1.add(jLabel[i]);
jPanel1.revalidate();
jPanel1.repaint();
}
jPanel1.updateUI();
}
Made a simple working example here:
public class Sample extends JFrame{
private JTextField inputField;
private JPanel outputPanel;
private Sample() {
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel form = new JPanel(new GridBagLayout());
inputField = new JTextField(3);
JButton submitBtn = new JButton("Enter");
form.add(inputField);
form.add(submitBtn);
mainPanel.add(form, BorderLayout.NORTH);
outputPanel = new JPanel();
mainPanel.add(outputPanel);
submitBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = inputField.getText();
int noSub = Integer.valueOf(text);
addData(noSub);
}
void addData(int data){
outputPanel.removeAll();
JLabel jLabel[] = new JLabel[data];
for(int i=0;i<data;i++){
jLabel[i] = new JLabel("Label "+i);
outputPanel.add(jLabel[i]);
}
outputPanel.revalidate();
outputPanel.repaint();
// No need to call outputPanel.updateUI()
}
});
setSize(400,500);
add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Sample();
}
}
I am currently making a News Ticker kind of program that scrolls the users inputted text accross the JLabel. Currently I can get it to display the text in a String Variable. However when I try to pass textual input into the field it cause's errors. What I have so far that works is the following;
public class Scroll2 extends JPanel implements Runnable, ActionListener{
JLabel label;
JLabel prompt;
JPanel LabelPan;
JPanel panelForText;
String str= "Hello";
String text;
JFrame mainFrame;
JTextField t;
public Scroll2(){
super();
mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(new Dimension(840, 280));
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setLayout(new GridLayout(0,1));
LabelPan = new JPanel();
LabelPan.isMaximumSizeSet();
LabelPan.setSize(620, 180);
label = new JLabel(str);
label.setFont(new Font("Serif", Font.PLAIN, 70));
LabelPan.add(label);
panelForText = new JPanel();
panelForText.setLayout(new GridLayout(0, 2));
prompt = new JLabel("Enter Text Here;");
panelForText.add(prompt);
t = new JTextField();
t.setSize(80, 53);
t.addActionListener(this);
panelForText.add(t);
mainFrame.add(LabelPan, BorderLayout.NORTH);
mainFrame.add(panelForText, BorderLayout.SOUTH);
Thread t = new Thread(this);
t.start();
}
public void run(){
while(true){
char c = str.charAt(0);
String rest = str.substring(1);
str = rest + c;
label.setText(str);
try{
Thread.sleep(200);
}catch(InterruptedException e){}
}
}
public void actionPerformed(ActionEvent evt) {
JTextField t = (JTextField) evt.getSource();
}
public static void main(String[] args) {
Scroll2 TextScroll = new Scroll2();
}
}
Any help would be appreciated thank you.
You never bother to update str in your actionPerformed() method:
public void actionPerformed( ActionEvent evt )
{
// JTextField t = (JTextField) evt.getSource();
str = t.getText();
}
Seriously if you took one minute to look at your code, you could have found this. Maybe proper indenting would help you read your code better.
(I'm going to ignore the multi-threading errors in the code. Read up on Swing concurrency: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/ )
what I am trying to do is compare two inputs from TextFields within a JFrame using an ActionListener. If the two inputs are equal and the user hits the button, a MessageDialog will pop up and say "equal". If they are not equal, a MessageDialog will pop up and say "not equal". I have the frame and ActionListener running, I just do not know how to take the inputs from the TextFields and compare them.
For example, if the user enters something like this,
Equal TextFields, this will pop up, Equal Message
Here is my Main Class:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here is my ActionListener Class:
class tfListener implements ActionListener
{
private final JTextField tf3;
public tfListener(JTextField nameTF)
{
tf3 = nameTF;
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("abc"))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
EDIT: ok than try to change the constructor in your ActionListener Class to
public tfListener(JTextField tf1, JTextField tf2){
{
Hi :) just don't overthink and you should be fine. The simple way would be to implement the ActionListener directly to your Main Class like this:
public class LabFiveOne
{
public static void main(String[] args)
{
JFrame frame = new JFrame("String Equality Program");
final JTextField tf1 = new JTextField(10);
tf1.setActionCommand(tf1.toString());
tfListener tfListen = new tfListener(tf1);
final JTextField tf2 = new JTextField(10);
tf2.setActionCommand(tf2.toString());
JButton chEq = new JButton("Check Equality");
chEq.addActionListener(tfListen);
JPanel nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
JPanel sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
{
class tfListener implements ActionListener
{
private final String tf1text;
private final String tf2text;
public tfListener(JTextField tf1, JTextField tf2)
{
tf1text = new String(tf1.getText());
tf1text = new String(tf2.getText());
}
#Override
public void actionPerformed(ActionEvent e)
{
if(tf1text.equal(tf2text))
{
JOptionPane.showMessageDialog(null, "equal");
}
else
{
JOptionPane.showMessageDialog(null, "not equal");
}
}
}
}
tf1.toString();
Shows you some information from the JTextField.
use another methods to get your input from the field. I mean it's the method:
tfi.getText();
Better look in a JTextField javadoc
To be honest with you, I don't think you need two classes; one for implementing the GUI and one for handling the ActionListener when you can have everything in one class like the class below
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
public class LabFiveOne implements ActionListener
{
private JFrame frame;
private JPanel nPanel, sPanel;
private JTextField tf1, tf2;
private JButton chEq;
public static void main(String[] args)
{
new LabFiveOne();
}
public LabFiveOne(){
frame = new JFrame("String Equality Program");
tf1 = new JTextField(10);
tf2 = new JTextField(10);
chEq = new JButton("Check Equality");
chEq.addActionListener(this);
nPanel = new JPanel();
nPanel.add(tf1);
nPanel.add(tf2);
frame.add(nPanel, BorderLayout.NORTH);
sPanel = new JPanel();
sPanel.add(chEq);
frame.add(sPanel, BorderLayout.SOUTH);
nPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String action = e.getActionCommand();
if(action.equals("Check Equality")){
String number1 = tf1.getText();
String number2 = tf2.getText();
int num1 = Integer.valueOf(number1);
int num2 = Integer.valueOf(number2);
if(num1 == num2){
JOptionPane.showMessageDialog(null, "Equal");
}
else{
JOptionPane.showMessageDialog(null, "Not Equal");
}
}
}
}
I have everything declared globally so that the ActionPerformed method will have access the values in the Textfields.
I've been working on creating a simple GUI through the use of JPanels. I've managed to what I believe fluke a reasonably looking layout and now I would like the user to be able to input values into the Mass textbox and the Acceleration textbox so when they hit calculate they are given a message telling them the Force.
The issue I am having is within the public void that is added to the buttons, I can't seem to figure out how to refer to values within the text field. I've tried to just refer to it generally by:
String mass = txts[1].getText();
However this doesn't recognise txts as existing?
Any help on this would be much appreciated.
Below is the full code in case it helps.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.*;
import java.awt.*;
public class InitScreen {
public static void createHomeScreen() {
/*Creates a Java Frame with the Window Name = HomeScreen*/
JFrame frame = new JFrame("HomeScreen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.getContentPane().setPreferredSize(new Dimension(400,300));
frame.pack();
/*Creates the main JPanel in form of GridLayout*/
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(new EmptyBorder(new Insets(20,20,20,20)));
/*Creates the first sub panel*/
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(1,2,75,100));
firstPanel.setMaximumSize(new Dimension(300,100));
/*Creates the buttons in the first sub panel*/
JButton[] btns = new JButton[2];
String bText[] = {"Calculate", "Clear"};
for (int i=0; i<2; i++) {
btns[i] = new JButton(bText[i]);
btns[i].setPreferredSize(new Dimension(100, 50));
btns[i].setActionCommand(bText[i]);
btns[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
/*JOptionPane.showMessageDialog(null, "Clicked "+choice);*/
JOptionPane.showMessageDialog(null, "Force = ");
}
});
firstPanel.add(btns[i]);
}
/*Creates the second sub panel*/
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new BorderLayout());
/*Creates the labels for the second sub panel*/
JLabel label = new JLabel("Calculate the Force of an Object", SwingConstants.CENTER);
secondPanel.add(label,BorderLayout.NORTH);
/*Creates the third sub Panel for entering values*/
JPanel thirdPanel = new JPanel();
thirdPanel.setLayout(new GridLayout(3,1,10,10));
thirdPanel.setMaximumSize(new Dimension(400,100));
/*Create labels and text fields for third sub panel*/
String lText[] = {"Mass of Body", "Acceleration of Body", "Force"};
JLabel[] lbls = new JLabel[3];
JTextField[] txts = new JTextField[3];
for (int i=0; i<3; i++) {
txts[i] = new JTextField();
lbls[i] = new JLabel(lText[i], SwingConstants.LEFT);
lbls[i].setPreferredSize(new Dimension(50, 50));
thirdPanel.add(lbls[i]);
thirdPanel.add(txts[i]);
}
mainPanel.add(secondPanel);
mainPanel.add(thirdPanel);
mainPanel.add(firstPanel);
frame.setContentPane(mainPanel);
frame.setVisible(true);
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createHomeScreen();
}
});
}
}
First drop the reliance on static, and instead, create an instance of InitScreen and call it's createHomeScreen method
public class InitScreen {
public void createHomeScreen() {
//...
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
InitScreen screen = new InitScreen();
screen.createHomeScreen();
}
});
}
Now, make txts and instance field of InitScreen and use it within your methods
public class InitScreen {
private JTextField[] txts;
public void createHomeScreen() {
//...
txts = new JTextField[3];
//...
}
This takes txts from a local context to a class instance context, meaning you can now access it from any method within InitScreen
So this is my runner that runs my entire game. CharacterGame, CharacterChoice and CharacterHead are all classes that contain graphics and paint. I was hoping to be able to call separate parts from these classes into the graphics by the remove and repaint located in one of my button's code. Right now its just updating the Frame with more and more panels instead of removing the old panels and adding these panels into the old panels place. I hope this makes sense as I am a bit new to graphics and may not have thought of the best way to do this. If anyone can shed some light into how to do this, I will be very grateful. Thanks! I've tried everything I can think of... from removeAll methods to repaint. I can't think of anything else to do.
The part not working is located in the ShowButtonDemo() in the choice1Button listener.
public class GraphicsRunner extends JFrame
{
private static final int WIDTH = 1280;
private static final int HEIGHT = 980;
private JFrame mainframe;
private JPanel controlPanel;
private JPanel headPanel;
private JPanel gamePanel;
private JPanel choicePanel;
private int gameInt = 0;
private int choiceInt = 0;
private int endGame = 0;
public GraphicsRunner()
{
super("Stranded...");
mainframe = new JFrame();
mainframe.setBackground(Color.BLACK);
mainframe.setSize(WIDTH,HEIGHT);
mainframe.setLayout(new GridLayout(4, 0));
mainframe.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headPanel = new JPanel();
gamePanel = new JPanel();
choicePanel = new JPanel();
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
headPanel = new CharacterHeading();
gamePanel = new CharacterGame(gameInt);
choicePanel = new CharacterChoice(choiceInt);
mainframe.add(headPanel);
mainframe.add(gamePanel);
mainframe.add(choicePanel);
mainframe.add(controlPanel);
mainframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainframe.setVisible(true);
}
public static void main( String args[] )
{
GraphicsRunner run = new GraphicsRunner();
run.showButtonDemo();
}
private void showButtonDemo(){
JButton choice1Button = new JButton("Choice #1");
JButton choice2Button = new JButton("Choice #2");
JButton choice3Button = new JButton("Choice #3");
choice3Button.setHorizontalTextPosition(SwingConstants.LEFT);
choice1Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gameInt = gameInt + 1;
choiceInt = choiceInt + 1;
gamePanel = new CharacterGame(gameInt);
//This is the part I am currently working on and I was hoping
//it would remove the panel instead of just removing the
//content on the panel...
mainframe.remove(headPanel);
mainframe.remove(gamePanel);
mainframe.remove(choicePanel);
mainframe.remove(controlPanel);
mainframe.add(headPanel, 0);
mainframe.add(gamePanel, 1);
mainframe.add(choicePanel, 2);
mainframe.add(controlPanel, 3);
mainframe.revalidate();
mainframe.repaint();
System.out.println(gameInt);
}
});
controlPanel.setBackground(Color.BLACK);
controlPanel.add(choice1Button);
controlPanel.add(choice2Button);
controlPanel.add(choice3Button);
mainframe.setVisible(true);
}
}