DriverManager won't seem to connect DB - java

I'm working on a school assignment for a client/server application and can't seem to connect using the JDBC DriverManager. I have set up the driver for the schema I am using, it351, and seem to have everything in order but it never fires through the connection to tell me it's connected. Any words of wisdom from the crowd? I do show the driver in the services task pane and I have saved my password so I don't have to share it with the class. Thanks.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.sql.*;
public class GUI extends JFrame
{
private JButton custButton;
private JButton prodButton;
private JButton exitButton;
private JPanel p1;
private JPanel p2;
private JPanel p3;
private JTextArea data;
// private String message = ""; // message from server
private String localhost; // host server for this application
public GUI()
{
super( "Database Data Retrieval" );
setSize(825, 800);
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container c = new Container();
add(c);
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
// create and add jpanels for components
p1 = new JPanel(); //(new FlowLayout(FlowLayout.CENTER));
c.add(p1);
p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
c.add(p2);
p3 = new JPanel(new FlowLayout(FlowLayout.CENTER));
c.add(p3);
data = new JTextArea(35, 70);
JScrollPane dataScroll = new JScrollPane(data);
dataScroll.setPreferredSize(null);
p1.add(data);
p1.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
data.setBorder(BorderFactory.createLineBorder(Color.black));
data.setVisible(true);
// create buttons
p2.setBorder(BorderFactory.createTitledBorder( null, "Database Controls"));
custButton = new JButton( "Retrieve Customer Data");
p2.add (custButton);
p2.add(Box.createRigidArea(new Dimension(50,0)));
prodButton = new JButton( "Retrieve Product Data" );
p2.add(prodButton);
p2.add(Box.createVerticalGlue());
p2.add(Box.createHorizontalGlue());
exitButton = new JButton (" Exit ");
p3.add(exitButton);
p3.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));
// register events for buttons
ButtonHandler handler = new ButtonHandler();
custButton.addActionListener( handler );
prodButton.addActionListener( handler );
exitButton.addActionListener( handler );
}
private void displayMessage( final String messageToDisplay )
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run() // updates displayArea
{
data.append( messageToDisplay );
} // end method run
} // end anonymous inner class
); // end call to SwingUtilities.invokeLater
} // end method displayMessage
private void connect()
{
Connection conn = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/it351?zeroDateTimeBehavior=convertToNull", "root", ""); //Connect
displayMessage("******* Connection created successfully *******"); //informs user of connection
}
catch (Exception err)
{
}
}
private class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed( ActionEvent event )
{
if (event.getSource() == custButton)
{
displayMessage( "******* Attempting connection *******\n" );
connect();
}
if (event.getSource() == prodButton)
{
}
if (event.getSource() == exitButton)
{
System.exit(0);
}
}// end of actionperformed
}// end of buttonhandler
}// end of GUI class

Related

Swing window doesn't return value after x time

I'm trying to do a call simulator in Swing and for some reason the window won't budge.
My goal is to open a seperate window that returns true or false if a button is pressed or another has been pressed. The user should have 15 seconds to do something, otherwise it returns false and performs an action.
When it returns, it should finish it's execution. This function is called by another function part of main.
However, due to my lack of experience and idiocy, it doesn't work. Instead, it opens a window (blank) that never closes by itself when it should...
Here's the code:
public static boolean callWindow(Telephone src, Telephone dst) {
Timer t1 = new Timer(15000, e-> {
DateTime date = new DateTime();
Call c = new Call(date, src.getTelephone(), dst.getTelephone(), 0);
dst.addLostCall(c);
});
//Janela para atender
JFrame window = new JFrame();
window.setTitle("Incoming Call");
JLabel telephones = new JLabel();
telephones.setText("From: " + src.getTelephone() + " To: " + dst.getTelephone() );
JButton answerCall = new JButton("Answer");
JButton denyCall = new JButton("Decline");
JLabel status = new JLabel();
answerCall.addActionListener( e -> status.setText("answer") );
denyCall.addActionListener( e -> status.setText("no answer") );
answerCall.setBackground(Color.GREEN);
denyCall.setBackground(Color.RED);
JPanel callInfo = new JPanel();
callInfo.add(telephones);
JPanel callOptions = new JPanel();
callOptions.add(answerCall);
callOptions.add(denyCall);
Container container = window.getContentPane();
container.add(callInfo, BorderLayout.NORTH);
container.add(callOptions);
window.setSize(350,120);
window.setVisible(true);
t1.start();
while (t1.isRunning()) {
if (status.getText().equals("answer")) return true;
if (status.getText().equals("no answer")) return false;
}
return false;
}
I would appreciate to know how this could work and how to despaghettify this horrible code.
I used a JDialog to demonstrate how to close a window after 15 seconds.
Here's the GUI JFrame I created.
Here's the JDialog I created
The JDialog will dispose after 15 seconds. The isAnswered method will return true if the call was answered or false if the call was declined, the JDialog was closed by left-clicking on the X, or when the 15 seconds runs out.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class JDialogTimedGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JDialogTimedGUI());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JDialog Timed GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(
75, 100, 75, 100));
panel.setPreferredSize(new Dimension(400, 200));
JButton button = new JButton("Open JDialog");
button.addActionListener(new ButtonListener());
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
IncomingCall ic = new IncomingCall(frame, "Incoming Call",
"555-1212", "555-2323");
System.out.println("Incoming call: " + ic.isAnswered());
}
}
public class IncomingCall extends JDialog {
private static final long serialVersionUID = 1L;
private boolean answered;
private Timer timer;
public IncomingCall(JFrame frame, String title,
String sourcePhone, String destinationPhone) {
super(frame, true);
this.answered = false;
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
add(createMainPanel(frame, sourcePhone, destinationPhone));
pack();
setLocationRelativeTo(frame);
timer = new Timer(15000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
setVisible(false);
dispose();
timer.stop();
}
});
timer.start();
setVisible(true);
}
private JPanel createMainPanel(JFrame frame,
String sourcePhone, String destinationPhone) {
JPanel panel = new JPanel(new BorderLayout(5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
String s = "From: " + sourcePhone + " To: " + destinationPhone;
JLabel telephones = new JLabel(s);
panel.add(telephones, BorderLayout.BEFORE_FIRST_LINE);
JPanel callOptions = new JPanel();
CallButtonListener listener = new CallButtonListener(this);
JButton answerCall = new JButton("Answer");
answerCall.addActionListener(listener);
answerCall.setBackground(Color.GREEN);
callOptions.add(answerCall);
JButton denyCall = new JButton("Decline");
denyCall.addActionListener(listener);
denyCall.setBackground(Color.RED);
callOptions.add(denyCall);
panel.add(callOptions, BorderLayout.CENTER);
return panel;
}
public void setAnswered(boolean answered) {
this.answered = answered;
}
public boolean isAnswered() {
return answered;
}
}
public class CallButtonListener implements ActionListener {
private IncomingCall incomingCall;
public CallButtonListener(IncomingCall incomingCall) {
this.incomingCall = incomingCall;
}
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
if (button.getText().equals("Answer")) {
incomingCall.setAnswered(true);
} else {
incomingCall.setAnswered(false);
}
incomingCall.dispose();
}
}
}

Close one JFrame before opening another JFrame

I want to close completely one JFrame before opening another .
Consider the code :
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
/**
*
* #author X
*
*/
class ServerConnect extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
/**
* Ctor
*/
ServerConnect()
{
this.setTitle("Sever Side Listener");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
gui.setSize(m_sizeX , m_sizeY);
this.setContentPane(gui);
JPanel labels = new JPanel(new GridLayout(0,1));
JPanel controls = new JPanel(new GridLayout(0,1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
this.setLocation(m_centerX , m_centerY);
this.setSize(m_sizeX , m_sizeY);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
new ServerConnect();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton)
{
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0)
{
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try
{
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try
{
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch(Exception exp)
{
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
this.setVisible(false);
new ServerGUI(ip , s_port);
}
}
}
In actionPerformed() after the user had entered the IP number and port , I set the window to false , i.e :
this.setVisible(false); // don't show the current window
new ServerGUI(ip , s_port); // open another JFrame
I want to close the current JFrame completely, not to set its visibility to false.
How can I do that ?
Regards
Your problem appears that if you call close on the JFrame, the program will exit since you've set its setDefaultCloseOperation to setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);.
Options:
Use a different defaultCloseOperation, one that doesn't close the application, perhaps JFrame.DISPOSE_ON_CLOSE.
Use a JDialog initially instead of a JFrame. These types of windows can't shut down the application. Here is the JDialog and JOptionPane Tutorial
Don't swap JFrames at all, but rather swap views by using a CardLayout. The CardLayout Tutorial link
My own preference is to use a CardLayout as much as possible to avoid annoying the user who usually doesn't appreciate having a bunch of windows flung at him. I also use modal JDialogs when I want to get information from the user in a modal fashion, i.e., where the application absolutely cannot move forward until the user gives the requested information, and non-modal dialogs to present program state monitoring information for the user. I almost never use multiple JFrames in a single application.
Edit
As an aside, I almost never create classes that extend JFrame or any top-level window since I find that much too restricting. Instead most of my GUI type classes are geared towards creating JPanels. The advantage to this is then I can decide when and where I want to put the JPanel, and can change my mind at any time. It could go into a JFrame, a JDialog, a JOptionPane, be a card that is swapped in a CardLayout,... anywhere.
Edit 2
For example, here's a small program that uses your code, slightly modified, and puts it into a JDialog:
My code:
import java.awt.Dialog.ModalityType;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MyServerMain extends JPanel {
private JTextField serverIp = new JTextField(8);
private JTextField serverPort = new JTextField(8);
private ServerConnect serverConnect = new ServerConnect();
private JDialog serverConnectDialog = null;
public MyServerMain() {
serverIp.setFocusable(false);
serverPort.setFocusable(false);
add(new JLabel("Server IP:"));
add(serverIp);
add(new JLabel("Server Port:"));
add(serverPort);
add(new JButton(new SetUpServerAction("Set Up Server", KeyEvent.VK_S)));
}
private class SetUpServerAction extends AbstractAction {
public SetUpServerAction(String name, int keyCode) {
super(name);
putValue(MNEMONIC_KEY, keyCode);
}
#Override
public void actionPerformed(ActionEvent evt) {
if (serverConnectDialog == null) {
Window owner = SwingUtilities.getWindowAncestor(MyServerMain.this);
serverConnectDialog = new JDialog(owner, "Server Set Up",
ModalityType.APPLICATION_MODAL);
serverConnectDialog.getContentPane().add(serverConnect);
serverConnectDialog.pack();
serverConnectDialog.setLocationRelativeTo(owner);
}
serverConnectDialog.setVisible(true);
// when here, the dialog is no longer visible
// so extract information from the serverConnect object
serverIp.setText(serverConnect.getServerIp());
serverPort.setText(serverConnect.getServerPort());
}
}
private static void createAndShowGui() {
MyServerMain mainPanel = new MyServerMain();
JFrame frame = new JFrame("My Server Main");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Your modified code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class ServerConnect extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField m_serverIP;
private JTextField m_serverPort; // you can use also JPasswordField
private JButton m_submitButton;
// location of the jframe
private final int m_centerX = 500;
private final int m_centerY = 300;
// dimensions of the jframe
private final int m_sizeX = 1650;
private final int m_sizeY = 150;
ServerConnect() {
m_serverIP = new JTextField(20);
m_serverPort = new JTextField(20);
JPanel gui = new JPanel(new BorderLayout(3, 3));
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
gui.setSize(m_sizeX, m_sizeY);
setLayout(new BorderLayout()); // !!
add(gui, BorderLayout.CENTER);
JPanel labels = new JPanel(new GridLayout(0, 1));
JPanel controls = new JPanel(new GridLayout(0, 1));
gui.add(labels, BorderLayout.WEST);
gui.add(controls, BorderLayout.CENTER);
labels.add(new JLabel("Server IP: "));
controls.add(m_serverIP);
labels.add(new JLabel("Server Port: "));
controls.add(m_serverPort);
m_submitButton = new JButton("Start Listening");
m_submitButton.addActionListener(this);
gui.add(m_submitButton, BorderLayout.SOUTH);
this.setLocation(m_centerX, m_centerY);
this.setSize(m_sizeX, m_sizeY);
// !! this.pack();
// !! this.setVisible(true);
}
public static void main(String[] args) {
new ServerConnect();
}
#Override
public void actionPerformed(ActionEvent event) {
Object object = event.getSource();
if (object == this.m_submitButton) {
// grab all values from the connection box
// if one of them is missing then display an alert message
String ip = this.m_serverIP.getText().trim();
String port = this.m_serverPort.getText().trim();
if (ip.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter IP address !");
return;
}
if (port.length() == 0) {
JOptionPane.showMessageDialog(null, "Please enter Port number!");
return;
}
int s_port = 0;
try {
// try parse the Port number
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
s_port = Integer.parseInt(port);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "Port number is incorrect!");
return;
}
try {
// try parse the IP address
// throws exception when an incorrect IP address
// is entered , and caught in the catch block
InetAddress.getByName(ip);
}
catch (Exception exp) {
JOptionPane.showMessageDialog(null, "IP address is incorrect!");
return;
}
// !! this.setVisible(false);
// !! new ServerGUI(ip , s_port);
// !!
Window ownerWindow = SwingUtilities.getWindowAncestor(this);
ownerWindow.dispose();
}
}
// !!
public String getServerIp() {
return m_serverIP.getText();
}
// !!
public String getServerPort() {
return m_serverPort.getText();
}
}
Hope this another_Frame frm = new another_Frame();
frm.setVisible(true);
this.dispose();// this represent the fram to close

Which timer to use for GUI in Java

I have been trying to find the best timer to use for the following code (note this is a simplified version of my overall program). My hope is to run a method after 3 seconds.
The problem is with the actionPerformed, checkBlankLogin, and resetLoginBlank and putting a timer to delay resetLoginBlank from happening 3 seconds after checkBlankLogin has happened. But I want all methods in the class Outerframe to continuously run. So checkBlankLogin will keep checking if its blank until the person inputs the information for a "Valid Input" and the Login innerframe will close. But I don't know how to do that... Any help there also?
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
import java.io.*;
import java.io.File;
import java.util.*;
import java.io.FileNotFoundException;
class OuterFrame extends JFrame implements ActionListener
{
Container pane; // container
JDesktopPane outframe; // outer frame
JInternalFrame login; // login frame
//pieces of login frame
JLabel loginLBLtitle;
JPanel loginPanel;
JLabel loginLBLname;
JLabel loginBlankName;
JLabel loginLBLpass;
JLabel loginBlankPass;
JTextField loginTXT;
JPasswordField loginPASS;
JButton loginBUT;
JInternalFrame apple;
OuterFrame()
{
//set up for Outer Frame
super("Application");
setSize(450,240);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outframe = new JDesktopPane();
outframe.setBackground(Color.BLUE);
//set up for Container
pane = getContentPane();
setContentPane(pane);
pane.add(outframe);
//Login Inner Frame
login = new JInternalFrame();
login.setSize(400,200);
login.setLocation(20,20);
login.setTitle("Member Login");
loginLBLtitle = new JLabel("Sign in with netid and your password.");
Font loginFontbody = new Font("SansSerif", Font.PLAIN, 12);
Font loginFonthead = new Font("SansSerif", Font.BOLD, 13);
loginLBLtitle.setFont(loginFonthead);
loginLBLname=new JLabel("User Name:");
loginLBLname.setFont(loginFontbody);
loginLBLpass=new JLabel("Password: ");
loginLBLpass.setFont(loginFontbody);
loginBUT=new JButton("Login");
loginBUT.setFont(loginFontbody);
loginBUT.addActionListener(this);
loginTXT=new JTextField(20);
loginPASS=new JPasswordField(20);
loginBlankName=new JLabel("");
loginBlankPass=new JLabel("");
loginPanel=new JPanel();
loginPanel.add(loginLBLtitle);
loginPanel.add(loginLBLname);
loginPanel.add(loginTXT);
loginPanel.add(loginBlankName);
loginPanel.add(loginLBLpass);
loginPanel.add(loginPASS);
loginPanel.add(loginBlankPass);
loginPanel.add(loginBUT);
//panel.add(lblmess);
login.add(loginPanel);
login.setVisible(true);
//Add Login to Outer Frame
outframe.add(login);
outframe.setSelectedFrame(login);
pane.add(outframe, BorderLayout.CENTER);
setVisible(true);
loginTXT.requestFocus();
}
public void actionPerformed(ActionEvent e)
{
//problem area
if(e.getSource()==loginBUT)
{
String uname=loginTXT.getText();
String passw=new String(loginPASS.getPassword());
int i=0;
while(i!=5)
{
if(checkBlankLogin(uname,passw,loginBlankName,loginBlankPass))
{
resetLoginBlank(loginBlankName,loginBlankPass);
}
else
{
if(!validateUser("accounts.txt",uname,passw,loginLBLtitle))
{
}
}
}
}
public void resetLoginBlank(JLabel loginBlankName, JLabel loginBlankPass)
{
loginBlankName.setText("");
loginBlankPass.setText("");
}
public void resetLoginTitle(JLabel loginBlankTitle)
{
loginBlankTitle.setText("Sign in with netid and your password.");
loginBlankTitle.setForeground(Color.BLACK);
}
public boolean checkBlankLogin(String name, String passw, JLabel loginBlankName, JLabel loginBlankPass)
{
boolean isBlank=false;
if(name.length()<1)
{
loginBlankMess("User name is required.",loginBlankName);
isBlank=true;
}
if(passw.length()<1)
{
loginBlankMess("Password is required.",loginBlankPass);
isBlank=true;
}
return isBlank;
}
public void loginBlankMess(String mess, JLabel lbl)
{
lbl.setText(mess);
lbl.setForeground(Color.RED);
}
public boolean validateUser(String filename, String name, String password, JLabel title)
{
boolean valid = false;
try
{
File file = new File(filename);
Scanner scanner = new Scanner(file);
ArrayList<String> fileInfo = new ArrayList<String>();
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
fileInfo.add(line);
}
String fullLogin = name + " " + password;
if(fileInfo.contains(fullLogin))
{
//loginBlankMess("Valid login",namemess);
valid=true;
}
if(!valid)
{
loginBlankMess("Please enter valid netid and password.", title);
resetLoginTitle(title);
}
}
catch(Exception ie)
{
System.exit(1);
}
return valid;
}
}
public class TheProgram
{
public static void main(String[] args)
{
new OuterFrame();
}
}`
I would check out the following resource (assuming you using Swing for your UI):
How to Use Swing Timers (Oracle)
Swing timers are the easiest in your case. You make your class implement ActionListener, and create a timer object. The timer will call the actionPerformed method when it expires.
import javax.swing.Timer;
class OuterFrame extends JFrame implements ActionListener{
Timer timer = null;
public void actionPerformed(ActionEvent e) {
if(e.getSource()==loginBUT){
//If the action came from the login button
if (checkBlankLogin()){
timer = new Timer(3000, this);
timer.setRepeats(false);
timer.setInitialDelay(3000);
timer.start();
} else if (timer != null){
timer.stop();
}
}else if(e.getSource()==timer){
//If the action came from the timer
resetLoginBlank(namemess,passwmess));
}
}
}

GUI is frozen whent he ftp site is not connected

Here is my main class:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.io.*;
import java.lang.Process.*;
public class FTP {
public static void main (String []args)
{
Runnable runner = new Runnable(){
public void run()
{
LookAndFeel nimbusLook = new LookAndFeel();
nimbusLook.NimbusLookAndFeel();
JFrame frame = new JFrame("BNA FTP Diagnose");
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(540, 420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(150, 150);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
final JMenuItem exitMenuItem = new JMenuItem("Exit");
fileMenu.add(exitMenuItem);
JMenu helpMenu = new JMenu("Help");
menuBar.add(new JPanel());
menuBar.add(helpMenu);
final JMenuItem aboutMenuItem = new JMenuItem("About");
helpMenu.add(aboutMenuItem);
JPanel titlePanel = new JPanel(new BorderLayout());
frame.add(titlePanel, BorderLayout.NORTH);
JLabel titleLabel = new JLabel("FTP Diagnose", JLabel.CENTER);
titleLabel.setFont(new Font(null, Font.BOLD, 14));
titleLabel.setForeground(Color.BLUE);
titlePanel.add(titleLabel);
JPanel gridPanel = new JPanel(new GridLayout(1, 1));
frame.add(gridPanel);
JPanel vendorPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
gridPanel.add(vendorPanel);
final String vendor [] = {"LLesiant" ,"WK-CCH", "Proquest", "Notes", "Research Institute of America", "Thomson",
"BNAI PDF Processing", " TM Portfolios to Indexing", "Postscript to PRODLOGIN1", "www.firstdoor.net", "psp.bna.com", "WEST", "LexisNexis", "McArdle Printing Company",
"Breaking News Email", "Ex Libris", "Pandora", "Bloomberg Law", "Acquire Media Site 1", "Acquire Media Site 2", "Quicksite", "QA Quicksite"};
final JComboBox vendorList = new JComboBox(vendor);
vendorPanel.add(vendorList);
JPanel diagnoseButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
gridPanel.add(diagnoseButtonPanel);
final JButton diagnoseButton = new JButton("Diagnose");
diagnoseButtonPanel.add(diagnoseButton);
JPanel centerPanel = new JPanel(new BorderLayout());
frame.add(centerPanel, BorderLayout.SOUTH);
JPanel commandPanel = new JPanel(new GridLayout(1, 0));
centerPanel.add(commandPanel);
final JTextArea commandResultArea = new JTextArea(7, 0);
JScrollPane scroll = new JScrollPane(commandResultArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
commandPanel.add(scroll);
commandResultArea.setEditable(false);
ActionListener buttonListener = new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
int selectedIndex = vendorList.getSelectedIndex();
String llesiant = "ftp.llesiant.com";
String wkCCH = "FTP1.cch.com";
String proquest = "ftp.proquest.com";
String notes = "notes5.bna.com";
//String lineThree = null;
CommandClass readCommand = new CommandClass();
if (selectedIndex == 0)
{
commandResultArea.setText(readCommand.getCommand(llesiant)); //these return strings
}
else if (selectedIndex == 1)
{
commandResultArea.setText(readCommand.getCommand(wkCCH));
}
else if (selectedIndex == 2)
{
commandResultArea.setText(readCommand.getCommand(proquest));
}
else if (selectedIndex == 3)
{
commandResultArea.setText(readCommand.getCommand(notes));
}
}
};
diagnoseButton.addActionListener(buttonListener);
ActionListener exitListener = new ActionListener (){
public void actionPerformed(ActionEvent el)
{
if (el.getSource()== exitMenuItem)
{
JOptionPane.showMessageDialog(null, "FTP Program will exit now!");
System.exit(0);
}
}
};
exitMenuItem.addActionListener(exitListener);
ActionListener aboutListener = new ActionListener()
{
public void actionPerformed(ActionEvent al)
{
if (al.getSource()== aboutMenuItem)
{
JOptionPane.showMessageDialog(null, "This Software was made for Editors to. \nDiagnose BNA Bloomberg client FTP site.");
}
}
};
aboutMenuItem.addActionListener(aboutListener);
}
};
EventQueue.invokeLater(runner);
}
}
Here is my Look and feel class:
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class LookAndFeel {
public void NimbusLookAndFeel()
{
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
}
}
}
Here is my CommandClass:
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class CommandClass {
public String getCommand(String ftpSite){
String command = "ftp ";
StringBuffer output = new StringBuffer();
try{
Process p = Runtime.getRuntime().exec(command +ftpSite);
InputStreamReader ir = new InputStreamReader (p.getInputStream());
int outputChar = 0;
while((outputChar = ir.read()) != -1){
output.append((char)outputChar);
if(!ir.ready()){ // If the next read is not guarenteed, come out of loop.
break;
}
}
ir.close();
JOptionPane.showMessageDialog(null, "FTP is connected");
}catch (IOException e){
e.printStackTrace();
}
return output.toString();
}
}
I have this FTP GUI which suppose to connect to an FTP site and return the status. If it's connected it shows the connection prompt.
I got the JTextArea to show the message when the FTP connection is established, but when it's not connected to the ftp site such as my 4th ftp site which is notes5.bna.com it freezes the program. Also a small problem is if you have the program FTP to a site like this "shlfsdklaflkhasdlhfas". It returns the ftp site is not found only after the JOptionPane shows that FTP is connected. I am not sure what's wrong with it.
The reason that notes5.bna.com is freezing is that the site is not responding to FTP connection requests. As you are simply using Runtime#exec to make the connection, this will block indefinitely for a response. Consider using a 3rd party FTP client such as Apache FTPClient which allows you to specify a connection timeout.
A related issue is that some sites are requesting a username & password for access. Again FTPClient allows you to provide login details.
Last but not least, don't let heavyweight non-UI tasks freeze your Swing application. Swing has mechanisms to deal with these such as SwingWorker objects.
Related Swingworker Network Example

Delete a specific button

I have a JPanel in a JFrame that contains 5 buttons. In another JPanel there is a button called "delete button", what I want to do is to click this button and than choose what button of the other 5 to delete by ckicking in one of them. Can anyone help me?
public class gui extends JFrame implements ActionListener
{
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p2 = new JPanel();
JButton b1 = new JButton("Delete");
JButton b2 = new JButton("A");
JButton b3 = new JButton("B");
JButton b4 = new JButton("C");
gui()
{
p1.setLayout(new GridLayout(1,2));
p1.add(p2);
p1.add(p3);
p2.setLayout(new GridLayout(3,1));
p2.add(b2);
p2.add(b3);
p2.add(b4);
p3.add(b1);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == b1)
// When I click this button I want to be able to delete a button of my choice (one of the other 3)
}
}
Use a chain of responsibility in the button listeners. One Button listener that listens for the "to be deleted" buttons and the "delete" button. Under normal operation this button listener just sends the "to be deleted" button events to the existing button events, but when it hears a "delete" button event, it then captures the "next" button event without sending it to the existing button listener, and acts to remove the button.
Ok you provided some code. Here is a solution that uses a chain of responsibility. Basically, if one ActionListener can't handle the event, it sends it to the next one, and so on.
import java.awt.GridLayou;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Gui extends JFrame {
public static final long serialVersionUID = 1L;
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JButton b1 = new JButton("Delete");
JButton b2 = new JButton("A");
JButton b3 = new JButton("B");
JButton b4 = new JButton("C");
public Gui() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
p1.setLayout(new GridLayout(1, 2));
p1.add(p2);
p2.add(p3);
p2.setLayout(new GridLayout(3, 1));
p2.add(b2);
p2.add(b3);
p2.add(b4);
p3.add(b1);
DoItListener doIt = new DoItListener(null);
DeleteItListener deleteIt = new DeleteItListener(this, doIt);
b1.addActionListener(deleteIt);
b2.addActionListener(deleteIt);
b3.addActionListener(deleteIt);
b4.addActionListener(deleteIt);
add(p1);
pack();
}
public void deleteButton(String name) {
if (b2 != null && "A".equals(name)) {
p2.remove(b2);
b2 = null;
p2.invalidate();
p2.redraw();
}
if (b3 != null && "B".equals(name)) {
p2.remove(b3);
b3 = null;
p2.invalidate();
p2.redraw();
}
if (b4 != null && "A".equals(name)) {
p2.remove(b4);
b4 = null;
p2.invalidate();
p2.redraw();
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Gui().setVisible(true);
}
});
}
}
class DoItListener implements ActionListener {
private ActionListener delegate;
public DoItListener(ActionListener next) {
delegate = next;
}
public void actionPerformed(ActionEvent e) {
if (!("Delete".equals(e.getActionCommand()))) {
System.out.println("doing " + e.getActionCommand());
} else if (delegate != null) {
delegate.actionPerformed(e);
}
}
}
class DeleteItListener implements ActionListener {
private Gui gui;
private boolean deleteNext;
private ActionListener delegate;
public DeleteItListener(Gui container, ActionListener next) {
gui = container;
delegate = next;
deleteNext = false;
}
public void actionPerformed(ActionEvent e) {
if ("Delete".equals(e.getActionCommand())) {
deleteNext = true;
} else if (deleteNext) {
gui.deleteButton(e.getActionCommand());
deleteNext = false;
} else if (delegate != null) {
delegate.actionPerformed(e);
}
}
}
Here try this code out :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DeleteButtonExample extends JFrame
{
private boolean deleteNow = false;
private JButton deleteButton;
private JPanel leftPanel;
private JPanel rightPanel;
private JButton[] buttons = new JButton[5];
private ActionListener deleteAction = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (deleteNow)
{
leftPanel.remove(button);
leftPanel.revalidate();
leftPanel.repaint();
deleteNow = false;
}
else
{
// Do your normal Event Handling here.
System.out.println("My COMMAND IS : " + button.getActionCommand());
}
}
};
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setLayout(new GridLayout(0, 2));
leftPanel = new JPanel();
leftPanel.setLayout(new GridLayout(0, 2));
leftPanel.setBackground(Color.WHITE);
for (int i = 0; i < 5; i++)
{
buttons[i] = new JButton("" + i);
buttons[i].addActionListener(deleteAction);
buttons[i].setActionCommand("" + i);
leftPanel.add(buttons[i]);
}
rightPanel = new JPanel();
rightPanel.setBackground(Color.BLUE);
JButton deleteButton = new JButton("DELETE");
deleteButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(null, "Delete any Button from the Left Panel by clicking it."
, "INFO : ", JOptionPane.INFORMATION_MESSAGE);
deleteNow = true;
}
});
rightPanel.add(deleteButton);
add(leftPanel);
add(rightPanel);
pack();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new DeleteButtonExample().createAndDisplayGUI();
}
});
}
}
OUTPUT :
, ,
Here's a snippet of code to kick you off in the right direction:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FrameTestBase extends JFrame {
public static void main(String args[]) {
FrameTestBase t = new FrameTestBase();
final JPanel p = new JPanel();
final JButton button = new JButton();
button.setAction(new AbstractAction("Remove me!") {
#Override
public void actionPerformed(ActionEvent e) {
p.remove(button);
p.revalidate();
p.repaint();
}
});
p.add(button);
t.setContentPane(p);
t.setDefaultCloseOperation(EXIT_ON_CLOSE);
t.setSize(400, 400);
t.setVisible(true);
}
}
Before click:
After click:
From the comments:
To generalize this, you could create an AbstractAction that takes the to-be-deleted button as argument. Use this AbstractAction, and update it as necessary whenever your delete-policy should change.
Have a look at the glass pane. This tutorial shows how it is used.
At a high level, clicking the 'Delete' button would put the glass pane listener into a state where it:
detects a click,
determines the target component,
determines whether the component is allowed to be deleted
and if so, delete the component.
As a design note, I would keep a Set of controls that are allowed to be deleted, and thereby separate the concerns. So when you add a button that is allowed to be deleted, it is your responsibility to also add it to the delete candidates set.
The easiest method:
Add an ActionListener to the button that will remove another one;
Repaint and revalidate the panel where is the button to remove.
Example (in this case the button that will delete another one is called by "deleteBtn" and the button in the another panel that will be removed is called by "btnToDlt" that exists in the "panel"):
deleteBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.remove(btnToDlt);
panel.revalidate();
panel.repaint();
}
});

Categories