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.
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);
}
}
}
Im trying to sort my GUI so it will be able to use the methods from the other classes
in the JProject i also want to call it from the main.
The action listeners i had just learnt today so i need feedback on what to do there as well.
Any Ideas??
It would be a great help to get some insight on this!
(I am new to stack so my code posted in the explanation and in the actual script idk
why).
package test;
import javax.swing.JPanel;
import javax.swing.JLabel;
import com.jgoodies.forms.factories.DefaultComponentFactory;
import java.awt.Container;
import java.awt.SystemColor;
import java.awt.Color;
import javax.swing.JRadioButton;
import java.awt.Font;
import java.io.File;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.util.ArrayList;
import java.util.Scanner;
//Main Method
public class TextUI{
protected StormTracker var;
public TextUI(StormTracker var)
{
this.var=var;
}
public static void main(String[] args)
{
ShowGUI gui = new SHOWGUI();
while(gui.running)
if(gui.buttonPress == -1)
continue;
StormTracker obj = new StormTracker("config.txt");
WeatherAuthority wa = new WeatherAuthority("stormfile.txt");
int xcoord=0;
int ycoord=0;
TextUI uiobj = new TextUI(obj);
Scanner scan = new Scanner(System.in);
while(true){
System.out.println("---------------------------------------------------------------");
System.out.println("Welcome to the StormTracker Application.");
System.out.println("Type the following commands to carry out the associated actions.");
System.out.println("\n");
System.out.println("----------------------{Commands Menu}---------------------
-------");
System.out.println("(1) NEW STORM x y");
System.out.println("(2) UPGRADE <name of storm>");
System.out.println("(3) DOWNGRADE <name of storm>");
System.out.println("(4) TICK");
System.out.println("(5) EXIT");
System.out.println("----------------------------------------------------------------");
String option=scan.nextLine();
if (option.substring(0,4).equals("TICK")){
obj.tick();
continue;
}
if (option.substring(0,9).equals("NEW STORM")){
if(option.length()==13){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,13));
}
else if (option.length()==14){
if (option.substring(11,12).equals(" ")){
xcoord = Integer.parseInt(option.substring(10,11));
ycoord = Integer.parseInt(option.substring(12,14));
}
else{
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,14));
}
}
else if (option.length()==15){
xcoord = Integer.parseInt(option.substring(10,12));
ycoord = Integer.parseInt(option.substring(13,15));
}
obj.newstorm(xcoord,ycoord);
}
if (option.substring(0,7).equals("UPGRADE")){
String storm_name = option.substring(8);
obj.upgrade(storm_name);
}
if (option.substring(0,9).equals("DOWNGRADE")){
String storm_name = option.substring(10);
obj.downgrade(storm_name);
}
}
}
//GUI Class
public ShowGUI extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
System.out.println("GUI Successfully Loaded");
createAndShow();
setToolTipText("Select Storm");
setBackground(Color.WHITE);
}
private void createAndShow(){
JPanel mainFrame = new JPanel("Storm Tracker V1.0");
}
private void addComponents(Container pane){
pane.setLayout(null);
JLabel lblStormTrackerV = DefaultComponentFactory.getInstance().createTitle("
Storm Tracker V1.0");
lblStormTrackerV.setBackground(SystemColor.activeCaption);
lblStormTrackerV.setFont(new Font("Calibri", Font.PLAIN, 22));
lblStormTrackerV.setBounds(162, 11, 430, 41);
add(lblStormTrackerV);
JRadioButton rdbtnMap = new JRadioButton("MAP");
rdbtnMap.setBounds(283, 59, 72, 23);
add(rdbtnMap);
JRadioButton rdbtnBulletin = new JRadioButton("Bulletin");
rdbtnBulletin.setBounds(406, 60, 72, 23);
add(rdbtnBulletin);
textField = new JTextField();
textField.setBounds(61, 103, 72, 20);
add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(61, 134, 72, 20);
add(textField_1);
textField_1.setColumns(10);
JTextPane txtpnX = new JTextPane();
txtpnX.setText("X:");
txtpnX.setBounds(23, 103, 28, 20);
add(txtpnX);
JTextPane txtpnY = new JTextPane();
txtpnY.setText("Y:");
txtpnY.setBounds(23, 134, 12, 20);
add(txtpnY);
JTextPane txtpnSpeed = new JTextPane();
txtpnSpeed.setText("Speed:");
txtpnSpeed.setBounds(10, 165, 41, 20);
add(txtpnSpeed);
textField_2 = new JTextField();
textField_2.setBounds(61, 165, 72, 20);
add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(61, 196, 72, 20);
add(textField_3);
textField_3.setColumns(10);
JTextPane txtpnSpeed_1 = new JTextPane();
txtpnSpeed_1.setText("Speed:");
txtpnSpeed_1.setBounds(10, 196, 41, 20);
add(txtpnSpeed_1);
JTextPane txtpnBearing = new JTextPane();
txtpnBearing.setText("Bearing:");
txtpnBearing.setBounds(10, 227, 41, 20);
add(txtpnBearing);
textField_4 = new JTextField();
textField_4.setBounds(61, 227, 72, 20);
add(textField_4);
textField_4.setColumns(10);
File input = new File(new
FileReader("C:\\Users\\620086793\\Documents\\test\\src\\test"));
List<String> strings = new ArrayList<String>();
try {
String line = null;
while (( line = input.readLine()) != null){
strings.add(line);
}
}
catch (FileNotFoundException e) {
System.err.println("Error, file " + "C:\\Users\\620086793\\Documents\\test\\src\\test" + " didn't exist.");
}
finally {
input.close();
}
String[] lineArray = strings.toArray(new String[]{});
JComboBox comboBox = new JComboBox(lineArray);
JComboBox comboBox = new JComboBox();
comboBox.setToolTipText("Select Storm");
comboBox.setEditable(true);
comboBox.setBounds(20, 60, 113, 20);
add(comboBox);
JButton btnUpdate = new JButton("UPDATE");
btnUpdate.setFont(new Font("Calibri", Font.BOLD, 11));
btnUpdate.setBounds(10, 273, 110, 28);
add(btnUpdate);
JButton btnNewButton = new JButton("NEW STORM\r\n");
btnNewButton.setFont(new Font("Calibri", Font.BOLD, 11));
btnNewButton.setBounds(10, 312, 110, 28);
add(btnNewButton);
addActionListeners();
pane.add(rdbtnMap);
pane.add(rdbtnBulletin);
pane.add(textField);
pane.add(textField_1);
pane.add(textField_2);
pane.add(textField_3);
pane.add(textField_4);
pane.add(comboBox);
pane.add(btnUpdate);
pane.add(btnNewButton);
}
//Im not sure how to properly add the action listeners i first learned about them
today.
private void addActionListeners(){
rdbtnMap.addActionListener(new ActionListener){
public void actionPerformed(ActionEvent ){
}
}
rdbtnBulletin.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_2.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_3.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
textField_4.addActionListener(){
public void actionPerformed(ActionEvent ){
stormTracker.tick = textField_4;
}
}
comboBox.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
btnUpdate.addActionListener(){
public void actionPerformed(ActionEvent ){
obj.upgrade() = btnUpdate;
return btnUpdate;
}
}
btnNewButton.addActionListener(){
public void actionPerformed(ActionEvent ){
}
}
}
I made an application that has some TextFields. When I click to search an item it popups JTable that contains a list of items. But the problem is how we can do it. I have tried many times but I failed please help in my project.
this is my code that i have tried
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FocusTraversalPolicy;
import javax.swing.JFrame;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Font;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import com.alee.laf.WebLookAndFeel;
import com.toedter.calendar.JDateChooser;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.CardLayout;
import java.awt.Component;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class DailySales3 {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField ItemID;
private JTextField ItemName;
private JTextField Stock;
private JTextField Qnty;
private JTextField UnitPrice;
private JTextField Tax;
private JTextField Amount;
private JTextField Discount;
private Connection con;
private String query,auto;
private PreparedStatement PStat;
private ResultSet res;
private DefaultTableModel model,model1;
private JTable table_2;
private JScrollPane scrollPane;
private double AmountGet=0.0,AmountCal=0.0,AmountResult=0.0;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WebLookAndFeel.install();
DailySales3 window = new DailySales3();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public DailySales3() {
initialize();
con=Database.Database();
}
public void AmountCalculate()
{
AmountGet=Double.parseDouble(UnitPrice.getText());
AmountCal=Double.parseDouble(Qnty.getText());
AmountResult=AmountCal*AmountGet;
Amount.setText(Double.toString(AmountResult));
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 1229, 658);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 1213, Short.MAX_VALUE)
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 630, Short.MAX_VALUE)
);
panel.setLayout(null);
JLabel label = new JLabel("Bill No");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("Georgia", Font.BOLD, 12));
label.setBounds(10, 11, 73, 35);
panel.add(label);
textField = new JTextField();
textField.setFont(new Font("Georgia", Font.BOLD, 15));
textField.setEditable(false);
textField.setColumns(10);
textField.setBounds(82, 11, 132, 35);
panel.add(textField);
JLabel label_1 = new JLabel("Bill Date");
label_1.setHorizontalAlignment(SwingConstants.CENTER);
label_1.setFont(new Font("Georgia", Font.BOLD, 12));
label_1.setBounds(224, 11, 73, 35);
panel.add(label_1);
JDateChooser dateChooser = new JDateChooser();
dateChooser.setFont(new Font("Georgia", Font.BOLD, 15));
dateChooser.setBounds(296, 11, 132, 35);
panel.add(dateChooser);
JLabel label_2 = new JLabel("Sales Type");
label_2.setHorizontalAlignment(SwingConstants.CENTER);
label_2.setFont(new Font("Georgia", Font.BOLD, 12));
label_2.setBounds(438, 11, 73, 35);
panel.add(label_2);
JComboBox comboBox = new JComboBox();
comboBox.setFont(new Font("Georgia", Font.BOLD, 15));
comboBox.setBounds(524, 10, 190, 35);
panel.add(comboBox);
JLabel label_3 = new JLabel("Customers");
label_3.setHorizontalAlignment(SwingConstants.CENTER);
label_3.setFont(new Font("Georgia", Font.BOLD, 12));
label_3.setBounds(724, 11, 73, 35);
panel.add(label_3);
textField_1 = new JTextField();
textField_1.setFont(new Font("Georgia", Font.BOLD, 15));
textField_1.setColumns(10);
textField_1.setBounds(797, 12, 210, 35);
panel.add(textField_1);
JButton button = new JButton("");
button.setBounds(1016, 12, 38, 35);
panel.add(button);
JPanel panel_1 = new JPanel();
panel_1.setBounds(10, 68, 997, 43);
panel.add(panel_1);
JLabel lblItemId = new JLabel("Item ID");
lblItemId.setHorizontalAlignment(SwingConstants.CENTER);
lblItemId.setPreferredSize(new Dimension(91, 35));
lblItemId.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblItemId);
JLabel lblItemName = new JLabel("Item Name");
lblItemName.setPreferredSize(new Dimension(273, 35));
lblItemName.setHorizontalAlignment(SwingConstants.CENTER);
lblItemName.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblItemName);
JLabel lblStock = new JLabel("Stock");
lblStock.setPreferredSize(new Dimension(86, 35));
lblStock.setHorizontalAlignment(SwingConstants.CENTER);
lblStock.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblStock);
JLabel lblQnty = new JLabel("Qnty");
lblQnty.setPreferredSize(new Dimension(86, 35));
lblQnty.setHorizontalAlignment(SwingConstants.CENTER);
lblQnty.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblQnty);
JLabel lblUnitPrice = new JLabel("Unit Price");
lblUnitPrice.setPreferredSize(new Dimension(123, 35));
lblUnitPrice.setHorizontalAlignment(SwingConstants.CENTER);
lblUnitPrice.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblUnitPrice);
JLabel lblTax = new JLabel("Tax (%)");
lblTax.setPreferredSize(new Dimension(86, 35));
lblTax.setHorizontalAlignment(SwingConstants.CENTER);
lblTax.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblTax);
JLabel lblDiscount = new JLabel("Discount (%)");
lblDiscount.setPreferredSize(new Dimension(86, 35));
lblDiscount.setHorizontalAlignment(SwingConstants.CENTER);
lblDiscount.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblDiscount);
JLabel lblAmount = new JLabel("Amount");
lblAmount.setPreferredSize(new Dimension(123, 35));
lblAmount.setHorizontalAlignment(SwingConstants.CENTER);
lblAmount.setFont(new Font("Georgia", Font.BOLD, 12));
panel_1.add(lblAmount);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 112, 997, 43);
panel.add(panel_2);
panel_2.setLayout(null);
ItemID = new JTextField();
ItemID.setBounds(5, 5, 89, 34);
ItemID.setFont(new Font("Georgia", Font.BOLD, 15));
ItemID.setColumns(10);
panel_2.add(ItemID);
ItemName = new JTextField();
ItemName.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(ItemName.getText().equals(""))
{
while(table_2.getRowCount()>0)
{
model.removeRow(0);
}
}
else if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
table_2.requestFocus();
table_2.changeSelection(0, 0, false, false);
}
else
{
try {
while(table_2.getRowCount()>0)
{
model.removeRow(0);
}
query="Select Item_No,Item_Name,Current_Stock,Unit_Price,Tax,Discount from StockEntry where Item_Name like '"+ItemName.getText().trim()+"%'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
while(res.next())
{
String ItemNo=res.getString("Item_No");
String ItemName=res.getString("Item_Name");
double CStock=res.getDouble("Current_Stock");
double PRate=res.getDouble("Unit_Price");
double tax=res.getDouble("Tax");
double discount=res.getDouble("Discount");
Object row[]= {ItemNo,ItemName,CStock,PRate,tax,discount};
model.addRow(row);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
});
ItemName.setBounds(98, 5, 276, 34);
ItemName.setFont(new Font("Georgia", Font.BOLD, 15));
ItemName.setColumns(10);
panel_2.add(ItemName);
Stock = new JTextField();
Stock.setBounds(376, 5, 89, 34);
Stock.setFont(new Font("Georgia", Font.BOLD, 15));
Stock.setColumns(10);
panel_2.add(Stock);
Qnty = new JTextField();
Qnty.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
model1=(DefaultTableModel)table.getModel();
String itemno=ItemID.getText();
String itemname=ItemName.getText();
String qnty=Qnty.getText();
String unitprice=UnitPrice.getText();
String tax=Tax.getText();
String discount=Discount.getText();
String amount=Amount.getText();
Object rows[]= {itemno,itemname,qnty,unitprice,tax,discount,amount};
model1.addRow(rows);
}
}
});
Qnty.setBounds(469, 5, 89, 34);
Qnty.setFont(new Font("Georgia", Font.BOLD, 15));
Qnty.getDocument().addDocumentListener(new DocumentListener()
{
#Override
public void changedUpdate(DocumentEvent arg0) {
AmountCalculate();
}
#Override
public void insertUpdate(DocumentEvent arg0) {
AmountCalculate();
}
#Override
public void removeUpdate(DocumentEvent arg0) {
}
});
Qnty.setColumns(10);
panel_2.add(Qnty);
UnitPrice = new JTextField();
UnitPrice.setBounds(561, 5, 122, 34);
UnitPrice.setFont(new Font("Georgia", Font.BOLD, 15));
UnitPrice.setColumns(10);
panel_2.add(UnitPrice);
Tax = new JTextField();
Tax.setBounds(687, 5, 89, 34);
Tax.setFont(new Font("Georgia", Font.BOLD, 15));
Tax.setColumns(10);
panel_2.add(Tax);
Discount = new JTextField();
Discount.setBounds(778, 5, 89, 34);
Discount.setFont(new Font("Georgia", Font.BOLD, 15));
Discount.setColumns(10);
panel_2.add(Discount);
Amount = new JTextField();
Amount.setBounds(869, 5, 122, 34);
Amount.setFont(new Font("Georgia", Font.BOLD, 15));
Amount.setColumns(10);
panel_2.add(Amount);
scrollPane = new JScrollPane();
scrollPane.setBounds(10, 156, 997, 412);
panel.add(scrollPane);
table_2 = new JTable();
table_2.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
try
{
int row=table_2.getSelectedRow();
String TableClicked=(table_2.getModel().getValueAt(row, 0).toString());
query="Select * from StockEntry where Item_No='"+TableClicked+"'";
PStat=con.prepareStatement(query);
res=PStat.executeQuery();
if(res.next())
{
String Itemno=res.getString("Item_No");
ItemID.setText(Itemno);
String itemName=res.getString("Item_Name");
ItemName.setText(itemName);
String PurchaseRate=Double.toString(res.getDouble("Unit_Price"));
UnitPrice.setText(PurchaseRate);
String stock=Double.toString(res.getDouble("Current_Stock"));
Stock.setText(stock);
String tax=Double.toString(res.getDouble("Tax"));
Tax.setText(tax);
String disc=Double.toString(res.getDouble("Discount"));
Discount.setText(disc);
}
}
catch(Exception e1)
{
e1.printStackTrace();
}
finally
{
try
{
PStat.close();
res.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
while(table_2.getRowCount()>0)
{
model.removeRow(0);
}
Qnty.requestFocus();
}
}
});
model=(DefaultTableModel)table_2.getModel();
model.addColumn("Item ID");
model.addColumn("Item Name");
model.addColumn("Qnty");
model.addColumn("Unit Price");
model.addColumn("Tax (%)");
model.addColumn("Discount (%)");
model.addColumn("Amount");
table_2.setRowHeight(30);
table_2.getTableHeader().setFont(new Font("Georgia", Font.BOLD, 14));
table_2.setFont(new Font("Georgia", Font.BOLD, 17));
scrollPane.setViewportView(table_2);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(10, 156, 997, 412);
panel.add(scrollPane_1);
table = new JTable();
model1=(DefaultTableModel)table.getModel();
model1.addColumn("Item ID");
model1.addColumn("Item Name");
model1.addColumn("Qnty");
model1.addColumn("Unit Price");
model1.addColumn("Tax (%)");
model1.addColumn("Discount (%)");
model1.addColumn("Amount");
table.setRowHeight(30);
table.setFont(new Font("Georgia", Font.BOLD, 17));
scrollPane_1.setViewportView(table);
frame.getContentPane().setLayout(groupLayout);
}
}
I'm a beginer in Java GUI, and i have an issue with trying to toggle between panel in other class.
My main Class "MyBoxGUI" has 2 Panels, "Login" and "UserMenu"
The default is "Login" panel, when pressing "OK" the window moved to "UserMenu" Panel.
So far so good while in the same class.
The issue is, when i set a new panel in new class and setvisibe that panel, i can't go back to "UserMenu" panel - (The actionlistener is working fine).
Can someone help me please?
MyBoxGUI Class
package main;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import java.awt.Component;
//import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.Toolkit;
import GUIs.*;
//import ocsf.client.*;
public class MyBoxGUI extends JPanel
{
private Mtds mtd;
public JFrame frmMybox;
private static JTextField UserName;
private static JTextField port;
private static JTextField IP;
private static JPasswordField passwordField;
public final JPanel Login = new JPanel();
public final JPanel UserMenu = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
MyBoxGUI window = new MyBoxGUI();
window.frmMybox.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyBoxGUI()
{
mtd = new Mtds();
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frmMybox = new JFrame();
frmMybox.setFont(new Font("Tempus Sans ITC", Font.BOLD, 15));
// frmMybox.setIconImage(Toolkit.getDefaultToolkit().getImage(MyBoxGUI.class.getResource("/images/gift-ideas-gift-card-bridal-gift-baby-shower-gift-gift-box-groom-gift-christmas-gift-party-gift-gift-for-wedding-friend-gift-birthday-gift-baby-gift-good-gift-box-ideas-for-friend-necklace-gift-box.jpg")));
frmMybox.setBounds(100, 100, 800, 500);
frmMybox.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMybox.getContentPane().setLayout(new CardLayout(0, 0));
frmMybox.setTitle("MyBox");
frmMybox.getContentPane().add(Login);
Login.setLayout(null);
JButton btnNewButton = new JButton("OK");
btnNewButton.addActionListener(new ActionListener()
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0)
{
Boolean ok = false;
String UName, Pass, Prt, SIP;
UName = UserName.getText();
Pass = passwordField.getText();
Prt = port.getText();
SIP = IP.getText();
if( ( mtd.isUserValid(UName) && mtd.isPasswordValid(Pass) && mtd.isPortValid(Prt) && mtd.isIPValid(SIP))
&& ( !UName.equals("") && !Pass.equals("") && !Prt.equals("") && !SIP.equals("") ) )
ok = true;
else
{
if(!mtd.isUserValid(UName) || UName.equals(""))
JOptionPane.showMessageDialog(frmMybox,"User Name Can Contain Only The Following Characters: ( 0-9 , a-z , A-Z , _ )"
+ " ","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPasswordValid(Pass) || Pass.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Invalid characters","Error Message",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isPortValid(Prt) || Prt.equals(""))
JOptionPane.showMessageDialog(frmMybox,"Port Can Contain Only Numbers","Invalid characters",JOptionPane.WARNING_MESSAGE);
else if(!mtd.isIPValid(SIP) || SIP.equals(""))
JOptionPane.showMessageDialog(frmMybox,"IP Address Can Contain Only Numbers seperated By Dots '.' ","Invalid characters",JOptionPane.WARNING_MESSAGE);
}
if(ok)
{
//LoginController user = new LoginController();
//chat= new ClientGUI(IP.getText(),port.getText());
//client = ClientGUI.getClient();
//msg=new Msg("login",user);
//client.handleMessageFromClientUI(msg);
setScreen(Login,UserMenu);
// frmMybox.getContentPane().add(UserMenu, "UserMenu");
// UserMenu.setVisible(true);
// Login.setVisible(false);
}
}
});
btnNewButton.setBounds(344, 313, 82, 48);
Login.add(btnNewButton);
JLabel lblWellcomeToMybox = new JLabel("Wellcome to MyBox");
lblWellcomeToMybox.setForeground(new Color(51, 204, 255));
lblWellcomeToMybox.setFont(new Font("Arial", Font.PLAIN, 36));
lblWellcomeToMybox.setBounds(224, 23, 327, 42);
Login.add(lblWellcomeToMybox);
JLabel lblUserName = new JLabel("User Name:");
lblUserName.setBounds(268, 109, 89, 14);
lblUserName.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblUserName);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(268, 139, 69, 14);
lblPassword.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblPassword);
JLabel lblServerPort = new JLabel("Server port:");
lblServerPort.setBounds(268, 197, 82, 14);
lblServerPort.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerPort);
JLabel lblServerIp = new JLabel("Server IP:");
lblServerIp.setBounds(266, 222, 71, 14);
lblServerIp.setFont(new Font("Arial", Font.PLAIN, 14));
Login.add(lblServerIp);
UserName = new JTextField();
UserName.setBounds(406, 107, 96, 20);
Login.add(UserName);
UserName.setColumns(10);
port = new JTextField();
port.setBounds(406, 195, 96, 20);
Login.add(port);
port.setColumns(10);
IP = new JTextField();
IP.setBounds(406, 220, 96, 20);
Login.add(IP);
IP.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(406, 137, 96, 20);
Login.add(passwordField);
frmMybox.getContentPane().add(UserMenu, "User Menu");
UserMenu.setLayout(null);
JButton LeaveGOI = new JButton("Back");
LeaveGOI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UserMenu,Login);
}
});
LeaveGOI.setBounds(10, 66, 153, 23);
UserMenu.add(LeaveGOI);
JButton btnJoinAGoi = new JButton("Join a GOI");
btnJoinAGoi.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
}
});
btnJoinAGoi.setBounds(10, 100, 153, 23);
UserMenu.add(btnJoinAGoi);
JButton btnSearchForA = new JButton("Search for a GOI");
btnSearchForA.setBounds(10, 134, 153, 23);
UserMenu.add(btnSearchForA);
JButton btnCreateAGoi = new JButton("Create a GOI");
btnCreateAGoi.setBounds(10, 32, 153, 23);
UserMenu.add(btnCreateAGoi);
JButton btnFilesSharedWith = new JButton("Files shared with you");
btnFilesSharedWith.setBounds(271, 66, 153, 23);
UserMenu.add(btnFilesSharedWith);
JButton btnUploadAFile = new JButton("Upload a file");
btnUploadAFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
JPanel UpLoad = new UploadFile();
setScreen(UserMenu,UpLoad);
// frmMybox.getContentPane().add(UpLoad, "UpLoad");
// UserMenu.setVisible(false);
// UpLoad.setVisible(true);
}
});
btnUploadAFile.setBounds(271, 32, 153, 23);
UserMenu.add(btnUploadAFile);
JButton btnSignout = new JButton("Sign-Out");
btnSignout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int dialog=JOptionPane.showConfirmDialog(Login, getUserName()+", are you sure you wants to leave?", "Do you want to leave?", JOptionPane.YES_NO_OPTION);
if(dialog==0){
//client.quit();
}
}
});
btnSignout.setBounds(293, 227, 131, 23);
UserMenu.add(btnSignout);
JButton btnHelpme = new JButton("Help-Me");
btnHelpme.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JOptionPane.showMessageDialog(Login,"Hello "+ getUserName()+", wellcom to Mybox!\n"
+ "Inside GOIs buttons you can ask to join, leave and even create a GOI.\n"
+ "Inside Files buttons you can check and edit files people shared with you.\n"
+ "You can even become an uploader and share files you own.\n"
+ "We wish you good luck and have fun using MyBox!");
}
});
btnHelpme.setBounds(10, 227, 131, 23);
UserMenu.add(btnHelpme);
}
public static String getUserName(){
return UserName.getText();
}
#SuppressWarnings("deprecation")
public static String getPassword(){
return passwordField.getText();
}
public static String getIP(){
return IP.getText();
}
public static String getPort(){
return port.getText();
}
public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
}
}
UploadFile Class
package GUIs;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import main.MyBoxGUI;
public class UploadFile extends MyBoxGUI {
private JTextField textField;
/**
* Create the panel.
*/
public static final JPanel UpLoad = new JPanel();
public UploadFile()
{
setBounds(100, 100, 800, 500);
setLayout(null);
JButton btnNewButton = new JButton("Back");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
setScreen(UpLoad,UserMenu);
System.out.print("A+++");
}
});
btnNewButton.setBounds(126, 145, 205, 30);
add(btnNewButton);
textField = new JTextField();
textField.setBounds(409, 150, 300, 20);
add(textField);
textField.setColumns(10);
JButton btnDone = new JButton("Done");
btnDone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDone.setBounds(365, 223, 89, 30);
add(btnDone);
JButton btnHelpMe = new JButton("Help Me");
btnHelpMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnHelpMe.setBounds(188, 390, 122, 52);
add(btnHelpMe);
JButton SignOut = new JButton("Sign-Out");
SignOut.setBounds(501, 392, 122, 48);
add(SignOut);
}
}
public void setScreen(JPanel fls, JPanel tru)
{
frmMybox.getContentPane().add(tru);
tru.setVisible(true);
fls.setVisible(false);
frmMybox.getContentPane().revalidate();
frmMybox.getContentPane().repaint();
}
update your setScreen method as above.
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.