How do I avoid creating Swing elements within a main method? - java

Currently my code will not run because I have no main, but when I make a main it must be static, and I am under the impression I shouldn't be making all of my variables for the Swing elements Static, as per the advice of many.
I'm not sure how to invoke the methods without using main as the constructor, currently my gui does not appear.
Thanks.
package movieinfo;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.commons.io.FileUtils;
public class Swinggui {
JButton enter;
public JTextField movietext;
JList listofmovies;// converts moviestowatch into gui
// element.
File textfilemovie; // file which movies marked for watching
// are saved
java.util.List<String> moviestowatch; // arraylist which is
// populated by
// textfilemovie
// than printed to
// GUI element
ListSelectionListener setSearch;
JButton add;
String info;
public Swinggui() throws IOException {
yourMovies();
gui();
jsonAndButtons();
}
public void gui() {
JFrame maingui = new JFrame("Gui");
maingui.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
enter = new JButton("Get Info");
c.gridx = 2;
c.gridy = 1;
maingui.add(enter, c);
add = new JButton("add");
c.gridx = 5;
c.gridy = 6;
maingui.add(add, c);
JTextArea movieinfo = new JTextArea(info, 5, 20);
movieinfo.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2,
Color.red));
movietext = new JTextField(18);
c.gridx = 1;
c.gridy = 1;
maingui.add(movietext, c);
final JScrollPane scrolll = new JScrollPane(movieinfo);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 2;
maingui.add(scrolll, c);
final JLabel titlee = new JLabel("Enter movie name below!");
c.gridx = 1;
c.gridy = 0;
maingui.add(titlee, c);
c.gridx = 1;
c.gridy = 3;
maingui.add(titlee, c);
final JLabel watchlist = new JLabel("Watchlist");
c.gridx = 5;
c.gridy = 1;
maingui.add(watchlist, c);
maingui.setResizable(false);
maingui.setVisible(true);
listofmovies = new JList(moviestowatch.toArray());
c.gridx = 4;
c.gridy = 3;
maingui.add(new JScrollPane(listofmovies), c);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
scrolll.getPreferredSize();
listofmovies.addListSelectionListener(setSearch);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
}
public void jsonAndButtons() {
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(apicall.getMovieInfo(movietext.getText()
.replaceAll(" ", "%20")));
info = apicall.getMovieInfo(movietext.getText().replaceAll(" ",
"%20"));
}
});
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
FileUtils.writeStringToFile(new File(
org.apache.commons.io.FileUtils.getUserDirectory()
+ "/yourmovies.txt"),
"\n" + movietext.getText(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
moviestowatch = FileUtils.readLines(textfilemovie);
listofmovies = new JList(moviestowatch.toArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void yourMovies() throws IOException {
textfilemovie = new File(
org.apache.commons.io.FileUtils.getUserDirectory()
+ "/yourmovies.txt");
textfilemovie.createNewFile();
moviestowatch = FileUtils.readLines(textfilemovie);
setSearch = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
info = apicall.getMovieInfo(((String) listofmovies
.getSelectedValue()).replaceAll(" ", "%20"));
}
};
}
}

Firstly, don't keep everything in one class. Create some other class and then create object of that type, and invoke its methods, it would look like this in your main() method:
MyClass myClass = new MyClass();
myClass.doStuff();

inside your main put:
new Swinggui();
This will pull you out of the static context and bring you into the non-static Swinggui constructor

Make your class Swinggui extend JFrame.
Then create a main method and create object of Swinggui
Swinggui gui = new Swinggui();
now you must make gui visible, for this write.
gui.setVisible(true);
And you are good to go.
Refer everything in code using "this" and you would have non static items.

Related

How to add the JcomboBox in JTable using Java?

I Browse a csv file and load the contents of the file to Jtable.
I want to add the JcomboBox in every row of the JTable .
Here is my tool for your reference:
I dont know how to add the ComboBox in each column of row.please help me to solve this problem .Any help is appreciated
Here is my code for your reference....
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.List;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import com.csvreader.CsvReader;
public class GUI {
private JPanel dialog = null;
private AboutDialog adlg;
public void addComponentsToPane() {
final JTextField txtfldcsvpth = new JTextField("Select a folder");
final JTextField txtsimprepname = new JTextField("Select a folder");
final JButton Btnbrowsecsv = new JButton("Select file");
final JButton BtnsimpRep = new JButton("Create SimpRep");
final JTable table = new JTable(){
final long serialVersionUID = 1L;
public boolean isCellEditable(int row,int column) {
return false;
};
};
BtnsimpRep.setEnabled(true);
dialog.setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.anchor = GridBagConstraints.LINE_START;
gBC.fill = GridBagConstraints.HORIZONTAL;
gBC.insets = new Insets(3, 3, 3, 3);
gBC.weightx = 1;
gBC.weighty = 0;
/******************************Browse Csv File***************************************/
JLabel label1 = new JLabel("Input File");
label1.setHorizontalAlignment(SwingConstants.RIGHT);
label1.setHorizontalTextPosition(SwingConstants.RIGHT);
label1.setPreferredSize(new Dimension(100, Btnbrowsecsv
.getPreferredSize().height));
gBC.gridx = 0;
gBC.gridy = 0;
dialog.add(label1, gBC);
//jtextfield for CsvPath
gBC.gridx = 1;
gBC.gridy = 0;
txtfldcsvpth.setPreferredSize(new Dimension(200, Btnbrowsecsv
.getPreferredSize().height));
txtfldcsvpth.setEditable(false);
dialog.add(txtfldcsvpth, gBC);
//Jbutton for Csv Browsing..
gBC.gridx = 2;
gBC.gridy = 0;
Btnbrowsecsv.setToolTipText("Select folder containing STEP files");
Btnbrowsecsv.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String selectedFile = fileChooserMethod();
if (selectedFile != null) {
txtfldcsvpth.setText(selectedFile);
try{
BufferedReader br = new BufferedReader(new FileReader(new File(selectedFile)));
ArrayList <String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
JOptionPane.showMessageDialog(null, elements);
String[] columNames = new String[] {"Serial No","PartNumber", "Quantity"};
Object[][] content = new Object[elements.size()][3];
for(int i=1; i<elements.size(); i++) {
content[i][0] = i;
content[i][1] = elements.get(i)[1].trim();
content[i][2] = elements.get(i)[0].trim();
//content[i][2] = elements.get(i)[2].trim();
// content[i][3] = elements.get(i)[3].trim();
}
JOptionPane.showMessageDialog(null, content.length);
table.setModel(new DefaultTableModel(content,columNames));
}catch(Exception e){
}
}
}
});
dialog.add(Btnbrowsecsv, gBC);
/******************************JTable for CsvGrid***************************************/
JScrollPane js=new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
js.setPreferredSize(new Dimension(300 + Btnbrowsecsv
.getPreferredSize().width, 400));
js.setVisible(true);
js.setHorizontalScrollBar(null);
// final JTable jt=new JTable(data,column);
table.setCellSelectionEnabled(false);
table.setRowSelectionAllowed(false);
table.setBorder(BorderFactory.createEtchedBorder());
table.setRowHeight(20);
table.setVisible(true);
gBC.gridx = 0;
gBC.gridy = 1;
gBC.gridwidth = 3;
dialog.add(js, gBC);
/******************************JButton for SimpRepCreation***************************************/
gBC.gridx = 0;
gBC.gridy = 4;
gBC.gridwidth = 3;
BtnsimpRep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
boolean allFilesConverted = false;
}
});
dialog.add(BtnsimpRep, gBC);
}
public GUI() {
// JDialog.setDefaultLookAndFeelDecorated(true);
dialog = new JPanel();
// Set up the content pane.
addComponentsToPane();
dialog.setSize(dialog.getPreferredSize());
adlg = new AboutDialog(dialog);
}
/*****************************file choosing method********************************************/
private String fileChooserMethod() {
JFileChooser fileChooser = new JFileChooser(".");
FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV files", "csv");
fileChooser.setFileFilter(filter);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
int retVal = fileChooser.showDialog(dialog, "Select File");
if (retVal == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile().getPath();
} else {
return null;
}
}
public static Object gettable (String csvPath){
try {
BufferedReader br = new BufferedReader(new FileReader(new File(csvPath)));
ArrayList <String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
Object[][] content = new Object[elements.size()][2];
for(int i=0; i<elements.size(); i++) {
content[i][0] = elements.get(i)[0].trim();
content[i][1] = elements.get(i)[1].trim();
//content[i][2] = elements.get(i)[2].trim();
//content[i][3] = elements.get(i)[3].trim();
}
return content;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
new GUI();
}
}
Thanks Regards,
Dinesh
Do you need to set the combo box in a specific cell?
You can set a cell renderer which uses a JCombobox. Similar to this:
http://www.java2s.com/Tutorial/Java/0240__Swing/UsingaJComboBoxinaCellinaJTableComponent.htm

How I supposed to make program to stop and wait for something? JAVA

got a problem here, trying to create a login to database system at the moment. I have to classes : UserLogManagerMainWindow and DatabaseConnectionFrame. My program is about log management. I want to make a database connection :
UserLogManagerMainWindow class has a button "Connect to database", on it's click DatabaseConnectionFrame initialize and gets up a frame with jlabels and jtextfields, after I enter everything i need, i press "Login" button, after this I want that my UserLogManagerMainWindow class continues on pressenting the logs from connected database.
I have written some code about how it supposed to look : "the logic about what am i trying to say"
connectToDatabaseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
DatabaseConnectionFrame dcf = new DatabaseConnectionFrame();
dcf.setVisible(true);
if(dcf.answer == true) {
importButtons(menuBar);
setJMenuBar(menuBar);
try {
DatabaseComm.getColumnNamesToPanel(model, titles);
projects = DatabaseComm.AddLogsToArrayReturnProjectNames(events);
DatabaseComm.fillDataToPanel(model, events, titles, row);
DatabaseComm.resizeColumnWidth(table);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else {
System.out.println("not working");
}
}
});
But if statement does not working, i know why. That's why i'm asking how to make it work? More likely, threading is the key, but not good at it at the moment. Any tips without threading? And if threading is the only way, may i get some help of it?
Giving DatabaseConnectionFrame class below either:
package manager;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.SwingConstants;
import javax.swing.JButton;
public class DatabaseConnectionFrame extends JFrame{
private JPanel contentPane;
private JTextField address;
private JPasswordField password;
private JTextField username;
private JButton btnLogin;
private JButton btnCancel;
private JLabel lblPort;
private JTextField port;
public boolean answer = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DatabaseConnectionFrame frame = new DatabaseConnectionFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DatabaseConnectionFrame() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(450,250);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
JLabel lblDatabaseIpAddress = new JLabel("Database ip address:");
GridBagConstraints gbc_lblDatabaseIpAddress = new GridBagConstraints();
gbc_lblDatabaseIpAddress.anchor = GridBagConstraints.EAST;
gbc_lblDatabaseIpAddress.insets = new Insets(0, 0, 5, 5);
gbc_lblDatabaseIpAddress.gridx = 0;
gbc_lblDatabaseIpAddress.gridy = 0;
contentPane.add(lblDatabaseIpAddress, gbc_lblDatabaseIpAddress);
address = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
contentPane.add(address, gbc_textField);
address.setColumns(10);
lblPort = new JLabel("Port");
GridBagConstraints gbc_lblPort = new GridBagConstraints();
gbc_lblPort.anchor = GridBagConstraints.EAST;
gbc_lblPort.insets = new Insets(0, 0, 5, 5);
gbc_lblPort.gridx = 0;
gbc_lblPort.gridy = 1;
contentPane.add(lblPort, gbc_lblPort);
port = new JTextField();
GridBagConstraints gbc_textField1 = new GridBagConstraints();
gbc_textField1.insets = new Insets(0, 0, 5, 0);
gbc_textField1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField1.gridx = 1;
gbc_textField1.gridy = 1;
contentPane.add(port, gbc_textField1);
port.setColumns(10);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_lblUsername = new GridBagConstraints();
gbc_lblUsername.anchor = GridBagConstraints.EAST;
gbc_lblUsername.insets = new Insets(0, 0, 5, 5);
gbc_lblUsername.gridx = 0;
gbc_lblUsername.gridy = 2;
contentPane.add(lblUsername, gbc_lblUsername);
username = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.insets = new Insets(0, 0, 5, 0);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 1;
gbc_textField_1.gridy = 2;
contentPane.add(username, gbc_textField_1);
username.setColumns(10);
JLabel lblPassword = new JLabel("Password");
GridBagConstraints gbc_lblPassword = new GridBagConstraints();
gbc_lblPassword.anchor = GridBagConstraints.EAST;
gbc_lblPassword.insets = new Insets(0, 0, 5, 5);
gbc_lblPassword.gridx = 0;
gbc_lblPassword.gridy = 3;
contentPane.add(lblPassword, gbc_lblPassword);
password = new JPasswordField();
GridBagConstraints gbc_passwordField = new GridBagConstraints();
gbc_passwordField.insets = new Insets(0, 0, 5, 0);
gbc_passwordField.fill = GridBagConstraints.HORIZONTAL;
gbc_passwordField.gridx = 1;
gbc_passwordField.gridy = 3;
contentPane.add(password, gbc_passwordField);
btnLogin = new JButton("Login");
GridBagConstraints gbc_btnLogin = new GridBagConstraints();
gbc_btnLogin.insets = new Insets(0, 0, 0, 5);
gbc_btnLogin.gridx = 0;
gbc_btnLogin.gridy = 4;
contentPane.add(btnLogin, gbc_btnLogin);
btnCancel = new JButton("Cancel");
GridBagConstraints gbc_btnCancel = new GridBagConstraints();
gbc_btnCancel.gridx = 1;
gbc_btnCancel.gridy = 4;
contentPane.add(btnCancel, gbc_btnCancel);
btnCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String dbAddress = address.getText();
String dbPort = port.getText();
String dbUsername = username.getText();
char[] dbPassword = password.getPassword();
if( dbAddress.isEmpty() || dbPort.isEmpty() || dbUsername.isEmpty() || dbPassword.length == 0) {
JOptionPane.showMessageDialog(getParent(),
"All fields have to be filled!");
}
else {
if(databaseValidation(dbAddress, dbPort, dbUsername, dbPassword)) {
JOptionPane.showMessageDialog(getParent(),
"Connected!");
answer = true;
setVisible(false);
}
else {
JOptionPane.showMessageDialog(getParent(),
"There was error connecting to the database!");
answer = false;
}
}
System.out.println(answer);
}
});
}
public boolean databaseValidation(String address, String port, String username, char[] password) {
String pw = String.valueOf(password);
System.out.println(pw);
try {
Connection con = DriverManager.getConnection("jdbc:mysql://" + address + ":" + port + "/logctrl?user=" + username + "&password=" + pw );
} catch (SQLException e) {
System.out.println("Error connecting to database!");
return false;
}
System.out.println("Connected");
return true;
}
}
If you want to wait for the user input, you have two choices, you either make your own observer pattern which can be called at some point in the future when the state changes in some way or you use a dialog, which will block the codes execution at the point the dialog is made visible and will wait till it's closed
See How to use dialogs for details
import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Show the dialog");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(TestPane.this), "I'm in charge now", true);
JButton btn = new JButton("Waiting");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(btn);
dialog.pack();
dialog.setLocationRelativeTo(TestPane.this);
dialog.setVisible(true);
JOptionPane.showMessageDialog(TestPane.this, "You won't see this till the dialog is closed");
}
});
}
}
}

Java ActionListener Return Variable To Method That Contains ActionListener

I have a method like so, which is given an array of JButton and returns their text whenever they are pressed:
public static String foo(JButton[] buttons) {
for (JButton i : buttons) {
i.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
return i.getText();
}
});
}
}
But, of course, this code will not compile because I am returning a variable to a null method. So, how would I have i.getText() return its output too the foo() method?
Edit, all of the code:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JCustomFrame {
public static void showMessageFrame(String title, String message,
String[] textOnButtons, ImageIcon icon) {
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.RELATIVE;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(5, 5, 5, 5);
JLabel messageLabel = new JLabel(message);
messageLabel.setFont(messageLabel.getFont().deriveFont(16.0f));
panel.add(messageLabel, c);
c.gridy = 1;
c.gridx = 0;
for (int i = 0; i < textOnButtons.length; i++) {
JButton button = new JButton(textOnButtons[i]);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
return ((JButton) arg0.getSource()).getText();
frame.dispose();
}
});
button.setFont(button.getFont().deriveFont(16.0f));
panel.add(button, c);
c.gridx++;
}
if (icon == null) {
frame.setIconImage(new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB_PRE));
} else {
frame.setIconImage(icon.getImage());
}
frame.add(panel);
frame.setTitle(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
public static void main(String[] args) {
JCustomFrame.showMessageFrame("Test Frame",
"Do you really want to do this?", new String[] { "Hell No",
"Sure, Why Not" }, null);
}
}
This statement doesn't make sense:
So, how would I have i.getText() return its output too the foo() method?
The method foo() is no longer running after the ActionListeners have been added to the buttons, and certainly will have ended by the time a user pushes a button, as per the rules of event-driven programming. Instead, though you could have the ActionListeners change the state of a class, any class, and that should suffice. For instance:
class FooClass {
private String text;
public void foo(JButton[] buttons) {
for (JButton i : buttons) {
i.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
text = e.getActionCommand();
}
});
}
}
}
If you need greater detail on a viable solution, please tell us more details about your actual program and your specific problem.
Now if you actually needed a method to return the value of the button pressed, you would need to do this via notification mechanisms and a call-back method, but again the details of a solution will depend on the details of the actual problem and code.
Edit
You're trying to emulate a JOptionPane. Your solution is to either use a JOptionPane, adding a JPanel to it, or create your own using a modal JDialog:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JCustomFrame2 {
public static String showMessageFrame(Window owner, String title,
String message, String[] textOnButtons, ImageIcon icon) {
final JDialog dialog = new JDialog(owner);
StringBuilder sb = new StringBuilder();
// make it application modal!
dialog.setModalityType(ModalityType.APPLICATION_MODAL);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBackground(Color.WHITE);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.EAST;
c.fill = GridBagConstraints.RELATIVE;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(5, 5, 5, 5);
JLabel messageLabel = new JLabel(message);
messageLabel.setFont(messageLabel.getFont().deriveFont(16.0f));
panel.add(messageLabel, c);
c.gridy = 1;
c.gridx = 0;
for (int i = 0; i < textOnButtons.length; i++) {
JButton button = new JButton(textOnButtons[i]);
button.addActionListener(new ButtonListener(sb));
button.setFont(button.getFont().deriveFont(16.0f));
panel.add(button, c);
c.gridx++;
}
if (icon == null) {
dialog.setIconImage(new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB_PRE));
} else {
dialog.setIconImage(icon.getImage());
}
dialog.add(panel);
dialog.setTitle(title);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.pack();
dialog.setVisible(true);
return sb.toString();
}
private static class ButtonListener implements ActionListener {
private StringBuilder sb;
public ButtonListener(StringBuilder sb) {
this.sb = sb;
}
#Override
public void actionPerformed(ActionEvent e) {
sb.append(e.getActionCommand());
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
if (win != null) {
win.dispose();
}
}
}
public static String showMessageFrame(String title,
String message, String[] textOnButtons, ImageIcon icon) {
return showMessageFrame(null, title, message, textOnButtons, icon);
}
public static void main(String[] args) {
String result = JCustomFrame2.showMessageFrame("Test Frame",
"Do you really want to do this?", new String[] { "Hell No",
"Sure, Why Not" }, null);
System.out.println(result);
}
}
Why so complicated? whatever foo is supposed to do, it would be a lot easier to simply call another method from inside the ActionListener with the name of the button as argument. Or, if you really want to achieve something like this, make the thread wait for the user to press a button.
public void doSomething(){
JButton[] someButtons = ...;//whereever you create the buttons
System.out.println(foo(someButtons));
}
public static String foo(JButton[] buttons){
final String someString = "";
final Object lock = new Object();
for(JButton b : buttons){
b.addActionListener(e -> {
someString.concat(b.getName());
synchronized(lock){
lock.notifyAll();
}
});
}
synchronized(lock){
try{
lock.wait();
}catch(InterruptedException e){}
}
return someString;
}

Getting String info from another java class rather than the same one

so I have 2 classes, 1 for a very small interface and 1 for some calculations. basically I want to have a string displayed in a box. That's done but now I need the string to be obtained from my other class. Here is where my question lies, How do I do that if my code looks like this:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class SwingJPanelDemo extends JFrame { //where I want the string to be send to from the other class
String letter = "apple"; //teststring
private JLabel LetterTest = new JLabel(letter); //where I use the string
private JButton NextButton = new JButton("Next");
private JButton NoButton = new JButton("No");
public SwingJPanelDemo() {
super("Is This Your Letter?");
JPanel newPanel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(10, 10, 10, 10);
constraints.gridx = 0;
constraints.gridy = 0;
newPanel.add(LetterTest, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
newPanel.add(NextButton, constraints);
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
newPanel.add(NoButton, constraints);
newPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Is This Your Letter?"));
add(newPanel);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
// set look and feel to the system look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SwingJPanelDemo().setVisible(true);
}
});
}
}
How would I go about Getting s string to this?
If your other class looks like this:
public class Other {
public static String text = "some text";
}
you can just use Other.text to get the String.

Populating JList with List<String> nullpointerexception

I am trying to populate the JList using a file I create, before I write the code for adding things to the file that is being read, I would like to make sure it will be read, and display properly on the screen. I am getting a nullpointerexception, and my GUI is launching, but only the "enter" button is showing. I appreciate any help anyone can offer me with this issue.
package movieinfo;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.apache.commons.io.FileUtils;
import com.json.parsers.JSONParser;
import com.json.parsers.JsonParserFactory;
public class Swinggui {
private static JButton enter;
private static JTextField movietext;
private static JTextArea movieinfo;
private static JList listofmovies;//converts moviestowatch into gui element.
private static File textfilemovie; //file which movies marked for watching are saved
private static java.util.List<String> moviestowatch; //arraylist which is populated by textfilemovie than printed to GUI element.
public static void main(String[] args) throws IOException
{
Gui();
Json();
YourMovies();
}
public static void Gui()
{
JFrame maingui = new JFrame("Gui");
maingui.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
enter = new JButton("Enter");
c.gridx = 2;
c.gridy = 1;
maingui.add(enter, c);
movieinfo = new JTextArea(5,20);
movieinfo.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.red));
movietext = new JTextField(18);
c.gridx = 1;
c.gridy = 1;
maingui.add(movietext, c);
final JScrollPane scrolll = new JScrollPane(movieinfo);
c.gridx = 1;
c.gridy = 4;
c.gridwidth = 2;
maingui.add(scrolll, c);
final JLabel titlee = new JLabel("Enter movie name below!");
c.gridx = 1;
c.gridy = 0;
maingui.add(titlee, c);
maingui.setResizable(false);
maingui.setVisible(true);
listofmovies = new JList(moviestowatch.toArray());
c.gridx = 2;
c.gridy = 3;
maingui.add(new JScrollPane(listofmovies), c);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
scrolll.getPreferredSize();
//pangui.setPreferredSize(new Dimension(300, 150));
//pangui.add(scrolll, BorderLayout.CENTER);
//movieinfo.add(scrolll);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
}
public static void Json()
{
enter.addActionListener(new ActionListener(){
#SuppressWarnings("rawtypes")
public void actionPerformed(ActionEvent e)
{
System.out.println(apicall.getMovieInfo(movietext.getText()));
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonData=parser.parseJson(apicall.getMovieInfo(movietext.getText()));
String Title = (String)jsonData.get("Title");
String Year = (String)jsonData.get("Year");
String Plot = (String)jsonData.get("Plot");
movieinfo.setText("Title: "+Title+"\nYear: "+ Year +"\nPlot: "+Plot);
}
});
}
public static void YourMovies() throws IOException
{
textfilemovie = new File("yourmovies.txt");
moviestowatch = FileUtils.readLines(textfilemovie);
}
}
You're calling moviestowatch.toArray() before you instantiate moviestowatch. You need to call YourMovies() before you call Gui().
I see that in the method Gui() you are using an un-initialized list. The method where the list is getting initialized is called afterwards ( method YourMovies())
listofmovies = new JList(moviestowatch.toArray());
^^^^^^^^^^^^^
this is null
On a side note:
As per Java naming convention, methods start with small case and follow camel case, example - yourMovies() gui()
moviestowatch is not assigned when Gui is called - reverse the order of these methods
YourMovies();
Gui();
and follow Java naming conventions for method names with initial lowercase latter, e.g. loadMovies

Categories