I created a console based program that allowed users to take a math quiz. The program basically generated random numbers and determined if the answer was right or wrong.
Now, I'm trying to create the GUI version of this program and I'm stuck.
I want to print text messages in the jtextarea from a different class. I've used the get and set methods, but for some reason it doesn't output the text messages. I've done some research on swing workers but I have no idea how to get it to work so I'm trying to avoid using it if possible.
This is not a homework assignment. I started learning java 4 months ago so i may not understand advance concepts.
I guess what I want to know... do I have to use swing workers? all really want to do is generate random numbers and output the result in the jtextarea... it shouldn't freeze the gui, right? Anyway, thanks in advance.
package algorithmsProgramGUI.view;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Toolkit;
import java.awt.Panel;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.text.JTextComponent;
import javax.swing.JFormattedTextField;
import java.awt.Choice;
import java.awt.Label;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.TextArea;
import java.awt.Button;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import javax.swing.JTextArea;
public class ProFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = -7222968352076888482L;
private static JTextArea textArea;
private JPanel contentPane;
public static JTextArea getTextArea() {
return textArea;
}
public static void setTextArea(JTextArea string) {
ProFrame.textArea = string;
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ProFrame frame = new ProFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ProFrame() {
setIconImage(Toolkit.getDefaultToolkit().getImage(ProFrame.class.getResource("/algorithmsProgramGUI/resources/AlgorithmsLogo.png")));
setTitle("Algorithms");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 864, 590);
contentPane = new JPanel();
contentPane.setToolTipText("Choose a test to take");
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSelectTest = new JLabel("Select Test :");
lblSelectTest.setFont(new Font("Times New Roman", Font.BOLD, 15));
lblSelectTest.setBounds(35, 42, 95, 14);
contentPane.add(lblSelectTest);
JFormattedTextField formattedTextField = new JFormattedTextField();
formattedTextField.setToolTipText("Input answer here");
formattedTextField.setBounds(419, 415, 108, 24);
contentPane.add(formattedTextField);
Label label = new Label("Answer :");
label.setFont(new Font("Times New Roman", Font.BOLD, 15));
label.setBounds(339, 415, 74, 22);
contentPane.add(label);
Panel status_panel = new Panel();
status_panel.setFont(new Font("Times New Roman", Font.PLAIN, 12));
status_panel.setBounds(220, 445, 558, 75);
contentPane.add(status_panel);
Button button_1 = new Button("Next Question");
button_1.setFont(new Font("Times New Roman", Font.BOLD, 15));
button_1.setBounds(545, 415, 154, 22);
contentPane.add(button_1);
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
textArea.setBounds(257, 62, 521, 305);
contentPane.add(textArea);
Choice Test = new Choice();
Test.setFont(new Font("Times New Roman", Font.BOLD, 12));
Test.setBounds(35, 62, 130, 20);
Test.add("Practice Quiz");
Test.add("Test 1");
Test.add("Test 2");
contentPane.add(Test);
Button button = new Button("Generate Test");
button.setFont(new Font("Times New Roman", Font.BOLD, 15));
button.setBounds(35, 235, 117, 26);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = Test.getSelectedItem().toString();
textArea.setText(s);
textArea.setFont(new Font("Times New Roman", Font.BOLD, 12));
if (Test.getSelectedItem().equalsIgnoreCase("Practice Quiz")) {
algorithmsProgramGUI.view.PracticeQuizGUI.runPracticeQuizGUI();
}
if (Test.getSelectedItem().equalsIgnoreCase("Test 1")) {
textArea.setText("Test 1 is not available at this time.");
}
if (Test.getSelectedItem().equalsIgnoreCase("Test 2")) {
textArea.setText("Test 2 is not available at this time.");
}
}
});
contentPane.add(button);
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{label, formattedTextField, Test, button, status_panel, lblSelectTest, button_1}));
}
#SuppressWarnings("unused")
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
public static void setTextArea(String string) {
// TODO Auto-generated method stub
}
}
package algorithmsProgramGUI.view;
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
import java.awt.*;
public class PracticeQuizGUI {
static void runPracticeQuizGUI() {
// System.out.println("This statement was created in PracticeQuizGUI class.");
//algorithmsProgramGUI.view.ProFrame.ProFrame().textArea.setText("s");
//algorithmsProgramGUI.view.ProFrame.getTextArea();
algorithmsProgramGUI.view.ProFrame.setTextArea("Welcome to the practice quiz.");
//algorithmsProgramGUI.view.ProFrame.getTextArea();
}
}
in your current code:
public static void setTextArea(String string) {
// TODO Auto-generated method stub
}
nothing is being done, use
JTextArea.setText(String t) method to set the value
Related
I have one Swing project and I have an action listener on JTextField for Tab key as follows.
There is a JOptionPane.showMessageDialog() inside the action listener. And when Tab is pressed option pane will show an Information message.
My problem is that, when I press Enter on OK button of Information Message dialog, a serie of action is invoked viz Tab action of JTextField and Enter action of btnNewButton.
If I use mouse click on OK button of Error Message dialog, every thing is fine and no problem.
Can I solve this using key bindings instead of key listener?
Please suggest a solution
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnNewButton;
private JDialog dialog;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null);
contentPane.setLayout(null);
textField = new JTextField();
textField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.emptySet());
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
JOptionPane.showMessageDialog(dialog, " Please Press ENTER Key", "information",
JOptionPane.INFORMATION_MESSAGE);
btnNewButton.grabFocus();
}
}
});
textField.setBounds(73, 28, 178, 28);
contentPane.add(textField);
textField.setColumns(10);
btnNewButton = new JButton("New button");
btnNewButton.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane.showMessageDialog(dialog, " That Invoked New Button Also", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(223, 137, 117, 25);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("Please Press TAB Key");
lblNewLabel.setBounds(83, 55, 183, 15);
contentPane.add(lblNewLabel);
dialog = new JDialog();
dialog.setAlwaysOnTop(true);
}
}
The problem is that you are overriding method keyReleased(). The JOptionPane is closing before the keyReleased() method is called and since you make btnNewButton the focused component after the JOptionPane is closed, the keyReleased() method is invoked – which displays the other JOptionPane.
Simply rename the method to keyPressed().
Also, you don't need the dialog member. The first parameter to JOptionPane#showMessageDialog should be the JFrame.
Here is your code with my corrections.
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null);
contentPane.setLayout(null);
textField = new JTextField();
textField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.emptySet());
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
JOptionPane.showMessageDialog(Test.this, " Please Press ENTER Key", "information",
JOptionPane.INFORMATION_MESSAGE);
btnNewButton.grabFocus();
}
}
});
textField.setBounds(73, 28, 178, 28);
contentPane.add(textField);
textField.setColumns(10);
btnNewButton = new JButton("New button");
btnNewButton.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane.showMessageDialog(Test.this, " That Invoked New Button Also", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(223, 137, 117, 25);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("Please Press TAB Key");
lblNewLabel.setBounds(83, 55, 183, 15);
contentPane.add(lblNewLabel);
}
}
Note that (at least in JDK 15) there is no need to explicitly set the default close operation for JFrame since the default is EXIT_ON_CLOSE
I am currently trying to write a simple program that will display musical notes at a given interval in BPM. I have most of the code written, but I can't figure out how to get the labels containing the note and sharp/flat to update every interval given. This is my code so far. The NoteGenerator object is of my own creation and is just used to generate a random note/sharp/flat and keep track of tempo. I have already tested the NoteGenerator class and it works exactly how I expect it to. Thanks in advance!
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JSpinner;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class NotePractice extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NotePractice frame = new NotePractice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public NotePractice() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
NoteGenerator noteGen = new NoteGenerator();
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerNumberModel(new Integer(100), new Integer(20), null, new Integer(5)));
spinner.setBounds(211, 196, 60, 20);
contentPane.add(spinner);
JLabel lblBpm = new JLabel("BPM");
lblBpm.setFont(new Font("Arial", Font.BOLD, 12));
lblBpm.setBounds(175, 198, 26, 14);
contentPane.add(lblBpm);
JLabel lblNote = new JLabel(noteGen.getNote());
lblNote.setFont(new Font("Arial", Font.BOLD, 99));
lblNote.setBounds(175, 60, 82, 104);
contentPane.add(lblNote);
JLabel lblStep = new JLabel(noteGen.getStep());
lblStep.setFont(new Font("Arial", Font.BOLD, 70));
lblStep.setBounds(258, 93, 60, 58);
contentPane.add(lblStep);
JButton btnUpdateTempo = new JButton("Update Tempo");
btnUpdateTempo.setFont(new Font("Arial", Font.PLAIN, 11));
btnUpdateTempo.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
noteGen.setBPM(spinner.getComponentCount());
Timer t = new Timer(noteGen.getBPM(), new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblNote.setText(noteGen.getNote());
lblStep.setText(noteGen.getStep());
contentPane.updateUI();
}
});
}
});
btnUpdateTempo.setBounds(168, 227, 103, 23);
contentPane.add(btnUpdateTempo);
}
}
I have my original text field in my first frame and I need it to be displayed in my other jframe. The code is:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
'nameL' is the textbox the user enters their name in.
This code describe where it should be displayed:
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
this is my first class where the user inputs their name
public order(String para){
getComponents();
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class frame1 {
public JFrame frame;
public JTextField nameL;
public JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1 window = new frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setEnabled(false);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GRAY);
frame.setForeground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
}
}
);
btnContinue.setBounds(0, 249, 450, 29);
frame.getContentPane().add(btnContinue);
JTextArea txtrPleaseEnterYour = new JTextArea();
txtrPleaseEnterYour.setEditable(false);
txtrPleaseEnterYour.setBackground(Color.LIGHT_GRAY);
txtrPleaseEnterYour.setBounds(0, 0, 450, 32);
txtrPleaseEnterYour.setText("\tPlease enter your name and email below\n If you do not have or want to provide an email, Leave the space blank");
frame.getContentPane().add(txtrPleaseEnterYour);
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(52, 180, 284, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
}
my second class where the text field has to be set
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class order extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
order frame = new order();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public order() {
setAlwaysOnTop(false);
setTitle("Order Details // Finalization");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 451, 523);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Submit Order");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
JOptionPane.showMessageDialog(null, "Your Order Has Been Confirmed", "enjoy your meal", JOptionPane.YES_NO_OPTION);
}
});
btnNewButton.setBounds(164, 466, 117, 29);
contentPane.add(btnNewButton);
}
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
}
}
Open both JFrames, have them listen to the EventQueue for a custom "string display" event.
Wrap the string to be displayed in a custom event.
Throw that on the event queue, allowing both the JFrames to receive the event, which they will then display accordingly.
---- Edited with an update ----
Ok, so you're a bit new to Swing, but hopefully not too new to Java. You'll need to understand sub-classing and the "Listener" design pattern.
Events are things that Components listen for. They ask the dispatcher (the Swing dispatcher is fed by the EventQueue) to "tell them about events" and the dispatcher then sends the desired events to them.
Before you get too deep in solving your problem, it sounds like you need to get some familiarity with Swing and its event dispatch, so read up on it here.
I create a java application and now I have to reload a web page. I open the web page with this code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.JProgressBar;
import java.io.*;
import java.util.*;
public class views extends JFrame {
private JPanel contentPane;
private JTextField txtHttpswwwyoutubecom;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
views frame = new views();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public views() {
setTitle("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 707, 485);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblPutTheUrl = new JLabel("Put the url of the video");
lblPutTheUrl.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPutTheUrl.setBounds(40, 93, 159, 24);
contentPane.add(lblPutTheUrl);
JLabel lblSelectTheNumber = new JLabel("Select the number");
lblSelectTheNumber.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblSelectTheNumber.setBounds(40, 200, 203, 24);
contentPane.add(lblSelectTheNumber);
final JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"5", "10", "15", "20"}));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 15));
comboBox.setBounds(322, 202, 121, 20);
contentPane.add(comboBox);
txtHttpswwwyoutubecom = new JTextField();
txtHttpswwwyoutubecom.setText("https://www.google.com/");
txtHttpswwwyoutubecom.setFont(new Font("Tahoma", Font.PLAIN, 15));
txtHttpswwwyoutubecom.setBounds(322, 93, 332, 24);
contentPane.add(txtHttpswwwyoutubecom);
txtHttpswwwyoutubecom.setColumns(10);
JLabel lblPressOk = new JLabel("Press Ok ");
lblPressOk.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblPressOk.setBounds(40, 298, 71, 24);
contentPane.add(lblPressOk);
JButton btnOk = new JButton("Ok");
btnOk.addActionListener(new ActionListener() {
private String views;
private int intViews;
public void actionPerformed(ActionEvent arg0) {
//trasformare il numero delle views in una stringa
views = comboBox.getSelectedItem().toString();
//trasformo stringa in int
intViews = Integer.parseInt(views);
System.out.println(intViews);
//campo url
String urls = txtHttpswwwyoutubecom.getText();
//apertura url
int cont=0;
int cont1=0;
//cont=intViews;
//System.out.println("cont");
//System.out.println(intViews);
/*
try {
Thread.sleep(millisecondi);
}
catch (Exception e) {}
*/
while(intViews>cont){
cont++;
cont1++;
String URL = urls;
//String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//System.exit(0);
}
if(cont1==5){
cont1=0;
try {
Thread.sleep(5500);
}
catch (Exception e1) {}
}
}
}
});
btnOk.setFont(new Font("Tahoma", Font.PLAIN, 15));
btnOk.setBounds(322, 299, 121, 23);
contentPane.add(btnOk);
JLabel lblDevelopedByRiccardo = new JLabel("Developed by Riccardo Vecchiato");
lblDevelopedByRiccardo.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblDevelopedByRiccardo.setBounds(464, 421, 237, 24);
contentPane.add(lblDevelopedByRiccardo);
JLabel lblAlpha = new JLabel("Alpha 1.0");
lblAlpha.setBounds(10, 428, 46, 14);
contentPane.add(lblAlpha);
}
}
Every 5 seconds I open five new web page. I open that web page using this code:
String URL = "https://www.google.com/";
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create(URL));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There is a command that reload all the web page that I create with this code?
Do not use Thread.sleep() as it will freeze your Swing application.
Instead you should use a javax.swing.Timer.
See the Java tutorial How to Use Swing Timers and Lesson: Concurrency in Swing for more information and examples.
I am trying to program an 'Inch-to-Centimeter Calculator'. I've got a problem with the method umrechnen(). The label lblCenti cannot be resolved. My Code is equal to the Solutioncode. I am grateful for every answer or tip I get.
I don't know what I should add to my Description, but StackOverflow forces me to write more, so I'm writing this.
package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.text.DecimalFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class ZollZentimeter extends JFrame {
private JPanel contentPane;
private JTextField tfInch;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ZollZentimeter frame = new ZollZentimeter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ZollZentimeter() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 359, 157);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnCalculate = new JButton("Umrechnen");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
umrechnen();
}
});
btnCalculate.setBounds(12, 77, 116, 25);
contentPane.add(btnCalculate);
JButton btnEnde = new JButton("Ende");
btnEnde.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnEnde.setBounds(214, 77, 116, 25);
contentPane.add(btnEnde);
JLabel lblZoll = new JLabel("Zoll");
lblZoll.setBounds(12, 13, 56, 16);
contentPane.add(lblZoll);
tfInch = new JTextField();
tfInch.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER){
umrechnen();
}
}
});
JLabel lblCenti = new JLabel("");
lblCenti.setBounds(214, 42, 116, 22);
contentPane.add(lblCenti);
tfInch.setBounds(12, 42, 116, 22);
contentPane.add(tfInch);
tfInch.setColumns(10);
}
private void umrechnen(){
DecimalFormat f=new DecimalFormat("#0.00");
double z, cm;
z=Double.parseDouble(tfInch.getText());
cm=z*2.54;
lblCenti.setText(f.format(cm+" cm"));
tfInch.requestFocus();
tfInch.selectAll();
}
}
JLabel lblCenti = new JLabel("");
"lblCenti" is defined as a local variable so it can only be accessible in the method/constructor where you define it.
It you want to access the label in another method you need to define it as an instance variable, the same way you do with the "tfInch" variable.