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

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.

Related

Word count for a scrollable JTextArea (scrollPane) word count

I have been trying to make a program where data inputted into a JTextArea, would then be counted and then displayed on a JLabel the number of words, after a button is clicked.
However the code I have tried to use, just shows the value of 1 everytime.
Any idea why?
`
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SPanel extends JPanel {
public SPanel(){
final TextAPanel textPanel = new TextAPanel();
final JLabel outputLabel = new JLabel();
JButton click = new JButton ("Click");
click.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String word = textPanel.inputBox.getText();
System.out.println("Test: " +word);
}
});
}
}
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextAPanel extends JPanel {
public JTextArea inputBox = new JTextArea(20,10);
public JScrollPane scrollPane = new JScrollPane(inputBox);
TextAreaPanel(){
JLabel title = new JLabel("Please type in the box below:");
inputBox.setLineWrap(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.NORTHWEST;
gc.gridx = 0;
gc.gridy = 0;
add(title,gc);
gc.gridx = 0;
gc.gridy = 1;
add(scrollPane, gc);
}
}
Just to put it in context, my JTextArea is on a seperate panel / class to the panel containing the button and JLabel.
Every time I run the program and click the button, after inputting some words the value is always one even if the text box is empty.
Well, if you create a new TextAPanel and assign it to the textPanel variable - then when you try to get input you get nothing, because the newly created panel doesn't contain anything. If textPanel is a field in your class, you should just remove the textPanel = new TextAPanel(); line and it should work fine. If you get a NullPointerException, it means you forgot to initialize it earlier in the code, you should probably do it in the constructor.
EDIT: OK, I made it work, the code is below. I have no idea how your program compiled, because in your TextAPanel class you had TextAreaPanel() method/constructor, which caused compilation error in my Eclipse. Anyway, I got this working, you'll need to complete it, but this should get you started:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
#SuppressWarnings("serial")
public class SPanel extends JPanel {
public SPanel() {
final TextAPanel textPanel = new TextAPanel();
this.add(textPanel);
final JLabel outputLabel = new JLabel();
JButton click = new JButton("Click");
click.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
String word = textPanel.inputBox.getText();
System.out.println("Test: " + word);
System.out.println(word.split("\\s+").length);
}
});
this.add(click);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.add(new SPanel());
f.setVisible(true);
}
}
#SuppressWarnings("serial")
class TextAPanel extends JPanel {
public JTextArea inputBox = new JTextArea(20, 10);
public JScrollPane scrollPane = new JScrollPane(inputBox);
TextAPanel() {
JLabel title = new JLabel("Please type in the box below:");
inputBox.setLineWrap(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.NORTHWEST;
gc.gridx = 0;
gc.gridy = 0;
add(title, gc);
gc.gridx = 0;
gc.gridy = 1;
add(scrollPane, gc);
}
}

Output not getting redirecting to proper Jtextarea

MainFrame.java
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
public class MainFrame extends JFrame{
private TextPanel textPanel1;
private TextPanel textPanel2;
private FormPanel formPanel;
private JSplitPane splitPane;
private JTabbedPane tabPane;
public MainFrame() {
super("Hello");
setLayout(new BorderLayout());
tabPane = new JTabbedPane();
textPanel1 = new TextPanel();
tabPane.addTab("Tab 1", textPanel1);
textPanel2 = new TextPanel();
tabPane.addTab("Tab 2", textPanel2);
//Newly Added code
formPanel = new FormPanel(textPanel1,textPanel2);
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,formPanel,tabPane);
splitPane.setOneTouchExpandable(true);
add(splitPane,BorderLayout.CENTER);
// add(formPanel,BorderLayout.WEST);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(500, 400));
setSize(600, 500);
}
}
TextPanel.java
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Scrollbar;
import java.io.ByteArrayOutputStream;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
public class TextPanel extends JPanel {
private JTextArea textArea1;
private JTextArea textArea2;
private FormPanel formPanel;
//Newly added code
private TextPanel textPanel;
public TextPanel(){
setLayout(new BorderLayout());
textArea1 = new JTextArea();
add(new JScrollPane(textArea1),BorderLayout.CENTER);
//textArea2 = new JTextArea();
//add(new JScrollPane(textArea2),BorderLayout.CENTER);
}
//Newly added code
public void appendText(String string, TextPanel textPanel2) {
// TODO Auto-generated method stub
this.textPanel = textPanel2;
textArea1.append(string);
}
}
FormPanel.java
import java.awt.Dimension;
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.event.KeyEvent;
import java.io.ObjectInputStream.GetField;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class FormPanel extends JPanel {
private static int numberOfTabs = 1;
private JLabel serverName_1;
private JLabel serverName_2;
private JButton startServer_1;
private JButton startServer_2;
//Added New Code
private TextPanel textPanel1;
private TextPanel textPanel2;
JumpHosts jumpHosts = new JumpHosts();
//Added New Code
public FormPanel(final TextPanel textPanel1,final TextPanel textPanel2){
Dimension dim = getPreferredSize();
dim.width = 350;
setPreferredSize(dim);
setMinimumSize(dim);
//Added New Code
this.textPanel = textPanel1;
this.textPanel = textPanel2;
serverName_1 = new JLabel("server1 ");
startServer_1 = new JButton("Start");
serverName_2 = new JLabel("server2 ");
startServer_2 = new JButton("Start");
startServer_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] ev = new String[]{"username#10.10.10.10","username#server1"};
String cmd = "ls -ltr";
//jumpHosts.JumpHosts(ev,cmd);
//Newly added code
jumpHosts.JumpHosts(ev,cmd,textPanel1);
}
});
startServer_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String[] ev = new String[]{"username#10.10.10.10","username#server2"};
String cmd = "ls -ltr";
//jumpHosts.JumpHosts(ev,cmd);
//Newly added code
jumpHosts.JumpHosts(ev,cmd,textPanel2);
}
});
Border innerborder = BorderFactory.createTitledBorder("Detail");
Border outerborder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
setBorder(BorderFactory.createCompoundBorder(outerborder, innerborder));
layoutComponents();
}
public void layoutComponents(){
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
//////////// First row ////////////
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 0.01;
gc.gridx = 0;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(serverName_1,gc);
/////////// Next Column ////////////
gc.gridy = 0;
gc.weightx = 2;
gc.weighty = 0.01;
gc.gridx = 2;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(startServer_1,gc);
//////////// Second row ////////////
gc.gridy++;
gc.weightx = 1;
gc.weighty = 0.1;
gc.gridx = 0;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(serverName_2,gc);
/////////// Next Column ////////////
//gc.gridy = 1;
gc.weightx = 2;
gc.weighty = 0.1;
gc.gridx = 2;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.FIRST_LINE_START;
add(startServer_2,gc);
}
}
JumpHosts.java
import com.jcraft.jsch.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.*;
public class JumpHosts {
TextPanel textPanel = new TextPanel();
//Newly added code
public void JumpHosts(final String[] arg,final String command,final TextPanel textPanel) {
StringBuffer resultDisplayBuffer = new StringBuffer();
SwingWorker sw = new SwingWorker(){
#Override
protected Object doInBackground() throws Exception {
try{
JSch jsch = new JSch();
if(arg.length <= 1){
System.out.println("This program expects more arguments.");
System.exit(-1);
}
Session session = null;
Session[] sessions = new Session[arg.length];
String host = arg[0];
String user = host.substring(0, host.indexOf('#'));
host = host.substring(host.indexOf('#')+1);
sessions[0] = session = jsch.getSession(user, host, 22);
session.setUserInfo(new MyUserInfo());
session.connect();
//textPanel.appendText("The session has been established to "+user+"#"+host+"\n");
//Newly added code
textPanel.appendText("The session has been established to "+user+"#"+host+"\n",textPanel);
for(int i = 1; i < arg.length; i++){
host = arg[i];
user = host.substring(0, host.indexOf('#'));
host = host.substring(host.indexOf('#')+1);
int assinged_port = session.setPortForwardingL(0, host, 22);
textPanel.appendText("portforwarding: "+
"localhost:"+assinged_port+" -> "+host+":"+22+"\n");
sessions[i] = session =
jsch.getSession(user, "localhost", assinged_port);
session.setUserInfo(new MyUserInfo());
session.setHostKeyAlias(host);
session.connect();
textPanel.appendText("The session has been established to "+
user+"#"+host+"\n");
}
String sudo_pass;
{
JTextField passwordField=(JTextField)new JPasswordField(8);
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null,
ob,
"Enter password for sudo",
JOptionPane.OK_CANCEL_OPTION);
if(result!=JOptionPane.OK_OPTION){
System.exit(-1);
}
sudo_pass=passwordField.getText();
}
Channel channel=session.openChannel("exec");
// man sudo
// -S The -S (stdin) option causes sudo to read the password from the
// standard input instead of the terminal device.
// -p The -p (prompt) option allows you to override the default
// password prompt and use a custom one.
((ChannelExec)channel).setCommand("sudo -S -p '' "+command);
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass + "\n").getBytes());
out.flush();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
textPanel.appendText(new String(tmp,0,i));
}
if (channel.isClosed()) {
textPanel.appendText(new String("exit-status: " + channel.getExitStatus())+ "\n");
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
System.out.println(ee);
}
}
channel.disconnect();
textPanel.appendText("Disconnect\n\n");
for(int i = sessions.length-1; i >= 0; i--){
sessions[i].disconnect();
}
}
catch(Exception e){
System.out.println(e);
}
return null;
}
public void done(){
try {
System.out.println(get());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
sw.execute();
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
Object[] options={ "yes", "no" };
int foo=JOptionPane.showOptionDialog(null,
str,
"Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
return foo==0;
}
String passwd;
JTextField passwordField=(JTextField)new JPasswordField(20);
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return true; }
public boolean promptPassword(String message){
Object[] ob={passwordField};
int result=
JOptionPane.showConfirmDialog(null, ob, message,
JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION){
passwd=passwordField.getText();
return true;
}
else{ return false; }
}
public void showMessage(String message){
JOptionPane.showMessageDialog(null, message);
}
final GridBagConstraints gbc =
new GridBagConstraints(0,0,1,1,1,1,
GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE,
new Insets(0,0,0,0),0,0);
private Container panel;
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
panel = new JPanel();
panel.setLayout(new GridBagLayout());
gbc.weightx = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridx = 0;
panel.add(new JLabel(instruction), gbc);
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.RELATIVE;
JTextField[] texts=new JTextField[prompt.length];
for(int i=0; i<prompt.length; i++){
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.weightx = 1;
panel.add(new JLabel(prompt[i]),gbc);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1;
if(echo[i]){
texts[i]=new JTextField(20);
}
else{
texts[i]=new JPasswordField(20);
}
panel.add(texts[i], gbc);
gbc.gridy++;
}
if(JOptionPane.showConfirmDialog(null, panel,
destination+": "+name,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE)
==JOptionPane.OK_OPTION){
String[] response=new String[prompt.length];
for(int i=0; i<prompt.length; i++){
response[i]=texts[i].getText();
}
return response;
}
else{
return null; // cancel
}
}
}
}
so whenever I am clicking on any button the output gets redirected to only one textarea whereas other seems to be no usable. i.e to the last created tab.
I want that when I am clicking on button 1 then it should write to tab 1 and when I am clicking on button 2 then it should write to tab 2 and so on.
Examples appreciated as I am new to java
In JumpHosts:
TextPanel textPanel = new TextPanel();
you create an instance of TextPanel which is referenced by no other object in the program. This is not either of the TextPanels you created in MainFrame.
You need to pass the TextPanels created in MainFrame, namely:
private TextPanel textPanel;
private TextPanel textPanel2;
into your JumpHosts constructor:
JumpHosts(TextPanel textPanel1, TextPanel textPanel2)
to be able to reference the same TextPanel as MainFrame does.
Response to Followup:
You will need to pass your TextPanel first to your FormPanel constructor from within your MainFrame constructor. You will then need to modify your FormPanel contructor to pass the TextPanel to your JumpHosts constructor.

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;
}

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

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.

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