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.
Related
I'm trying to make a QUIZ Application where everytime where the questions are retrieved from the DB,Each time the user selects the right option his marks should be incremented.
While I'm trying to do that the marks doesnt seem to increase and sometimes end up staying at zero even If I select the right option.
This whole project is being done on Eclipse using WindowBuilder. I would be grateful if anyone helped me out on this.
package quiz;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JRadioButton;
import java.sql.*;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import quiz.SqlConnection;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class QuizStart extends JFrame {
SqlConnection c1= new SqlConnection();
public int tmarks=0;
public int db_marks;
String studentAnswer="";
String db_ans="";
static String username="";
String usern;
int count=0;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
QuizStart frame = new QuizStart(username);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #param username2
* #param username
*/
//public QuizStart() {
//initComponents();
//}
public QuizStart(String username) {
//initComponents();
usern=username;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 950, 631);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmBack = new JMenuItem("Back");
mntmBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Login().setVisible(true);
}
});
mnFile.add(mntmBack);
contentPane = new JPanel();
contentPane.setBackground(new Color(30, 144, 255));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBackground(new Color(30, 144, 255));
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblNewLabel.setBounds(101, 47, 715, 99);
contentPane.add(lblNewLabel);
JRadioButton radioButton = new JRadioButton("New radio button");
radioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
radioButton.setFont(new Font("Tahoma", Font.PLAIN, 16));
radioButton.setBounds(124, 213, 230, 47);
contentPane.add(radioButton);
JRadioButton radioButton_1 = new JRadioButton("New radio button");
radioButton_1.setFont(new Font("Tahoma", Font.PLAIN, 16));
radioButton_1.setBounds(125, 289, 254, 60);
contentPane.add(radioButton_1);
JRadioButton radioButton_2 = new JRadioButton("New radio button");
radioButton_2.setFont(new Font("Tahoma", Font.PLAIN, 16));
radioButton_2.setBounds(418, 201, 254, 71);
contentPane.add(radioButton_2);
JRadioButton radioButton_3 = new JRadioButton("New radio button");
radioButton_3.setFont(new Font("Tahoma", Font.PLAIN, 16));
radioButton_3.setBounds(418, 289, 303, 60);
contentPane.add(radioButton_3);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Statement str1= c1.con.createStatement();
ResultSet rs=str1.executeQuery("select Question,Option1,Option2,Option3,Option4,CorrectOption,Marks from question ORDER BY RAND() LIMIT 10");
while(rs.next())
{
String v1=rs.getString("Question");
String v2=rs.getString("Option1");
String v3=rs.getString("Option2");
String v4=rs.getString("Option3");
String v5=rs.getString("Option4");
db_ans=rs.getString("CorrectOption");
db_marks=rs.getInt("Marks");
lblNewLabel.setText(v1);
radioButton.setText(v2);
radioButton_1.setText(v3);
radioButton_2.setText(v4);
radioButton_3.setText(v5);
System.out.print("second");
}
if(radioButton.isSelected())
{
studentAnswer=radioButton.getText();
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
}
else if(radioButton_1.isSelected())
{
studentAnswer=radioButton_1.getText();
radioButton.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
}
else if(radioButton_2.isSelected())
{
studentAnswer=radioButton_2.getText();
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_3.setSelected(false);
}
else {
studentAnswer=radioButton_3.getText();
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
}
if(db_ans.equals(studentAnswer))
{
tmarks=tmarks+db_marks;
System.out.println("correct-second");
}
count++;
//System.out.println(count);
//System.out.println("two");
System.out.println(tmarks);
if(count == 11)
{
btnNext.setEnabled(false);
}
//for(int i = qhist.size()-1;i>=0; i--){
// System.out.println(qhist.get(i));
//}
}
catch(Exception s) {
System.out.println("Error due to :"+s);
}
}
});
btnNext.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnNext.setBounds(338, 440, 159, 60);
contentPane.add(btnNext);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new QuizResult(usern,tmarks).setVisible(true);
}
});
btnSubmit.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnSubmit.setBounds(706, 524, 159, 60);
contentPane.add(btnSubmit);
JLabel lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setBounds(48, 10, 184, 27);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(username);
try {
Statement str= c1.con.createStatement();
ResultSet rs=str.executeQuery("select QID,Question,Option1,Option2,Option3,Option4,CorrectOption,Marks from question ORDER BY RAND() LIMIT 10");
while(rs.next())
{
//qhist.push(rs.getInt("QID"));
String v1=rs.getString("Question");
String v2=rs.getString("Option1");
String v3=rs.getString("Option2");
String v4=rs.getString("Option3");
String v5=rs.getString("Option4");
db_ans=rs.getString("CorrectOption");
db_marks=rs.getInt("Marks");
lblNewLabel.setText(v1);
radioButton.setText(v2);
radioButton_1.setText(v3);
radioButton_2.setText(v4);
radioButton_3.setText(v5);
System.out.print("first");
}
if(radioButton.isSelected())
{
studentAnswer=radioButton.getText();
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
}
else if(radioButton_1.isSelected())
{
studentAnswer=radioButton_1.getText();
radioButton.setSelected(false);
radioButton_2.setSelected(false);
radioButton_3.setSelected(false);
}
else if(radioButton_2.isSelected())
{
studentAnswer=radioButton_2.getText();
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_3.setSelected(false);
}
else {
studentAnswer=radioButton_3.getText();
radioButton.setSelected(false);
radioButton_1.setSelected(false);
radioButton_2.setSelected(false);
}
if(db_ans.equals(studentAnswer) )
{
//tmarks=tmarks+db_marks;
//System.out.println("correct");
tmarks=tmarks+db_marks;
System.out.println(tmarks);
System.out.println("correct-first");
}
count++;
//System.out.println("first");
//System.out.println(count);
//System.out.println("one");
}
catch(Exception a) {
System.out.println("Error due to :"+a);
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I created Login and Register frames separated which both connected to MySQL. If I just run the register frame, I can insert a new user to the database. However, If I run the login frame which includes the register frame inside and press register, the button that adds in the register frame does not work even the text fields are filled out.
//this is Login frame class
package YASAR;
import java.awt.BorderLayout;
import java.sql.*;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GirisEkrani extends JFrame {
static JButton btnKullancEkle = new JButton("Kullan\u0131c\u0131 Ekle");
public static JPanel contentPane;
private static JTextField textField;
private static JComboBox comboBox = new JComboBox();
private static JButton btnBalan = new JButton("Ba\u011Flan");
private static JLabel lblParola = new JLabel("Parola :");
private static JLabel lblXaampeBalanlamad = new JLabel("Xaampe Ba\u011Flan\u0131lamad\u0131");
//private static KullaniciEkle ke=new KullaniciEkle();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
lblXaampeBalanlamad.setVisible(false);
try {
GirisEkrani frame = new GirisEkrani();
frame.setVisible(true);
try {
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");
btnKullancEkle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
KullaniciEkle ke=new KullaniciEkle();
ke.setVisible(true);
}
});
btnBalan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
deneme abc=new deneme();
abc.setVisible(true);
}
});
con.close();
}
catch(SQLException e) {
textField.setEditable(false);
btnKullancEkle.setEnabled(false);
comboBox.setEnabled(false);
btnBalan.setEnabled(false);
lblParola.setVisible(false);
lblXaampeBalanlamad.setVisible(true);
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GirisEkrani() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 286, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(74, 129, 124, 19);
contentPane.add(textField);
textField.setColumns(10);
comboBox.setBounds(74, 42, 124, 21);
contentPane.add(comboBox);
btnBalan.setBounds(74, 184, 124, 33);
contentPane.add(btnBalan);
btnKullancEkle.setBounds(74, 227, 124, 26);
contentPane.add(btnKullancEkle);
lblParola.setBounds(10, 132, 45, 13);
contentPane.add(lblParola);
lblXaampeBalanlamad.setBounds(74, 90, 162, 29);
contentPane.add(lblXaampeBalanlamad);
}
}
// And this is register frame class where I add user
package YASAR;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class KullaniciEkle extends JFrame {
public static JPanel contentPane;
public static JTextField textField;
public static JTextField textField_1;
public static JTextField textField_2;
public static JLabel lblIsim;
public static JLabel lblSoyisim;
public static JButton btnNewButton = new JButton("Ekle");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KullaniciEkle frame = new KullaniciEkle();
frame.setVisible(true);
try {
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
try {
PreparedStatement ps=con.prepareStatement(input);
ps.setInt(1, Integer.parseInt(textField.getText()));
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
//ps.execute();
if(ps.executeUpdate()>0) {
JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
}
}catch(SQLException f) {
f.printStackTrace();
}
finally {System.out.println("pressed");}
frame.setVisible(false);
new GirisEkrani().setVisible(true);
}
});
}
catch(SQLException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public KullaniciEkle() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 285, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(87, 67, 96, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(87, 112, 96, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(87, 160, 96, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));
btnNewButton.setBounds(93, 232, 85, 21);
contentPane.add(btnNewButton);
JLabel lblTc = new JLabel("TC");
lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblTc.setBounds(10, 70, 45, 13);
contentPane.add(lblTc);
lblIsim = new JLabel("\u0130sim");
lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblIsim.setBounds(10, 115, 45, 13);
contentPane.add(lblIsim);
lblSoyisim = new JLabel("Soyisim");
lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblSoyisim.setBounds(10, 163, 45, 13);
contentPane.add(lblSoyisim);
}
}
You need to put this code inside your Constructor.
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
try {
PreparedStatement ps=con.prepareStatement(input);
ps.setInt(1, Integer.parseInt(textField.getText()));
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
//ps.execute();
if(ps.executeUpdate()>0) {
JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
}
}catch(SQLException f) {
f.printStackTrace();
}
finally {System.out.println("pressed");}
frame.setVisible(false);
new GirisEkrani().setVisible(true);
}
});
Finally, it will look like this,
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class KullaniciEkle extends JFrame {
public static JPanel contentPane;
public static JTextField textField;
public static JTextField textField_1;
public static JTextField textField_2;
public static JLabel lblIsim;
public static JLabel lblSoyisim;
public static JButton btnNewButton = new JButton("Ekle");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KullaniciEkle frame = new KullaniciEkle();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public KullaniciEkle() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 285, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(87, 67, 96, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(87, 112, 96, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(87, 160, 96, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));
btnNewButton.setBounds(93, 232, 85, 21);
contentPane.add(btnNewButton);
JLabel lblTc = new JLabel("TC");
lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblTc.setBounds(10, 70, 45, 13);
contentPane.add(lblTc);
lblIsim = new JLabel("\u0130sim");
lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblIsim.setBounds(10, 115, 45, 13);
contentPane.add(lblIsim);
lblSoyisim = new JLabel("Soyisim");
lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblSoyisim.setBounds(10, 163, 45, 13);
contentPane.add(lblSoyisim);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButtonActionPerformed(e);
}
});
}
private void btnNewButtonActionPerformed(ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar", "ozkan", "******");
String input = "INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
try {
PreparedStatement ps = con.prepareStatement(input);
ps.setInt(1, Integer.parseInt(textField.getText()));
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
//ps.execute();
if (ps.executeUpdate() > 0) {
JOptionPane.showMessageDialog(null, "user added", "user add", JOptionPane.OK_CANCEL_OPTION);
}
} catch (SQLException f) {
f.printStackTrace();
} finally {
System.out.println("pressed");
}
//Instead of frame use this keyword
this.setVisible(false);
new GirisEkrani().setVisible(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
NOTE:- This is not the best practice to communicate with the database.
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 am making a program for my friend. I ran into an error while trying to create a write and save text into a .txt file. I should note this is the first time I have ever created something in Java Swing.
The error is marked with an asterisk.
package com.laganstoop.me;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
// Created by: Laganstoop (David L. Perez)
// Do Not Distribute!
public class Main implements ActionListener {
private JFrame frame;
public static String infoBox(String infoMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, infoMessage, "" + titleBar, JOptionPane.INFORMATION_MESSAGE);
return "";
}
public static void errorMessage(String errorMessage, String titleBar)
{
JOptionPane.showMessageDialog(null, errorMessage, "" + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
public static final int HEIGHT = 800;
public static final int WIDTH = 600;
public static final int nHEIGHT = 400;
public static final int nWIDTH = 300;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(HEIGHT, WIDTH);
JButton btnNewButton = new JButton("Click To Add New");
btnNewButton.setBounds(10, 11, 132, 23);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
frame.getContentPane().setLayout(null);
frame.getContentPane().add(btnNewButton);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 764, 181);
panel.setBackground(Color.WHITE);
panel.setForeground(Color.WHITE);
frame.getContentPane().add(panel);
panel.setLayout(null);
panel.hide();
JLabel lblName = new JLabel("Name:");
lblName.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblName.setBounds(10, 11, 46, 14);
panel.add(lblName);
JLabel lblDate = new JLabel("Date:");
lblDate.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblDate.setBounds(10, 36, 46, 14);
panel.add(lblDate);
JLabel lblLocation = new JLabel("Time:\r\n");
lblLocation.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblLocation.setBounds(10, 61, 60, 14);
panel.add(lblLocation);
JLabel lblLocation_1 = new JLabel("Location:");
lblLocation_1.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblLocation_1.setBounds(10, 86, 60, 14);
panel.add(lblLocation_1);
JLabel lblRe = new JLabel("Referee");
lblRe.setFont(new Font("Yu Gothic", Font.BOLD, 13));
lblRe.setBounds(10, 111, 60, 14);
panel.add(lblRe);
textField = new JTextField();
textField.setBounds(76, 8, 127, 20);
panel.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(76, 33, 127, 20);
panel.add(textField_1);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(76, 58, 127, 20);
panel.add(textField_2);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(76, 86, 127, 20);
panel.add(textField_3);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_4.setBounds(76, 108, 127, 20);
panel.add(textField_4);
JCheckBox checkBox = new JCheckBox("");
checkBox.setBounds(209, 7, 21, 23);
panel.add(checkBox);
JCheckBox checkBox_1 = new JCheckBox("");
checkBox_1.setBounds(209, 32, 21, 23);
panel.add(checkBox_1);
JCheckBox checkBox_2 = new JCheckBox("");
checkBox_2.setBounds(209, 57, 21, 23);
panel.add(checkBox_2);
JCheckBox checkBox_3 = new JCheckBox("");
checkBox_3.setBounds(209, 82, 21, 23);
panel.add(checkBox_3);
JCheckBox checkBox_4 = new JCheckBox("");
checkBox_4.setBounds(209, 107, 21, 23);
panel.add(checkBox_4);
JPanel panel_2 = new JPanel();
panel_2.setBounds(20, 290, 358, 210);
panel_2.setLayout(null);
JButton btnNewNote = new JButton("New Note");
btnNewNote.setFont(new Font("Yu Gothic", Font.BOLD, 16));
btnNewNote.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame noteFrame = new JFrame();
noteFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
noteFrame.setLocationRelativeTo(panel);
noteFrame.pack();
noteFrame.setSize(nHEIGHT, nWIDTH);
noteFrame.getContentPane().add(panel_2);
noteFrame.setVisible(true);
}
});
btnNewNote.setBounds(293, 16, 461, 151);
panel.add(btnNewNote);
JLabel lblNotes = new JLabel("Notes:");
lblNotes.setBounds(10, 0, 46, 23);
panel_2.add(lblNotes);
lblNotes.setFont(new Font("Yu Gothic", Font.BOLD, 13));
JButton btnSaveCreate = new JButton("Create & Save");
btnSaveCreate.setBounds(237, 177, 131, 23);
panel_2.add(btnSaveCreate);
JCheckBox checkBox_5 = new JCheckBox("");
checkBox_5.setBounds(210, 177, 21, 23);
panel_2.add(checkBox_5);
btnSaveCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String NAME = textField.getText();
String DATE = textField_1.getText();
String TIME = textField_2.getText();
String LOCATION = textField_3.getText();
String Referee = textField_4.getText();
if(checkBox.isSelected() && checkBox_1.isSelected() && checkBox_2.isSelected() && checkBox_2.isSelected() && checkBox_3.isSelected() && checkBox_4.isSelected() && checkBox_5.isSelected())
{
infoBox("Met with " + NAME + " on " + DATE + " #" + TIME + ", and went to " + LOCATION + ", then I was introduced by " + Referee, "Paragraph");
}
else {
errorMessage("Error: Please validate entries!", "Error!");
}
}
});
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButton.hide();
panel.setVisible(true);
}
});
try {
String content = textField_5.getText();
File file = new File("/users/David/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content); //step2: write it
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace(); **** *****
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Any Help is greatly appreciated!
You just forgot to add the } in this statement:
catch (IOException e) {
e.printStackTrace();
}
Just as Andrew Thompson said: simple indentation would have made this error a lot easier to spot if done properly, and should be used as common practice.
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