I want to know how my console output can be save in a notepad file?
import java.awt.EventQueue;
public class HLS1 {
private JFrame frmHttpsLiveStreaming;
private JTextField textField;
// file is accessed to the whole class
private File file;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HLS1 window = new HLS1();
window.frmHttpsLiveStreaming.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public HLS1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHttpsLiveStreaming = new JFrame();
frmHttpsLiveStreaming.setTitle("HTTPS Live Streaming");
frmHttpsLiveStreaming.setBounds(100, 100, 494, 112);
frmHttpsLiveStreaming.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHttpsLiveStreaming.getContentPane().setLayout(null);
JButton btnBrowse = new JButton("Open File");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Argument:" + arg0);
JFileChooser fs = new JFileChooser(new File("c:\\"));
fs.setDialogTitle("Open a file");
fs.setFileFilter(new FileTypeFilter(".m3u8", ""));
fs.setFileFilter(new FileTypeFilter(".m3u", ""));
fs.showOpenDialog(null);
file = fs.getSelectedFile();
textField.setText(file.getAbsolutePath());
}
});
btnBrowse.setBounds(336, 7, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnBrowse);
JButton btnNewButton_1 = new JButton("Clear");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("");
}
});
btnNewButton_1.setBounds(237, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton_1);
JLabel lblUrl = new JLabel("URL");
lblUrl.setBounds(83, 11, 24, 14);
frmHttpsLiveStreaming.getContentPane().add(lblUrl);
textField = new JTextField();
textField.setBounds(116, 11, 210, 19);
frmHttpsLiveStreaming.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Check");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
List<String> fileArray = new ArrayList<String>();
List<String> errors = new ArrayList<String>();
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
Scanner s = null;
if(textField.getText().matches(regex)){
URL url = new URL(textField.getText());
s= new Scanner(url.openStream());
}else{
s = new Scanner(new BufferedReader(new FileReader(file)));
}
if(s != null){
while(s.hasNextLine()){
String line = s.nextLine();
if(!line.isEmpty()){
fileArray.add(line);
}
System.out.println(line);
}
}
s.close();
errors.addAll(validateEXTM3U(fileArray));
for (String error : errors) {
System.out.println(error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnNewButton.setBounds(126, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton);
}
private List<String> validateEXTM3U(List<String> fileArray){
List<String> errors = new ArrayList<String>();
String tag = fileArray.get(0);
if(!tag.equals("#EXTM3U")){
errors.add("First line in the menifest file is not #EXTM3U");
}
return errors;
}
}
It could be a hacky solution , but if you are running in windows or linux then you can pipe / redirect it.
java HLS1 > notepad.txt
if not what you are looking for , then why not using something called log4j ?
Why don't you write your own utility that has an public static void output(String output) method. Then instead of using System.out.println("...") you call output("...") then in your output(String output) method you can do anything with the output, like first write to the file, then print to the console.
Hope this helps.
Related
I'm a complete beginner to programming and this is my first question. I want to create a program in java to search images' paths on windows OS. All the paths should appear as a list in the interface I programmed.
my interface
How can I output all the paths? I tried to use this:
list.setText(file.getAbsolutePath());
but .setText deletes all previous strings and leaves only the last.
Please help and thank you
My code:
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame("Search Window");
window.setBounds(5,5, 500, 500);
window.setLayout(null);
JButton button = new JButton("Search Images");
button.setBounds(160, 20, 150, 50);
button.setBackground(Color.gray);
button.setForeground(Color.white);
window.add(button);
JLabel label = new JLabel("Output Here");
label.setBounds(20, 80, 150, 50);
window.add(label);
JList list = new JList();
list.setBounds(20, 130, 440, 30);
window.add(list);
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ArrayList<File> fileList = new ArrayList<>();
searchFiles(new File("D:\\"), fileList);
for (File file: fileList) {
System.out.println(file.getAbsolutePath());
}
}
private static void searchFiles(File rootFile, List<File> fileList) {
if (rootFile.isDirectory()) {
File[] directoryFiles = rootFile.listFiles();
if (directoryFiles != null) {
for(File file: directoryFiles) {
if (file.isDirectory()) {
searchFiles(file, fileList);
} else {
if (file.getName().toLowerCase().endsWith(".jpg")) {
fileList.add(file);
}
}
}
}
}
}
};
button.addActionListener(actionListener);
window.setVisible(true);
}
}
As said in comment, you can modify the section into something like this:
String temp = list.getText() + file.getAbsolutePath();
list.setText(temp);
which you can then also append , or other syntax if needed.
Below are the codes:
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame("Search Window");
window.setBounds(5,5, 500, 500);
window.setLayout(null);
JButton button = new JButton("Search Images");
button.setBounds(160, 20, 150, 50);
button.setBackground(Color.gray);
button.setForeground(Color.white);
window.add(button);
JLabel label = new JLabel("Output Here");
label.setBounds(20, 80, 150, 50);
window.add(label);
JList list = new JList();
list.setBounds(20, 130, 440, 30);
window.add(list);
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ArrayList<File> fileList = new ArrayList<>();
searchFiles(new File("D:\\"), fileList);
for (File file: fileList) {
// Assume you need it here.
String temp = list.getText() + file.getAbsolutePath();
list.setText(temp);
}
}
private static void searchFiles(File rootFile, List<File> fileList) {
if (rootFile.isDirectory()) {
File[] directoryFiles = rootFile.listFiles();
if (directoryFiles != null) {
for(File file: directoryFiles) {
if (file.isDirectory()) {
searchFiles(file, fileList);
} else {
if (file.getName().toLowerCase().endsWith(".jpg")) {
fileList.add(file);
}
}
}
}
}
}
};
button.addActionListener(actionListener);
}
Hope this answer helps you well.
I'm starting with Socket Server in Java. I've written already simple app where I can send text between hosts. I'm sending with my message name of the host which is sending and here is my problem, how can I get host message?
Can someone just change my code to show host name instead of message?
Here is the code:
public class FMain extends JFrame {
private JPanel contentPane = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FMain frame = new FMain();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 508, 321);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
PReceiver receiver = new PReceiver();
receiver.setBorder(new LineBorder(new Color(0, 0, 0)));
receiver.setBounds(35, 13, 423, 106);
contentPane.add(receiver);
PSender sender = new PSender((String) null, 0);
sender.setBorder(new LineBorder(new Color(0, 0, 0)));
sender.setBounds(35, 132, 423, 129);
contentPane.add(sender);
}
}
And the class which is receiving:
interface MyListener {
void messageReceived(String theLine);
}
class Receiver {
private List < MyListener > ml = new ArrayList < MyListener > ();
private Thread t = null;
private int port = 0;
private ServerSocket s = null;
private boolean end = false;
public void stop() {
t.interrupt();
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void start() {
end = false;
t = new Thread(new Runnable() {
#Override
public void run() {
try {
s = new ServerSocket(port);
while (true) {
Socket sc = s.accept();
InputStream is = sc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String theLine = br.readLine();
ml.forEach((item) - > item.messageReceived(theLine));
sc.close();
}
} catch (SocketException e) {} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
public void addMyListener(MyListener m) {
ml.add(m);
}
public void removeMyListener(MyListener m) {
ml.remove(m);
}
Receiver(int port) {
this.port = port;
}
}
public class PReceiver extends JPanel implements MyListener {
private JTextField txtPort;
private Receiver r = null;
private JTextField txtMessage;
/**
* Create the panel.
*/
public PReceiver() {
setLayout(null);
txtPort = new JTextField();
txtPort.setBounds(282, 13, 62, 22);
add(txtPort);
// txtPort.setColumns(10);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(241, 16, 35, 16);
add(lblPort);
JToggleButton btnListen = new JToggleButton("Listen");
btnListen.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (btnListen.isSelected()) {
r = new Receiver(Integer.parseInt(txtPort.getText()));
r.addMyListener(PReceiver.this);
r.start();
} else {
r.stop();
}
}
});
btnListen.setBounds(265, 70, 79, 25);
add(btnListen);
JLabel lblMessage = new JLabel("message");
lblMessage.setBounds(12, 51, 56, 16);
add(lblMessage);
txtMessage = new JTextField();
txtMessage.setBounds(12, 71, 220, 22);
add(txtMessage);
//txtMessage.setColumns(10);
}
#Override
public void messageReceived(String theLine) {
txtMessage.setText(theLine);
}
}
And the sender class:
class Sender {
public void send(String message, String host, int port) {
Socket s;
try {
s = new Socket(host, port);
OutputStream out = s.getOutputStream();
PrintWriter pw = new PrintWriter(out, false);
pw.println(message);
pw.flush();
pw.close();
s.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class PSender extends JPanel {
private JTextField txtMessage;
private JTextField txtHost;
private JTextField txtPort;
private JLabel lblMessage;
/**
* Create the panel.
*/
public PSender(String host, int port) {
setLayout(null);
txtMessage = new JTextField();
txtMessage.setBounds(12, 77, 216, 22);
add(txtMessage);
//txtMessage.setColumns(10);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
new Sender().send(txtMessage.getText(), txtHost.getText(), Integer.parseInt(txtPort.getText()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
});
btnSend.setBounds(268, 76, 78, 25);
add(btnSend);
txtHost = new JTextField();
txtHost.setBounds(51, 13, 149, 22);
add(txtHost);
//txtHost.setColumns(10);
txtPort = new JTextField();
txtPort.setBounds(268, 13, 78, 22);
add(txtPort);
//txtPort.setColumns(10);
JLabel lblHost = new JLabel("host:");
lblHost.setBounds(12, 16, 35, 16);
add(lblHost);
JLabel lblPort = new JLabel("port:");
lblPort.setBounds(231, 16, 35, 16);
add(lblPort);
lblMessage = new JLabel("message");
lblMessage.setBounds(12, 58, 56, 16);
add(lblMessage);
}
}
So i just started with eclipse and java script and i am also a new coder. I started of wtih this random name picker project. And the code is written like this:
public static void gods() {
System.out.println("You have to play this God:");
String[] gods =
{"Agni",
"Ah Muzen Cab",
"Ah Puch",
"Amaterasu",
"Anhur",
"Anubis",
"Ao Kuang",
"Aphrodite",
"Apollo",
"Arachne",
"Ares",
"Artemis",
"Athena",
"Awilix",
"Bacchus",
"Bakasura",
"Bastet",
"Bellona",
"Cabrakan",
"Chaac",
"Change",
"Chiron",
"Chronos",
"Cupid",
"Fenrir",
"Geb",
"Guan Yu",
"Hades",
"He Bo",
"Hel",
"Hercules",
"Hou Yi",
"Hun Batz",
"Isis",
"Janus",
"Kali",
"Khepri",
"Kukulkan",
"Kumbhakarna",
"Loki",
"Medusa",
"Mercury",
"Ne Zha",
"Neith",
"Nemesis",
"Nox",
"Nu Wa",
"Odin",
"Osiris",
"Poseidon",
"Ra",
"Rama",
"Ratatoskr",
"Ravana",
"Scylla",
"Serqet",
"Sobek",
"Sol",
"Sun Wukong",
"Sylvanus",
"Thanatos",
"Thor",
"Tyr",
"Ullr",
"Vamana",
"Vulcan",
"Xbalanque",
"Xing Tian",
"Ymir",
"Zeus",
"Zhong Kui"};
List<String> names = Arrays.asList(gods);
int index = new Random().nextInt(names.size());
String name = names.get(index);
System.out.print(name + " ");
}
public static void roles() {
String[] roles = {" Solo", " Jungle", " Mid", " ADC", " Support"};
List<String> names = Arrays.asList(roles);
int index = new Random().nextInt(names.size());
String name = names.get(index);
System.out.print(name + " ");}
public void Randomize() {
System.out.println("Here you have your god:");
gods();
System.out.println("Here you have your role:");
roles();}
But i want to import or set in this code inside my windowbuilder plugin. I have tried inserting it inside a JButton as an "actionPerformed" but when i launched the program and clicked the button it opened up the console in eclipse when i want it to open inside the program.
This is my windowbuilder code:
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Plswork window = new Plswork();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Plswork() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Comic Sans MS", Font.PLAIN, 18));
frame.getContentPane().setBackground(Color.MAGENTA);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
txtAronErDu = new JTextField();
txtAronErDu.setFont(new Font("SWTOR Trajan", Font.PLAIN, 22));
txtAronErDu.setText("Aron er du homofil?");
txtAronErDu.setBounds(0, 0, 434, 39);
frame.getContentPane().add(txtAronErDu);
txtAronErDu.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(199, 118, 89, 23);
frame.getContentPane().add(btnNewButton);
}
public void actionPerformed(ActionEvent e) {
}
}
PS: This is how it looks when i imoprt it:
public class Plswork {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Plswork window = new Plswork();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Comic Sans MS", Font.PLAIN, 18));
frame.getContentPane().setBackground(Color.MAGENTA);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Sebbe");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("You have to play this God:");
String[] gods =
{"Agni",
"Ah Muzen Cab",
"Ah Puch",
"Amaterasu",
"Anhur",
"Anubis",
"Ao Kuang",
"Aphrodite",
"Apollo",
"Arachne",
"Ares",
"Artemis",
"Athena",
"Awilix",
"Bacchus",
"Bakasura",
"Bastet",
"Bellona",
"Cabrakan",
"Chaac",
"Change",
"Chiron",
"Chronos",
"Cupid",
"Fenrir",
"Geb",
"Guan Yu",
"Hades",
"He Bo",
"Hel",
"Hercules",
"Hou Yi",
"Hun Batz",
"Isis",
"Janus",
"Kali",
"Khepri",
"Kukulkan",
"Kumbhakarna",
"Loki",
"Medusa",
"Mercury",
"Ne Zha",
"Neith",
"Nemesis",
"Nox",
"Nu Wa",
"Odin",
"Osiris",
"Poseidon",
"Ra",
"Rama",
"Ratatoskr",
"Ravana",
"Scylla",
"Serqet",
"Sobek",
"Sol",
"Sun Wukong",
"Sylvanus",
"Thanatos",
"Thor",
"Tyr",
"Ullr",
"Vamana",
"Vulcan",
"Xbalanque",
"Xing Tian",
"Ymir",
"Zeus",
"Zhong Kui"};
List<String> names = Arrays.asList(gods);
int index = new Random().nextInt(names.size());
String name = names.get(index);
System.out.print(name + " ");
}
});
btnNewButton.setBounds(167, 117, 89, 23);
frame.getContentPane().add(btnNewButton);
}
public void actionPerformed(ActionEvent e) {
}
}
I cant seems to load data into table despite being able to load column name dynamically. When I try to load data nothing appear despite the fact that Java Icon still showed on the taskbar. It doesn't look like there is anything wrong with GUI itself so I was wondering if opening a connection from constructor will cause logical error.I printed out the locals variables in the second for loop of populateTable method to check if data was passed into local variables and they did, so I don't know exactly what was causing this error.
here is the code for GUI:
public class WeatherFrame extends JFrame {
private JPanel contentPane;
private JTable table;
HealthData health = new HealthData();
private DefaultTableModel model;
String[] columnNames = {"zipcode", "county", "city", "state", "year", "month","ageGroup",
"numOfVisits", "MonthlyMax", "MonthlyMin", "MonthlyNor"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WeatherFrame frame = new WeatherFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WeatherFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 300);
contentPane = new JPanel();
contentPane.setBounds(100, 100,750, 200);
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(6, 25, 788, 180);
contentPane.add(scrollPane);
model = new DefaultTableModel();
populateTable();
table = new JTable(model);
scrollPane.setViewportView(table);
JButton btnInsert = new JButton("insert");
btnInsert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnInsert.setBounds(315, 217, 117, 29);
contentPane.add(btnInsert);
JButton btnDelete = new JButton("delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDelete.setBounds(198, 243, 117, 29);
contentPane.add(btnDelete);
JButton btnSearch = new JButton("search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnSearch.setBounds(81, 243, 117, 29);
contentPane.add(btnSearch);
JLabel lblWeatherTable = new JLabel("Weather Table");
lblWeatherTable.setBounds(149, 6, 107, 16);
contentPane.add(lblWeatherTable);
JButton btnNext = new JButton("update");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNext.setBounds(198, 217, 117, 29);
contentPane.add(btnNext);
JButton btnRefresh = new JButton("refresh");
btnRefresh.setBounds(81, 217, 117, 29);
contentPane.add(btnRefresh);
}
public void populateTable() {
for(String name: columnNames)
model.addColumn(name);
ArrayList<Health> healthdata = new ArrayList<Health>();
healthdata = health.showAllData();
model.addRow(healthdata.toArray());
}
}
this is the constructor for the HealthData class
public HealthData(){
try {
/* Connect to database */
connection = DriverManager.getConnection(jdbcURL, MySQLConfig.user, MySQLConfig.password);
statement = connection.createStatement();
data = new ArrayList<Health>();
} catch (Exception e)
{
e.printStackTrace();
}
}
this is the code for showAlldata method
public ArrayList<Health> showAllData(){
ArrayList<Health> list = new ArrayList<Health>();
try {
connection = DriverManager.getConnection(jdbcURL, MySQLConfig.user, MySQLConfig.password);
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(SELECT_ALL_QUERY);
/* Get and print out data from health table : zipcode, county, city, state, year, month, ageGroup, numberOfVisits, MMax, MMin, MNor */
while(result.next()){
Health data = new Health();
int zipcode = result.getInt(1);
data.setZipCode(zipcode);
String county = result.getString(2);
data.setCounty(county);
String city = result.getString(3);
data.setCity(city);
String state = result.getString(4);
data.setState(state);
int year = result.getInt(5);
data.setYear(year);
int month = result.getInt(6);
data.setMonth(month);
String ageGroup = result.getString(7);
data.setAgeGroup(ageGroup);
int numOfVisits = result.getInt(8);
data.setNumOfVisits(numOfVisits);
float MMax = result.getFloat(9);
data.setMMax(MMax);
float MMin = result.getFloat(10);
data.setMMin(MMin);
float MNor = result.getFloat(11);
data.setMNor(MNor);
list.add(data);
connection.close()
stmt.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
Can someone suggest a solution for solving this problem. Thank you in advance for helping. I already posted a question about this but this question is up to date with required codes.
I edit the code to make only one call to showAlldata and also close connection and statement, however, the same error still persist
public void populateTable() {
model = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
for(String name: columnNames)
model.addColumn(name);
ArrayList<Health> temp = new ArrayList<Health>();
temp = health.showAllData();
for(int i = 0; i< temp.size(); i++) {
Object[] data = {temp.get(i).getZipCode(), temp.get(i).getCounty(), temp.get(i).getCounty(), temp.get(i).getState(),temp.get(i).getYear(),
temp.get(i).getMonth(), temp.get(i).getAgeGroup(), temp.get(i).getNumOfVisits(), temp.get(i).getMMax(), temp.get(i).getMMin(), temp.get(i).getMNor()};
model.addRow(data);
}
}
thank you very much for helping, I solved this question by modifying my populateTable Method as above.
I seem to be having some issues when using the JOptionPane.showMessageDialog() method.
When I use the method the only thing that is set up correctly is the dialogs title. It doesn't want to display the text that I provide.
Here's the code that I'm using to try and create an alert:
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
The code above provides the image below:
If someone could tell me what I'm doing wrong or if there is a different method that I'm supposed to be using, I would much appreciate it.
Edit:
My main class:
This creates a GUI where the user enters information "Host" and "DisplayName". When they click "Connect" a new thread is created (the ClientConnectSocket).
public class Main extends JFrame {
public static JPanel contentPane;
private JTextField hostTxt;
public static JTextField displayNameTxt;
JLabel lblDisplayName = new JLabel("Display Name:");
JButton btnConnect = new JButton("Connect");
JLabel lblHost = new JLabel("Host:");
public static String username = "None :(";
public static String host = "localhost";
public static boolean connected = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setType(Type.UTILITY);
setTitle("Java Chat Client - v0.1");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 390, 200);
contentPane = new JPanel();
this.setResizable(false);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblHost.setBounds(60, 11, 56, 19);
contentPane.add(lblHost);
hostTxt = new JTextField();
hostTxt.setBounds(165, 10, 103, 20);
contentPane.add(hostTxt);
hostTxt.setColumns(10);
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (hostTxt.getText() == null || displayNameTxt.getText() == null){
}else{
Thread ccs = new ClientConnectSocket(hostTxt.getText(), displayNameTxt.getText());
ccs.start();
while (!connected){
//System.out.println("Not connected yet..");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Yey, connected");
username = displayNameTxt.getText();
host = hostTxt.getText();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Chat frame = new Chat();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
dispose();
}
}
});
btnConnect.setBounds((this.getWidth()/2)- 70, 76, 89, 23);
contentPane.add(btnConnect);
displayNameTxt = new JTextField();
displayNameTxt.setColumns(10);
displayNameTxt.setBounds(165, 45, 103, 20);
contentPane.add(displayNameTxt);
lblDisplayName.setBounds(60, 41, 95, 29);
contentPane.add(lblDisplayName);
this.getRootPane().setDefaultButton(btnConnect);
}
ClientConnectSocket class:
public class ClientConnectSocket extends Thread{
String host;
String name;
public ClientConnectSocket(String host, String displayName){
this.host = host;
this.name = displayName;
}
boolean b = true;
public void run(){
try{
while (b){
Socket server = new Socket(host, 6969);
System.out.println("Sending info to try and connect.");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
out.write("method=connect:displayName="+ name);
out.flush();
Thread.sleep(500);
InputStream in = server.getInputStream();
StringBuffer sb = new StringBuffer();
byte[] buffer = new byte[1024];
int buf;
while ((buf = in.read(buffer)) != -1){
String line = new String(buffer, 0, buf);
sb.append(line);
}
in.close();
System.out.println(sb.toString() + " || " + sb.toString().equalsIgnoreCase("connect"));
if (sb.toString().equalsIgnoreCase("connect")){
//Allow them to connect
Main.connected = true;
}else if(sb.toString().equalsIgnoreCase("invalid:Username")){
//Tell them they have username already taken;
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
b = false;
}
server.close();
out.close();
in.close();
b = false;
}
}catch (Exception e){
System.exit(2);
e.printStackTrace();
}
}
Your posted code snippet suggests that you're running into a Swing threading issue. If your program is a Swing GUI, then most of the above code needs to be called off of the Swing EDT or Event Dispatch Thread, while any Swing calls, including displaying the JOptionPane should be called on the EDT. For more specific help, consider telling and showing more about your code and your use of background threading.
Edit
OK, so that code is in a background thread. So now you must take care to show your JOptionPane on the EDT. Consider making these changes:
} else if(sb.toString().equalsIgnoreCase("invalid:Username")) {
b = false;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JOptionPane.showMessageDialog(null, "alert", "alert",
JOptionPane.ERROR_MESSAGE);
}
});
}
Note: code not tested by compiling or by running. Please be wary of typos.
Edit 2
As an aside, you've got other issues including that the connected variable should not be static. You also have threading issues:
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (hostTxt.getText() == null || displayNameTxt.getText() == null) {
} else {
// .........
// ********** you should not have this type of code on the EDT
while (!connected) {
// ........
}
// ...............
}
}
});