How can i get my program to reply with an answer - java

I'm working on a program that you can have a conversation with so I could ask it hello and it would reply.
But when typing in the text field I can't seem to get it to display the answer in the other text field.
here is my code so far any help is useful
public class Gui extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField input, output;
private String answer;
private JPanel contentpanel;
boolean opchosen = false;
public Gui() {
super("Vixen");
input = new JTextField(null, 20);
output = new JTextField(null, 20);
question q = new question();
input.addActionListener(q);
contentpanel = new JPanel();
contentpanel.setBackground(Color.lightGray);
contentpanel.setLayout(new FlowLayout());
contentpanel.add(input, BorderLayout.NORTH);
input.setEditable(true);
contentpanel.add(output, BorderLayout.SOUTH);
output.setEditable(false);
this.setContentPane(contentpanel);
}
private class question implements ActionListener {
public void actionPerformed(ActionEvent Event) {
JTextField input = (JTextField) Event.getSource();
if (input.equals("whats you name")) {
if (opchosen == false) {
if (answer == null) {
answer = "My name is Vixen!";
}
}
}
if (opchosen == false) {
output.setText(answer);
}
}
}
}
}
Okay that problem is fixed but when i try to ask another question my output box wont display the new answer its just stuck on My name is Vixen

Use your JTextField for input only. In the text field's actionPerformed() implementation, append() the input text and the response to an adjacent JTextArea. This example illustrated the basic approach. In the example, responses come from another socket; yours will come from code that handles canned responses.

Related

trouble hooking up an actionlistener to a radiobutton

I'm trying to create a personality quiz. The idea is that a JPanel will show up with the first question and then once the user selects one of the radio buttons, the second JPanel with the second question will show up.
Since I have 5 questions each with 3 answer choices I thought it would be faster and more efficient to create a method that creates radio buttons and adds an ActionListener but I'm having trouble getting the listener to work. Right now to see if it works I'm just trying to change the button text when it is selected.
I tried adding the listener to the button in the createButton method but I haven't had luck. Originally I had it as a parameter in the method but that didn't get the expected result so I tried to create it without the listener as a parameter. Inserting the listener as a parameter didn't change the text.
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;
public class UserInterface extends ClickListener implements Runnable
{
private ActionListener listeners;
private JFrame frame;
public UserInterface(){
}
#Override
public void run() {
frame = new JFrame("title");
frame.setPreferredSize(new Dimension(1000, 1000));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public JFrame getFrame(){
return frame;
}
private void createComponents(Container container){
BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
container.setLayout(layout);
container.add(QuizIntro());
container.add(QuestionOne());
container.add(QuestionOneGroup());
}
public JLabel QuizIntro(){
JLabel text = new JLabel("Intro text");
return text;
}
public JLabel QuestionOne(){
JLabel text = new JLabel("1. this is the first question");
return text;
}
public JPanel QuestionOneGroup(){
JRadioButton int1 = createButton("This button was created with my createButton method");
JRadioButton e1 = new JRadioButton("This button was created without that method");
JPanel panel = new JPanel();
panel.add(int1);
panel.add(e1);
return panel;
}
public JRadioButton createButton(String text){
JRadioButton b = new JRadioButton(text);
b.addActionListener(listeners);
return b;
}
}
here's my action listener
public class ClickListener implements ActionListener {
private UserInterface ui;
private JRadioButton b;
#Override
public void actionPerformed(ActionEvent ae) {
if (b.isSelected()){
b.setText("this works");
}
}
}
The actual result is that the button is selected but the text does not change. I'm having trouble figuring out if I'm running the wrong test to see if my listener works or if my listener just does not work.
Your main problem is here:
private ActionListener listeners;
You create an ActionListener but you never call it.
You're also inheriting from ClickListener but never using it.
public class UserInterface extends ClickListener implements Runnable
In your code you call:
b.addActionListener(listeners); //Listeners is null!
So, you're telling your JRadioButton to have a listener that is null.
So, here you have 2 approaches:
Remove private ActionListener listeners; from the top of your program and change:
b.addActionListener(listeners);
To:
b.addActionListener(this);
Remove extends ClickListener from your class definition and keep:
b.addActionListener(listeners);
But adding
listeners = new ClickListener();
Before
createComponents(frame.getContentPane());
IMO I would take the 2nd approach.
BTW for your ActionListener to actually change the text you don't need private variables but rather get the source and cast it. For example:
public void actionPerformed(ActionEvent ae) {
JRadioButton b = (JRadioButton) ae.getSource();
b.setText("this works");
}
Forgot to mention, please follow Java naming conventions so that your program is more readable and understandable by everyone who reads it.
firstWordLowerCaseVariable
firstWordLowerCaseMethod()
FirstWordUpperCaseClass
ALL_WORDS_UPPER_CASE_CONSTANT
And indent your code correctly as well :)
First of all the GUI should not extend the listener class. Not good. Better to keep them separate and to pass references where needed. For example, if the listener needs a reference to the GUI, pass it in as a paramter
Also, you apparently want to do is to respond to JRadioButton selection immediately with useful behavior. I would use an ItemListener not an ActionListener, since the ItemListener will tell you if the radio button has been selected. Calling getSource() on the ItemEvent will give you the current JRadioButton that was selected.
e.g.,
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class UserInterface2 extends JPanel {
public static final Object QUESTION = "question";
// fill label with blank text to expand it
private JLabel resultLabel = new JLabel(String.format("%150s", " "));
// CardLayout to allow swapping of question panels
private CardLayout cardLayout = new CardLayout();
private JPanel centerPanel = new JPanel(cardLayout);
public UserInterface2(List<Question> questions) {
centerPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
for (Question question : questions) {
centerPanel.add(createQPanel(question), question.getQuestion());
}
JPanel bottomPanel = new JPanel(new BorderLayout());
// add button that allows swapping question panels
bottomPanel.add(new JButton(new AbstractAction("Next") {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(centerPanel);
}
}), BorderLayout.LINE_START);
bottomPanel.add(resultLabel);
setLayout(new BorderLayout());
add(bottomPanel, BorderLayout.PAGE_END);
add(centerPanel);
}
private JPanel createQPanel(Question question) {
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
ButtonGroup buttonGroup = new ButtonGroup();
ItemListener myItemListener = new MyItemListener(this);
for (String answer : question.getAnswers()) {
JRadioButton answerButton = new JRadioButton(answer);
// this is present in case you want to extract the Question
// object from the JRadioButton, useful for if you want to
// test if the selected answer is correct
answerButton.putClientProperty(QUESTION, question);
// add our listener to the JRadioButton
answerButton.addItemListener(myItemListener);
// add to button group so only one can be selected
buttonGroup.add(answerButton);
// add to JPanel for display
radioPanel.add(answerButton);
}
JPanel qPanel = new JPanel(new BorderLayout());
qPanel.add(new JLabel(question.getQuestion()), BorderLayout.PAGE_START);
qPanel.add(radioPanel);
return qPanel;
}
// public method that the item listener will use to display selection
public void displayResult(String selectedText) {
resultLabel.setText(selectedText);
}
private static void createAndShowGui() {
// create mock questions
// likely this information will be in a text file
List<Question> questions = new ArrayList<>();
for (int i = 0; i < 10; i++) {
String question = "Question " + i;
List<String> answers = new ArrayList<>();
for (int j = 0; j < 4; j++) {
answers.add(String.format("Answer [%d %d]", i, j));
}
int correctIndex = (int) (Math.random() * answers.size());
// future iteration will also need correctIndex int
questions.add(new Question(question, answers, correctIndex));
}
UserInterface2 mainPanel = new UserInterface2(questions);
JFrame frame = new JFrame("User Interface");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyItemListener implements ItemListener {
private UserInterface2 ui;
public MyItemListener(UserInterface2 ui) {
this.ui = ui;
}
#Override
public void itemStateChanged(ItemEvent e) {
JRadioButton source = (JRadioButton) e.getSource();
String selected = "The JRadioButton " + source.getText();
selected += e.getStateChange() == ItemEvent.SELECTED ? " has been selected"
: " has been unselected";
// to get the actual Question object get the client property:
Question question = (Question) source.getClientProperty(UserInterface2.QUESTION);
// now can get answer Strings and check if correct one selected
System.out.println(question);
String correctAnswer = question.getAnswers().get(question.getCorrectIndex());;
if (source.getText().equals(correctAnswer)) {
selected += " and is correct";
} else {
selected += " and is incorrect";
}
// tell the GUI to display the result
ui.displayResult(selected);
}
}
class Question {
private String question;
private List<String> answers;
private int correctIndex;
public Question(String question, List<String> answers, int correctIndex) {
this.question = question;
this.answers = answers;
this.correctIndex = correctIndex;
}
public String getQuestion() {
return question;
}
public List<String> getAnswers() {
return answers;
}
public int getCorrectIndex() {
return correctIndex;
}
#Override
public String toString() {
return "Question [question=" + question + ", correctIndex="
+ correctIndex + "]";
}
}
Since there are many things to be improved in your code, I thought I'll write a sample program to show you how this kind of a thing should be done in Swing. Try it and see.
(There are few things we can improve in this sample code as well. But I just wanted to keep things simple and address only the key points.)
import javax.swing.*;
import java.awt.event.*;
public class Questions {
public static void main(String[] args) {
JFrame f = new JFrame("Questions");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new QuestionPanel());
f.setBounds(300, 200, 400, 300);
f.setVisible(true);
}
}
class QuestionPanel extends JPanel implements ActionListener {
private static final String ANSWER_1_TEXT = "Answer 1";
private static final String ANSWER_2_TEXT = "Answer 2";
private static final String ANSWER_3_TEXT = "Answer 3";
private JRadioButton answer1;
private JRadioButton answer2;
private JRadioButton answer3;
QuestionPanel() {
answer1 = new JRadioButton(ANSWER_1_TEXT);
answer2 = new JRadioButton(ANSWER_2_TEXT);
answer3 = new JRadioButton(ANSWER_3_TEXT);
answer1.addActionListener(this);
answer2.addActionListener(this);
answer3.addActionListener(this);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(answer1);
buttonGroup.add(answer2);
buttonGroup.add(answer3);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(answer1);
add(answer2);
add(answer3);
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton selectedAnswer = (JRadioButton) e.getSource();
if (selectedAnswer == answer1) {
answer1.setText(ANSWER_1_TEXT + " (selected)");
answer2.setText(ANSWER_2_TEXT);
answer3.setText(ANSWER_3_TEXT);
}
else if (selectedAnswer == answer2) {
answer1.setText(ANSWER_1_TEXT);
answer2.setText(ANSWER_2_TEXT + " (selected)");
answer3.setText(ANSWER_3_TEXT);
}
else if (selectedAnswer == answer3) {
answer1.setText(ANSWER_1_TEXT);
answer2.setText(ANSWER_2_TEXT);
answer3.setText(ANSWER_3_TEXT + " (selected)");
}
}
}
How many programmers do you need to change a lightbulb? 76, 1 to change it and 75 to say how they could've done it better.
You do have bad code practices, but thats usually because of a shaky understanding of the fundamental concepts behind the language design. So I won't comment on how your code is bad for this or that, just explain the basics you should know.
To simplify, an ActionListener is an object that will react on an ActionPerformedEvent. Lets define one, a class called Observer:
Observer has no idea who generated the event, so lets tell him, and if it is a JRadioButton, lets use it as one
public class Observer implements ActionListener{
#Override
public void ActionPerformed(ActionEvent ae){
Object source = ae.getSource();
if (source instanceof JRadioButton)
((JRadioButton) source).setText("this works");
}
Any of your JRadioButton are objects that generates ActionEvents constantly, but nobody we care about is usually watching, when we add an ActionListener we are basically saying: make this ActionListener object observe my behaviour.
So we need someone to be observed and an observer, lets make those in your UI (or a simplified version of it):
Since you are trying to use a global listener, you need to make sure there is one there, observer (our ActionListener) is null for now. Lets instantiate it This time, we know that observer is not null
public class UserInterface implements runnable{
private ActionListener observer new Observer();
//...
public void someMethodToCreateButtons(){
JRadioButton observableButton = new JRadioButton("Created here");
observableButton.addActionListener(observer);
}
And thats it, when you select observableButton, it will change its text to "this works".
Those are the basics, now, I used those names observableButton and Observer for a reason, ActionListeners are based on what is known as the observer design pattern you could pick up a book regarding designs patterns, you wont regret it.
Finally, it seems that you are making things too difficult for yourself, try to simplify your logic. Perhaps making a JPanel containing different sets of buttons and displaying it whenever a condition is true? just spitballing here, but try to keep it simple, hope it helps, good luck!

Use KeyListener in a loop

I don't have a lot of experience with KeyListeners but I used one in my application and it works fine except I need to wait for input before my program can continue. For this I made a while loop that loops until the String temp is not null (which would mean there would be input).
The problem is there is no way to type in the JTextField (called input). Below is code from my two methods that are supposed to work together so that the text in my JTextField (input) can be returned (as temp). I'm not sure why this doesn't work or how to fix it.
The keyPressed method for my KeyListener:
public void keyPressed(KeyEvent e)
{
//only sends text if the enter key is pressed
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
//if there really is text
if (!input.getText().equals(""))
{
//String temp is changed from null to input
temp=input.getText();
//text sent to another JTextField
output.append(temp+"\n");
//input no longer has text
input.setText("");
}
}
}
The method thats trying to get text, also in my KeyListener class
public String getTemp()
{
booleans isNull=temp==null;
//loops until temp is not null
while (isNull)
{
//unnecessary line of code, only used so the loop not empty
isNull=checkTemp();
}
return temp;
}
public boolean checkTemp()
{
return temp==null;
}
Your while loop is a common console program construct, but understand that you're not creating a console program here but rather an event-driven GUI, and in this situation, the while loop fights against the Swing GUI library, and you need to get rid of it. Instead of a while loop with continual polling you now want to respond to events, and if you're listening for user input into a JTextField do not use a KeyListener as this low-level listener can cause unwanted side effects. Instead add a DocumentListener to the JTextField's Document.
Edit: You're listening for the enter key, and so the solution is even easier: add an ActionListener to the JTextField!
e.g.,
input.addActionListener(e -> {
String text = input.getText().trim();
if (text.isEmpty()) {
return;
}
output.append(text + "\n");
input.setText("");
});
More complete example:
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ChatBox extends JPanel {
private static final int COLS = 40;
private JTextField input = new JTextField(COLS);
private JTextArea output = new JTextArea(20, COLS);
private JButton submitButton = new JButton("Submit");
public ChatBox() {
output.setFocusable(false); // user can't get into output
JScrollPane scrollPane = new JScrollPane(output);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
ActionListener inputListener = e -> {
String text = input.getText().trim();
if (text.isEmpty()) {
return;
}
output.append(text + "\n");
input.setText("");
input.requestFocusInWindow();
};
input.addActionListener(inputListener);
submitButton.addActionListener(inputListener);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(input);
bottomPanel.add(submitButton);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
ChatBox mainPanel = new ChatBox();
JFrame frame = new JFrame("Chat Box");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

How can I transfer values of an int and string from one program to another in Java

Ok so In my code I'm asking the user for their name and asking them to click one of 3 buttons which gives a variable a corresponding value. Now in another program I want to call upon this program and then pretty much display the string and use the int value for a certain purpose.
public class MainMenuofgame extends JFrame implements ActionListener{
JButton slow, medium, fast;
JLabel pic1, pic2, pic3, pic4;
JTextField username;
Container frame;
static String name;
static int xspeed = 0;
public MainMenuofgame() {
super ("Main Menu of Rocket Launch");
frame = getContentPane ();
frame.setLayout (null);
pic1 = new JLabel (new ImageIcon ("welcome.png"));
pic2 = new JLabel (new ImageIcon ("name.png"));
pic3 = new JLabel (new ImageIcon ("speed.png"));
pic4 = new JLabel (new ImageIcon ("backgnd.jpg"));
username = new JTextField ();
slow = new JButton("Slow");
// slow.setActionCommand("slowspeed");
slow.addActionListener (this);
medium = new JButton("Medium");
// medium.setActionCommand("mediumspeed");
medium.addActionListener (this);
fast = new JButton("Fast");
// fast.setActionCommand("fastspeed");
fast.addActionListener (this);
pic1.setBounds (30,50, 525, 173);//welcome
pic2.setBounds (100,230,212,73);//name
pic3.setBounds (80,350,428,84);//speed
username.setBounds(310,255,150,30);
slow.setBounds (100,450,100,100);
medium.setBounds (250,450,100,100);
fast.setBounds (400,450,100,100);
//background bound goes in the end
pic4.setBounds (0,0, 600,900);
frame.add (pic1);
frame.add (pic2);
frame.add (pic3);
frame.add (username);
frame.add (slow);
frame.add (medium);
frame.add (fast);
frame.add (pic4);
setSize(600, 900);
setVisible (true);
setDefaultCloseOperation (EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent evt){
String name = username.getText();
if (evt.getSource () == slow)
{
xspeed = 1;
}
else if(evt.getSource () == medium)
{
xspeed = 5;
}
else
{
xspeed = 10;
}
}
public static void main(String[] args) {
new MainMenuofgame ();
}
}
The behavior that you describe is not in fact the "transfer values of an int and string from one program to another in Java", but rather much more simply the transfer of data from one object to another, here the objects are represented by GUI components. Don't create two separate programs, but rather create separate objects that interact in a meaningful way. That is the essence of OOPs with Java. The simplest solution is to have the main application display the sub-application's GUI within a modal dialog such as a modal JDialog, and then once the dialog has been dealt with (i.e., is no longer visible) then the main program/object queries the dialog for the state of its components -- the data that was entered.
Also you are painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.
For example:
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class MenuDemoMainPanel extends JPanel {
private MenuPanel menuPanel = new MenuPanel();
private JDialog menuDialog = null;
private String name;
private Speed speed;
private JTextField nameField = new JTextField(10);
private JTextField speedField = new JTextField(10);
public MenuDemoMainPanel() {
// these fields are for display only and should not allow user
// interaction
nameField.setFocusable(false);
speedField.setFocusable(false);
// not kosher to set this directly, per kleopatra, but oh well
setPreferredSize(new Dimension(600, 400));
// simple demo GUI -- add components
add(new JLabel("Name:"));
add(nameField);
add(new JLabel("Speed:"));
add(speedField);
add(new JButton(new GetNameAndSpeedAction("Get Name And Speed")));
}
// action for JButton that displays the menuDialog JDialog
private class GetNameAndSpeedAction extends AbstractAction {
public GetNameAndSpeedAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (menuDialog == null) {
// if the menu dialog has not been created yet -- create it
Window win = SwingUtilities.getWindowAncestor(MenuDemoMainPanel.this);
menuDialog = new JDialog(win, "Menu", ModalityType.APPLICATION_MODAL);
menuDialog.add(menuPanel);
menuDialog.pack();
menuDialog.setLocationRelativeTo(win);
}
// display the menu JDialog
menuDialog.setVisible(true);
// this code is called only when the dialog is no longer visible
// query the dialog for the state it holds
name = menuPanel.getNameText();
speed = menuPanel.getSpeed();
// and display the state in the main GUI
if (name != null && speed != null) {
nameField.setText(name);
speedField.setText(speed.getText());
}
}
}
private static void createAndShowGui() {
// create the main GUI JPanel
MenuDemoMainPanel mainPanel = new MenuDemoMainPanel();
// then create an application GUI
JFrame frame = new JFrame("Menu Demo -- Main GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel); // place the main panel into the GUI
// and pack and display it:
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
// JPanel to hold menu dialog components
#SuppressWarnings("serial")
class MenuPanel extends JPanel {
private JComboBox<Speed> speedCombo = new JComboBox<>(Speed.values());
private JTextField nameField = new JTextField(10);
public MenuPanel() {
speedCombo.setSelectedIndex(-1);
add(new JLabel("Name:"));
add(nameField);
add(new JLabel("Speed:"));
add(speedCombo);
add(new JButton(new SubmitAction("Submit")));
}
// allow outside classes to query the nameField JTextField's state
public String getNameText() {
return nameField.getText();
}
// allow outside classes to query the speedCombo JComboBox's state
public Speed getSpeed() {
return (Speed) speedCombo.getSelectedItem();
}
// Action for JButton that submits the dialog to the main GUI
private class SubmitAction extends AbstractAction {
public SubmitAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// if the data is not all entered or selected
if (nameField.getText().trim().isEmpty() || speedCombo.getSelectedIndex() == -1) {
Component comp = MenuPanel.this;
String msg = "You must enter your name and select a speed";
String title = "Invalid Data";
int msgType = JOptionPane.ERROR_MESSAGE;
// warn the user and leave this dialog still visible
JOptionPane.showMessageDialog(comp, msg, title, msgType);
} else {
// otherwise dispose of this dialog and thereby pass control
// back to the main application / GUI
Window win = SwingUtilities.getWindowAncestor(MenuPanel.this);
win.dispose();
}
}
}
}
// an enum to encapsulate possible game speeds
enum Speed {
SLOW("Slow"), MEDIUM("Medium"), FAST("Fast");
private String text;
private Speed(String text) {
this.text = text;
}
public String getText() {
return text;
}
#Override
public String toString() {
return getText();
}
}
There are one of two ways that come to mind on how to transfer information from one program to another...
Client-Server applications
This requires you to have a third application running accepting information from each of the other two application (clients) through a socket. For further information Google "Client-Server applications in Java"
Have a text file passing information
To do this you should have a text file that one application stores information in and the other application just simply reads it... This is an easier solution but is less of a learning experience. Here is example code.
Application 1:
private void storeMessage(String msg){
File centralFile = new File("path to your file");
BufferedWriter writer = new BufferedWriter(new FileWriter(centralFile));
writer.write(msg);
writer.close();
}
Application 2:
private String getMessage(){
File centralFile = new File("path to your file");
String msg = "";
BufferedReader reader = new BufferedReader(new FileReader(centralFile));
while (reader.hasNextLine()){
msg += reader.nextLine();
}
reader.close();
return msg;
}
Hope this helps
Um... really all I needed to do was call upon my variable that I wanted to store my data in and then well... store it. This is done in the If statement at the bottom. Thanks everyone for helping but honestly most of your answers rised more questions than answered mine and just confused me but I figured it out so thanks anyways :)
public class MainMenuofgame extends JFrame implements ActionListener{
JButton slow, medium, fast;
JLabel pic1, pic2, pic3, pic4;
JTextField username;
Container frame;
static String name;
static int xspeed = 0;
public MainMenuofgame() {
super ("Main Menu of Rocket Launch");
frame = getContentPane ();
frame.setLayout (null);
pic1 = new JLabel (new ImageIcon ("welcome.png"));
pic2 = new JLabel (new ImageIcon ("name.png"));
pic3 = new JLabel (new ImageIcon ("speed.png"));
pic4 = new JLabel (new ImageIcon ("backgnd.jpg"));
username = new JTextField ();
slow = new JButton("Slow");
// slow.setActionCommand("slowspeed");
slow.addActionListener (this);
medium = new JButton("Medium");
// medium.setActionCommand("mediumspeed");
medium.addActionListener (this);
fast = new JButton("Fast");
// fast.setActionCommand("fastspeed");
fast.addActionListener (this);
pic1.setBounds (30,50, 525, 173);//welcome
pic2.setBounds (100,230,212,73);//name
pic3.setBounds (80,350,428,84);//speed
username.setBounds(310,255,150,30);
slow.setBounds (100,450,100,100);
medium.setBounds (250,450,100,100);
fast.setBounds (400,450,100,100);
//background bound goes in the end
pic4.setBounds (0,0, 600,900);
frame.add (pic1);
frame.add (pic2);
frame.add (pic3);
frame.add (username);
frame.add (slow);
frame.add (medium);
frame.add (fast);
frame.add (pic4);
setSize(600, 900);
setVisible (true);
setDefaultCloseOperation (EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent evt){
String name = username.getText();
Rocketlaunch.name = name;
if (evt.getSource () == slow)
{
Rocketlaunch.moveSpeed = 1;
Rocketlaunch.speed = "Slow";
setVisible (false);
}
else if(evt.getSource () == medium)
{
Rocketlaunch.moveSpeed = 5;
Rocketlaunch.speed = "Medium";
setVisible (false);
}
else
{
Rocketlaunch.moveSpeed = 10;
Rocketlaunch.speed = "Fast";
setVisible (false);
}
new Rocketlaunch();
}
public static void main(String[] args) {
new MainMenuofgame ();
}
}

Cant add gui elements from other methods and if statmens

Hey all I have one question I am new to GUI stuff so I need some help when I want to add an element to a window using some other method or if statement I don't get error but it doesn't show up hears a code I marked problem I am working in java by the way this is not whole program but only this is a problem
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame{
private JTextField usernameTF;
private JPasswordField passwordField;
private String username,password;
private JRadioButton A,B,C,D,F;
//private JComboBox box;
private JLabel logo,errorPic,promt;
private JButton logIn;
private boolean value;
private Apples function= new Apples();
public Gui(){
super ("Awsome Progrma");
setLayout(new FlowLayout());
Icon errorIcon = new ImageIcon(getClass().getResource("wrong.png"));
errorPic = new JLabel(errorIcon);
usernameTF = new JTextField(10);
usernameTF.setToolTipText("Enter your user name hear");
add(usernameTF);
passwordField = new JPasswordField(10);
passwordField.setToolTipText("Enter your password hear");
add(passwordField);
logIn = new JButton("Log IN");
add(logIn);
usernameTF.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
username = event.getActionCommand();
password = passwordField.getText();
value = function.chack(username,password);
if (value == true){add(errorPic);} // this is a problem JLabel dosn't show up in my window
}
}
);
passwordField.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
username = usernameTF.getText();;
password = event.getActionCommand();
value = function.chack(username,password);
if (value == true){add(errorPic);} // this is a problem JLabel dosn't show up in my window
}
}
);
logIn.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
username = usernameTF.getText();
password = passwordField.getText();
value = function.chack(username,password);
if (value == true){add(errorPic);} // this is a problem JLabel dosn't show up in my window
}
}
);
}
}
The only GUI element that won't show up is the Jlabel errorPic. This is because the container needs to be validated after the component has been added. You need to call:
revalidate();
repaint();
after adding the JLabel. A better approach would be to add a JLabel with no image when adding components to the JFrame and later simply call JLabel.setIcon to update the label.
Some side notes:
Don't extend JFrame. Instead create an instance of the window component directly.
JPassword.getText is deprecated. Safer to use JPassword.getPassword instead.
Consider using Initial Threads at application startup.

Java: JTextField creates infinite loop when method called more than once from JMenuItem

I'm writing a Text Analysis Program for college that requires you to add a word to a dictionary as well as other actions. I'm having a problem with this section of the code as I need an error message to come up if the user hits ok while the JTextField is empty. I can get it going but have created an infinite loop somehow with the error message. Please help, I've looked all over the internet but can't find an answer for such a simple bug. Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.lang.Character;
public class TAPtest implements ActionListener
{
private JFrame tap = new JFrame("Text Analysis");
private JMenuBar tapMenu = new JMenuBar();
private JMenu dictionary = new JMenu("Dictionary");
private JMenuItem addWord = new JMenuItem("Add Word");
private JFrame frameAdd = new JFrame("Add Word");
private JLabel add = new JLabel("Enter word to add:");
private JButton okNewWord = new JButton("Ok");
private JButton cancelNewWord = new JButton("Cancel");
private JTextField inputNewWord = new JTextField(28);
private JPanel westAdd = new JPanel();
private JPanel eastAdd = new JPanel();
private JPanel southAdd = new JPanel();
private Vector <String> dictionaryVector = new Vector<String>();
public TAPtest() //Constructor. Contains TAP GUI.
{
tap.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tap.setSize(350, 100);
tap.setLocation(700, 500);
tap.setResizable(false);
tap.setJMenuBar(tapMenu);
tapMenu.add(dictionary);
dictionary.add(addWord);
addWord.addActionListener(this);
tap.setVisible(true);
}
public void actionPerformed(ActionEvent event) //All actions performed.
{
if (event.getActionCommand() == "Add Word") addNewDicWordGUI();
if (event.getSource() == okNewWord) addNewDicWord();
if (event.getSource() == cancelNewWord) frameAdd.dispose();
}
public void addNewDicWordGUI()
{
frameAdd.setSize(350, 150);
frameAdd.setLocation(700, 500);
frameAdd.setResizable(false);
okNewWord.setSize(5,20);
cancelNewWord.setSize(5,20);
westAdd.add(add);
eastAdd.setLayout(new GridLayout(2,1));
eastAdd.add(okNewWord);
eastAdd.add(cancelNewWord);
southAdd.add(inputNewWord);
frameAdd.add(westAdd, BorderLayout.WEST);
frameAdd.add(eastAdd, BorderLayout.EAST);
frameAdd.add(southAdd, BorderLayout.SOUTH);
okNewWord.addActionListener(this);
cancelNewWord.addActionListener(this);
inputNewWord.addActionListener(this);
frameAdd.setVisible(true);
}
public void addNewDicWord()
{
String inputNew = inputNewWord.getText(); //Get JTextField value.
inputNew = inputNew.toLowerCase();
frameAdd.dispose();
if (inputNew.equals(""))
JOptionPane.showMessageDialog(null, "You must enter a word", "Notice", 1);
else {
boolean addItemFound = dictionaryVector.contains(inputNew); //True if contains.
if(addItemFound) //If true.
JOptionPane.showMessageDialog(null, inputNew + " already exists in the dictionary.", "Word Already Exists", 1);
else { //If not true.
dictionaryVector.addElement(inputNew); //Add the word to the dictionary Vector.
Collections.sort(dictionaryVector); //Sort the vector in ascending order.
JOptionPane.showMessageDialog(null, inputNew + " was added to the dictionary.", "Word Added", 1);
}
inputNewWord.setText(null);
}
}
public static void main(String [] args)
{
TAPtest program = new TAPtest();
}
}
private Vector <String> dictionaryVector = new Vector<String>();
inputNewWord.setText(null);
JOptionPane.showMessageDialog(null, "You must enter a word", "Notice", 1);
public void actionPerformed(ActionEvent event) //All actions performed.
{
...
}
should better be
private SortedSet<String> dictionaryVector = new TreeSet<String>();
inputNewWord.setText("");
JOptionPane.showMessageDialog(null, "You must enter a word", "Notice",
JOptionPane.ERROR_MESSAGE);
public void actionPerformed(ActionEvent event) //All actions performed.
{
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
...
}
}
}
The last invokeLater might have caused the troubles. The event handling actionPerformed is done on the event thread, and showing a message should be done after
the event is handled (as any longer task for the GUI to remain responsive).
Declare frameAdd like this -
private JFrame frameAdd = null;
The addNewDicWordGUI() method should be like this -
public void addNewDicWordGUI()
{
if(frameAdd==null)
{
//Initialized only for the first time
frameAdd = new JFrame("Add Word");
frameAdd.setSize(350, 150);
frameAdd.setLocation(100, 200);
frameAdd.setResizable(false);
okNewWord.setSize(5,20);
cancelNewWord.setSize(5,20);
westAdd.add(add);
eastAdd.setLayout(new GridLayout(2,1));
eastAdd.add(okNewWord);
eastAdd.add(cancelNewWord);
southAdd.add(inputNewWord);
frameAdd.add(westAdd, BorderLayout.WEST);
frameAdd.add(eastAdd, BorderLayout.EAST);
frameAdd.add(southAdd, BorderLayout.SOUTH);
okNewWord.addActionListener(this);
cancelNewWord.addActionListener(this);
inputNewWord.addActionListener(this);
}
frameAdd.setVisible(true);
}
Make the above changes and it will work fine.

Categories