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
Related
I am having trouble replacing ImageIcon with a first ImageIcon whereupon a Jbutton is pressed. So far I have tried replacing the frame, .setIcon(myNewImage);, and .remove();. Not sure what to do now... (I'll need to replace and resize them.) Here is my code. (It is supposed to be like one of those Japanese dating games... please ignore that the pictures are local I have no site to host them yet.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.*;
public class NestedPanels extends JPanel {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
JButton b = new JButton("Say Hello");//1
JButton c = new JButton("Say You Look Good");//1
JButton d = new JButton("Say Sorry I'm Late");//1
JButton e2 = new JButton("So where are we headed?");//2
JButton f = new JButton("Can we go to your place?");//2
JButton g = new JButton("I don't have any money for our date...");//2
public NestedPanels() { //implemeted class
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button1Clicked(e);//when button clicked, invoke method
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button2Clicked(e);//when button clicked, invoke method
}
});
d.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button3Clicked(e);//when button clicked, invoke method
}
});
e2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button4Clicked(e);//when button clicked, invoke method
}
});
f.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button5Clicked(e);//when button clicked, invoke method
}
});
g.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button6Clicked(e);//when button clicked, invoke method
}
});
southBtnPanel.add(b);
southBtnPanel.add(c);
southBtnPanel.add(d);
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void button1Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Hey there! Ready to get started?", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button2Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Ugh... thanks! You too ready?!", "Christian is a bit... Embarrased.", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button3Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "It's ok! Just make sure it doesn't happen again!", "Christian is a bit angry!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button4Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageTwo = new ImageIcon("C:/Users/wchri/Documents/chrisferry.jpg");
mainPanel.add(label);
label.setIcon(imageTwo);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Let's take the ferry to NYC!", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button5Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageThree = new ImageIcon("C:/Users/wchri/Pictures/Screenshots/chrisart.jpg");
mainPanel.add(label);
label.setIcon(imageThree);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Don't you think it's a bit soon for that?", "Christian is embarrassed...", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button6Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageFour = new ImageIcon("C:/Users/wchri/Downloads/chrismoney.jpg");
mainPanel.add(label);
label.setIcon(imageFour);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "I got money!", "Christian is ballin'", JOptionPane.PLAIN_MESSAGE); //display button Action
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
Here is MCVE that demonstrates changing an icon on a JButton when it is clicked:
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ChangeButtonIcon extends JPanel{
private URL[] urls = {
new URL("https://findicons.com/files/icons/345/summer/128/cake.png"),
new URL("http://icons.iconarchive.com/icons/atyourservice/service-categories/128/Sweets-icon.png"),
new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_FkBgG3_ux0kCbfG8mcRHvdk1dYbZYsm2SFMS01YvA6B_zfH_kg"),
};
private int iconNumber = 0;
private JButton button;
public ChangeButtonIcon() throws IOException {
button = new JButton();
button.setIcon(new ImageIcon(urls[iconNumber]));
button.setHorizontalTextPosition(SwingConstants.CENTER);
button.addActionListener(e -> swapIcon());
add(button);
}
private void swapIcon() {
iconNumber = iconNumber >= (urls.length -1) ? 0 : iconNumber+1;
button.setIcon(new ImageIcon(urls[iconNumber]));
}
public static void main(String[] args) throws IOException{
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new ChangeButtonIcon());
window.pack();
window.setVisible(true);
}
}
I find writting MCVE a very useful technique. Not only it makes helping much easier, it
is a powerful debugging tool. It many case, while preparing one, you are likely to find the problem.
It should represent the problem or the question asked. Not your application.
I am creating a web browser in java and am receiving the following error when I attempt to run it:
Exception in thread "main" java.net.MalformedURLException: no protocol:
I have not been able to find an answer to my particular problem but I believe it has something to do with my socket. Do I simply need to add a MalformedURLException? Any help is appreciated.
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Browser extends JFrame {
public JPanel addressPanel, windowPanel;
public JLabel addressLabel;
public JTextField textField;
public JEditorPane windowPane;
public JScrollPane windowScroll;
public JButton addressButton;
private Search search = new Search();
public Browser() throws IOException {
addressLabel = new JLabel(" address: ", SwingConstants.CENTER);
textField = new JTextField("Enter a web address..");
textField.addActionListener(search);
addressButton = new JButton("Go");
addressButton.addActionListener(search);
windowPane = new JEditorPane("");
windowPane.setContentType("text/html");
windowPane.setEditable(false);
addressPanel = new JPanel(new BorderLayout());
windowPanel = new JPanel(new BorderLayout());
addressPanel.add(addressLabel, BorderLayout.WEST);
addressPanel.add(textField, BorderLayout.CENTER);
addressPanel.add(addressButton, BorderLayout.EAST);
windowScroll = new JScrollPane(windowPane);
windowPanel.add(windowScroll);
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
pane.add(addressPanel, BorderLayout.NORTH);
pane.add(windowPanel, BorderLayout.CENTER);
setTitle("Web Browser");
setSize(1000, 1000);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class Search implements ActionListener {
public void actionPerformed(ActionEvent ea) {
String line;
try {
Socket socket = new Socket(textField.getText(), 80);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.print("GET / HTTP/1.1\r\n");
out.print(textField.getText() + "\r\n\r\n");
out.flush();
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
Browser browser = new Browser();
}
}
The problem was because the line bellow:
windowPane = new JEditorPane("");
Just change to
windowPane = new JEditorPane();
According to JEditorPane constructor javadoc:
Creates a JEditorPane based on a string containing a URL specification.
#param url the URL
#exception IOException if the URL is null or cannot be accessed
I have a chat client program I am working on and currently I can get the text pane, text input on the left. I can add buttons and change the background color to the right but I can not get an image to display on the right. There is more than one way to skin a cat on this from what I've read but I'm trying to stick with the setup I currently have so I don't have to rewrite everything. I understand the basics of Java (OOP) and how it works. I'm just lost as to how to format image icon and get this image to display. Here is the code: I am compiling with IntelliJ.
package edu.lmu.cs.networking;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ChatClient {
private BufferedReader in;
private PrintWriter out;
private JFrame frame = new JFrame("Chatter");
private JTextField textField = new JTextField(20);
private JTextArea messageArea = new JTextArea(8, 40);
private JPanel panel;
private JButton button;
private JLabel label;
public ChatClient() {
textField.setEditable(false);
messageArea.setEditable(false);
// frame.setSize(500, 500);
// frame.setVisible(true);
frame.getContentPane().add(textField, "South");
frame.getContentPane().add(new JScrollPane(messageArea), "West");
panel = new JPanel();
panel.setBackground(Color.YELLOW);
button = new JButton("Button");
label = new JLabel(new ImageIcon("x.gif"));
panel.add(button);
panel.add(label, BorderLayout.EAST);
frame.add(panel);
frame.pack();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
}
});
}
private String getServerAddress() {
return JOptionPane.showInputDialog(frame, "Enter IP Address of the Server:",
"Welcome to the Chatter", JOptionPane.QUESTION_MESSAGE);
}
private String getName() {
return JOptionPane.showInputDialog(frame, "Choose a screen name:", "Screen name selection",
JOptionPane.PLAIN_MESSAGE);
}
private void run() throws IOException {
// Make connection and initialize streams
String serverAddress = getServerAddress();
Socket socket = new Socket(serverAddress, 5910);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
while (true) {
String line = in.readLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}
}
public static void main(String[] args) throws Exception {
ChatClient client = new ChatClient();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.run();
}
}
Thanks in advance,
-Brandon
You can just change your code as below and it will work. Just tested it on my own computer and it worked.
ImageIcon icon = new ImageIcon(getClass().getResource("x.gif"));
label = new JLabel(icon);
It seems your problem is that you didn't actually loaded the image in. Remember to use a ClassLoader to load the resource files.
You should place 'x.gif' under your project directory or your resource folder(preferred) in order to make this work.
For more details about loading resources, take a look at this link.
If the image is in your projects root directory,then you can access it the directly,similar to what you have done.
If it is inside some folder(say resources folder) in your project structure you need to use getClass().getResource("/resources/x.gif").
You can also create a scaled version of the image,specifying the height and width.It can be done using the sample code below:
ImageIcon icon = new ImageIcon("x.gif");
Image img = icon.getImage();
Image newimg = img.getScaledInstance(30, 20,
java.awt.Image.SCALE_SMOOTH);
icon = new ImageIcon(newimg);
label = new JLabel(icon);
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
I've searched through the forums but keep coming up empty for a solution.
I'm making a sort of library with a GUI program. What I want is for it to save entries via a text file. I can create objects fine with the methods I have, and can save them to a file easily. The problem comes from starting up the program again and populating a Vector with values in the text file. The objects I'm adding have a String value, followed by 7 booleans. When I try to load up from file, the String value is empty ("") and all booleans are false.
How do I get it to read the text before starting the rest of the GUI and filling the Vector right?
EDIT: Sorry for being very vague about it all. I'll post the code, but it's about 337 lines long..
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class SteamLibraryGUI extends JFrame implements ActionListener
{
//For main window
private JButton exitButton, addEntry, editEntry, removeEntry;
private JLabel selectGame, gameCount;
private JComboBox<String> gameCombo;
private Vector<Game> gamesList = new Vector<Game>();
private Vector<String> titleList = new Vector<String>();
private int numGames = gamesList.size();
private int selectedGame;
//For add window
private JFrame addFrame;
private JLabel gameTitle = new JLabel("Title:");
private JTextField titleText = new JTextField(60);
private JCheckBox singleBox, coopBox, multiBox, cloudBox, controllerBox, achieveBox, pcBox;
private JButton addGame, addCancel;
//For edit window
private JFrame editFrame;
private JButton editGame, editCancel;
public SteamLibraryGUI()
{
setTitle("Steam Library Organizer");
addEntry = new JButton("Add a game");
editEntry = new JButton("Edit a game");
removeEntry = new JButton("Remove a game");
exitButton = new JButton("Exit");
selectGame = new JLabel("Select a game:");
gameCount = new JLabel("Number of games:"+numGames);
gameCombo = new JComboBox<String>(titleList);
JPanel selectPanel = new JPanel();
selectPanel.setLayout(new GridLayout(1,2));
selectPanel.add(selectGame);
selectPanel.add(gameCombo);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,3));
buttonPanel.add(addEntry);
buttonPanel.add(editEntry);
buttonPanel.add(removeEntry);
JPanel exitPanel = new JPanel();
exitPanel.setLayout(new GridLayout(1,2));
exitPanel.add(gameCount);
exitPanel.add(exitButton);
Container pane = getContentPane();
pane.setLayout(new GridLayout(3,1));
pane.add(selectPanel);
pane.add(buttonPanel);
pane.add(exitPanel);
addEntry.addActionListener(this);
editEntry.addActionListener(this);
removeEntry.addActionListener(this);
exitButton.addActionListener(this);
gameCombo.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==addEntry)
addEntry();
if(e.getSource()==editEntry)
editEntry(gamesList.get(selectedGame));
if(e.getSource()==removeEntry)
{
removeEntry(selectedGame);
update();
}
if(e.getSource()==exitButton)
exitProg();
if(e.getSource()==gameCombo)
{
selectedGame = gameCombo.getSelectedIndex();
}
if(e.getSource()==singleBox)
singleBox.isSelected();
if(e.getSource()==coopBox)
coopBox.isSelected();
if(e.getSource()==multiBox)
multiBox.isSelected();
if(e.getSource()==cloudBox)
cloudBox.isSelected();
if(e.getSource()==controllerBox)
controllerBox.isSelected();
if(e.getSource()==achieveBox)
achieveBox.isSelected();
if(e.getSource()==pcBox)
pcBox.isSelected();
if(e.getSource()==addGame)
{
gamesList.add(new Game(titleText.getText(), singleBox.isSelected(), coopBox.isSelected(),
multiBox.isSelected(), cloudBox.isSelected(), controllerBox.isSelected(),
achieveBox.isSelected(), pcBox.isSelected()));
titleList.add(titleText.getText());
addFrame.dispose();
update();
}
if(e.getSource()==addCancel)
addFrame.dispose();
if(e.getSource()==editCancel)
editFrame.dispose();
if(e.getSource()==editGame)
{
gamesList.get(selectedGame).name = titleText.getText();
gamesList.get(selectedGame).single = singleBox.isSelected();
gamesList.get(selectedGame).coop = coopBox.isSelected();
gamesList.get(selectedGame).multi = multiBox.isSelected();
gamesList.get(selectedGame).cloud = cloudBox.isSelected();
gamesList.get(selectedGame).controller = controllerBox.isSelected();
gamesList.get(selectedGame).achieve = achieveBox.isSelected();
gamesList.get(selectedGame).pc = pcBox.isSelected();
titleList.remove(selectedGame);
titleList.add(titleText.getText());
editFrame.dispose();
update();
}
}
public void update()
{
Collections.sort(titleList);
Collections.sort(gamesList);
gameCombo.updateUI();
titleText.setText("");
gameCombo.setSelectedIndex(-1);
numGames = gamesList.size();
gameCount.setText("Number of games:"+numGames);
}
public void addEntry()
{
addFrame = new JFrame("Add Entry");
addFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
addFrame.getContentPane();
addFrame.setLayout(new GridLayout(3,1));
singleBox = new JCheckBox("Single-Player");
singleBox.setSelected(false);
coopBox = new JCheckBox("Coop");
coopBox.setSelected(false);
multiBox = new JCheckBox("MultiPlayer");
multiBox.setSelected(false);
cloudBox = new JCheckBox("Steam Cloud");
cloudBox.setSelected(false);
controllerBox = new JCheckBox("Controller Support");
controllerBox.setSelected(false);
achieveBox = new JCheckBox("Achievements");
achieveBox.setSelected(false);
pcBox = new JCheckBox("For New PC");
pcBox.setSelected(false);
addGame = new JButton("Add game");
addCancel = new JButton("Cancel");
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(gameTitle);
titlePanel.add(titleText);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new FlowLayout());
checkPanel.add(singleBox);
checkPanel.add(coopBox);
checkPanel.add(multiBox);
checkPanel.add(cloudBox);
checkPanel.add(controllerBox);
checkPanel.add(achieveBox);
checkPanel.add(pcBox);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(addGame);
buttonPanel.add(addCancel);
addFrame.add(titlePanel);
addFrame.add(checkPanel);
addFrame.add(buttonPanel);
singleBox.addActionListener(this);
coopBox.addActionListener(this);
multiBox.addActionListener(this);
cloudBox.addActionListener(this);
controllerBox.addActionListener(this);
achieveBox.addActionListener(this);
pcBox.addActionListener(this);
addGame.addActionListener(this);
addCancel.addActionListener(this);
addFrame.pack();
addFrame.setVisible(true);
}
public void editEntry(Game g)
{
editFrame = new JFrame("Edit Entry");
editFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
editFrame.getContentPane();
editFrame.setLayout(new GridLayout(3,1));
singleBox = new JCheckBox("Single-Player");
singleBox.setSelected(g.single);
coopBox = new JCheckBox("Coop");
coopBox.setSelected(g.coop);
multiBox = new JCheckBox("MultiPlayer");
multiBox.setSelected(g.multi);
cloudBox = new JCheckBox("Steam Cloud");
cloudBox.setSelected(g.cloud);
controllerBox = new JCheckBox("Controller Support");
controllerBox.setSelected(g.controller);
achieveBox = new JCheckBox("Achievements");
achieveBox.setSelected(g.achieve);
pcBox = new JCheckBox("For New PC");
pcBox.setSelected(g.pc);
editGame = new JButton("Edit game");
editCancel = new JButton("Cancel");
titleText.setText(g.name);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(gameTitle);
titlePanel.add(titleText);
JPanel checkPanel = new JPanel();
checkPanel.setLayout(new FlowLayout());
checkPanel.add(singleBox);
checkPanel.add(coopBox);
checkPanel.add(multiBox);
checkPanel.add(cloudBox);
checkPanel.add(controllerBox);
checkPanel.add(achieveBox);
checkPanel.add(pcBox);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(editGame);
buttonPanel.add(editCancel);
editFrame.add(titlePanel);
editFrame.add(checkPanel);
editFrame.add(buttonPanel);
singleBox.addActionListener(this);
coopBox.addActionListener(this);
multiBox.addActionListener(this);
cloudBox.addActionListener(this);
controllerBox.addActionListener(this);
achieveBox.addActionListener(this);
pcBox.addActionListener(this);
editGame.addActionListener(this);
editCancel.addActionListener(this);
editFrame.pack();
editFrame.setVisible(true);
}
public void removeEntry(int g)
{
Object[] options = {"Yes, remove the game", "No, keep the game"};
int n = JOptionPane.showOptionDialog(null, "Are you sure you want to remove this game from the list?",
"Remove game?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
if (n==0)
{
gamesList.remove(g);
titleList.remove(g);
}
}
public void exitProg()
{
try
{
PrintWriter out = new PrintWriter("games.txt");
out.flush();
for(int i=0;i<gamesList.size();i++)
{
out.print(gamesList.get(i).toString());
}
out.close();
}
catch (FileNotFoundException e) {}
System.exit(0);
}
public static void main(String[] args)
{
SteamLibraryGUI frame = new SteamLibraryGUI();
frame.pack();
frame.setSize(600,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Scanner in = new Scanner("games.txt");
while(in.hasNextLine())
{
String line = in.nextLine();
String[] options = line.split("|");
Game g = new Game(options[0],Boolean.getBoolean(options[1]),
Boolean.getBoolean(options[2]),Boolean.getBoolean(options[3]),
Boolean.getBoolean(options[4]),Boolean.getBoolean(options[5]),
Boolean.getBoolean(options[6]),Boolean.getBoolean(options[7]));
frame.gamesList.add(g);
frame.titleList.add(options[0]);
System.out.println(g.toString());
}
in.close();
}
}
There's also a Game class, but it's simply 1 String, and then 7 booleans.
There were two significant bugs in the code. First, Scanner was constructed with a string parameter (which means that the Scanner scanned the string, not the file named by the string). Second, the pipe character "|" is a regular expression metacharacter. That is important because line.split() splits on regular expressions. Thus, the "|" has to be escaped. The main() function works fine if it is written as follows (with debugging output code included to show that each step is working correctly):
public static void main(String[] args)
{
SteamLibraryGUI frame = new SteamLibraryGUI();
frame.pack();
frame.setSize(600,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try
{
Scanner in = new Scanner(new File("games.txt"));
while(in.hasNextLine())
{
System.out.println("line = ");
String line = in.nextLine();
System.out.println(line);
String[] options = line.split("\\|");
System.out.println("Options = ");
for (String s : options)
{
System.out.println(s);
}
Game g = new Game(options[0],Boolean.getBoolean(options[1]),
Boolean.getBoolean(options[2]),Boolean.getBoolean(options[3]),
Boolean.getBoolean(options[4]),Boolean.getBoolean(options[5]),
Boolean.getBoolean(options[6]),Boolean.getBoolean(options[7]));
frame.gamesList.add(g);
frame.titleList.add(options[0]);
System.out.println(g.toString());
}
in.close();
} catch (IOException x)
{
System.err.println(x);
}
}
There is one other important Gotcha: The method exitProg() writes the "games.txt" file out again before the program finishes. This creates a problem if the file was read incorrectly in the first place because the wrong data will be written back to the file. During testing, this means that even when the reading code has been corrected, it will still read the erroneous data that was written from a previous test run.
My preference in this situation is would be to isolate all the reading and writing code for "game.txt" inside the Game class (which makes it easier to verify that the reading and writing formats are identical) and only write the code to write the data back out once I'd written and tested the reading code, which would avoid this Gotcha.