how to array,ascending,descending,bubble,inputarea,outputarea in JFrame - java

I don't know where to start I don't want to be spoon fed either. Help me with tons of problem.
My goal in this program is to get input from the user by letting them type in the input area and there area three button (ascending, array, bubble sort) must them to pick and then the output must show in outputarea.
my code only ends up in getting the input of the user in input area.
My problems are:
Can I tell the user to input like this (1, 2, 3, 5, 6) with comma and neglected the comma then convert it to array to sort it.
After they click the either three buttons how can i output it in the output area.
Is my code in the right track or not? :D
Sorry for my bad english.
i dont want to be spoonfeed just help me guys :D
more power stackoverflow
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JavaGui205 extends JPanel
{
final JTextField inputarea,outputarea;
final JButton asc,desc,bubble;
int getsd;
JavaGui205()
{
//initialize textfield and buttons
inputarea=new JTextField("Inputarea",20);
outputarea=new JTextField("Outputarea",20);
asc=new JButton("Ascending");
desc=new JButton("Descending");
bubble=new JButton("BubbleSort");
//adding function on fields
inputarea.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==inputarea)
{
String sd=e.getActionCommand();
getsd=Integer.parseInt(sd);
}
}
});
//ascending function
asc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
}
});
//adding to frame
add(inputarea);
add(asc);
add(desc);
add(bubble);
add(outputarea);
}
public static void main(String[]args)
{
JFrame frame = new JFrame("WTF");
frame.add(new JavaGui205());
frame.setVisible(true);
frame.setSize(300,150);
}
}
I try some fixixation.I add these code tnx to mr Wyatt Lowery.but i have some problems how can i convert those string array into integer array then contain its values to use to three buttons then the product of those will display in the output area.Im sorry guys im slowpoke T_T :D i try my best to research but nothing happens
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==inputarea)
{
String sd=inputarea.getText();
String[] inputArray=sd.split(",\\s*");
}
}

Your problems in order:
Get the string from the text field inputarea.getText() and store it into a variable(E.g. inputText = inputarea.getText()). You can use the method split() to separate the values and put it into an array(E.g. String[] inputArray = inputText.split(", "))
When the button is clicked, set the outputarea text equal to the array
(E.g. outputarea.setText(inputArray.toString()))
Try working on your coding conventions :-)

Related

get value of changed JTextField on Java Swing

Hey guyz i'm working on a GPA calculator for my java assignment, and the gui i have created is 100% based on Events i.e. no buttons for the user to submit his data. my question is how do i know if a textfield value has changed and if it did how do i get the original value befor the change.
another question how can i store each component in an arrayList do the user can create as many rows as they like Thanks
this is the snapshot of mu GUIenter image description here
BTW feel free any other suggestion
You can use keylistener
JTextField usernameTextField= newJTextField();
usernameTextField.addKeyListener(new () { public void keyReleased(Key KeyAdapter Event e) { JTextField textField = (JTextField) e.getSource(); String text = textField.getText(); textField.setText(text.toUpperCase()); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { } });

How do I change the size and location of JOptionPane.showOptionDialog()

Okay, so here's the deal. Currently, I am using this:
String[] choices = {"Rock", "Paper", "Scissors"};
String input = (String) JOptionPane.showInputDialog(null, "Please, make your choice", "Rock Paper Scissors!", JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);
Which is what I need. It creates a drop down menu that allows the user to select Rock, Paper, or Scissors and then outputs it into a String. The problem is, the window that it pops in is REALLY small, and is in the center of the screen. I want to re-size it to be 970 pixels by 300 pixels, and to appear at the location of 950 pixels and 0 pixels.
Now, before you say it, I HAVE tried to use JFrames for this, because I know how to get it the size and at the location I want it. However, I can't get the ActionListener to behave in the way that I want it to.
public static void main(String args[]) throws IOException
{
JFrame hi = new JFrame("Hi");
hi.setSize(970, 300);
hi.setLocation(950, 0);
System.out.println("Hi");
Picture Hi = new Picture("c:/The Game/Cool.png");
Hi.display();
JButton B = new JButton("Hey There!");
hi.add(B);
int c = Output(hi);
}
public int Output(JFrame b)
{
int j = 0;
j = //CODE NEEDED HERE
return j;
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
So, the problem with this is that I need the JFrame to pop up in then "CODE NEEDED HERE" section, and then, upon clicking the button, to return a certain value, and then to close out of the JFrame. However, the JFrame doesn't wait for the Output() function, and it immediately returns j, which is equal to 0. Instead, it just does whatever is in the actionPerformed function.
So, I am asking for a solution to either one of these problems. How to either re-size the JOptionPane.showInputDialog() or to get the JFrame to return an int value upon clicking a button.
Sorry if this is really poorly explained, I'm really new to JOptionPane and JFrames.
JOptionPane is quite configurable, it's also nicely self contained, taking a lot of the repetitive, boil plate code and hiding it away in an easy to use package.
But that doesn't mean you have to use it that way, you can simply create an instance of JOptionPane, which is just an ancestor of JComponent and add it to what ever you want.
The difficulty is plumbing all the functionality back together, so you can respond to the buttons, for example.
Just beware, your example places the dialog under my task bar (yes, mine is at the top of the screen), so I can tell you, as a user, that will annoy me!
So, this example basically wraps up all the boiler plate code into a simple class/method, which makes it easy to repeatedly prompt the user the same question, over and over again...
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.OK_CANCEL_OPTION;
import static javax.swing.JOptionPane.UNINITIALIZED_VALUE;
import static javax.swing.JOptionPane.VALUE_PROPERTY;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
String pick = Picker.pick();
System.out.println("You picked " + pick);
System.exit(0);
}
public static class Picker {
public static String pick() {
String[] choices = {"Rock", "Paper", "Scissors"};
JOptionPane pane = new JOptionPane("Please, make your choice", JOptionPane.QUESTION_MESSAGE,
OK_CANCEL_OPTION, null, null, null);
pane.setWantsInput(true);
pane.setSelectionValues(choices);
pane.setInitialSelectionValue(choices[0]);
JDialog dialog = new JDialog();
dialog.setModal(true);
PropertyChangeListener listener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
// Let the defaultCloseOperation handle the closing
// if the user closed the window without selecting a button
// (newValue = null in that case). Otherwise, close the dialog.
if (dialog.isVisible()
&& (event.getPropertyName().equals(VALUE_PROPERTY))
&& event.getNewValue() != null
&& event.getNewValue() != JOptionPane.UNINITIALIZED_VALUE) {
dialog.setVisible(false);
}
}
};
WindowAdapter adapter = new WindowAdapter() {
private boolean gotFocus = false;
public void windowClosing(WindowEvent we) {
pane.setValue(null);
}
public void windowClosed(WindowEvent e) {
dialog.removePropertyChangeListener(listener);
dialog.getContentPane().removeAll();
}
public void windowGainedFocus(WindowEvent we) {
// Once window gets focus, set initial focus
if (!gotFocus) {
pane.selectInitialValue();
gotFocus = true;
}
}
};
dialog.addWindowListener(adapter);
dialog.addWindowFocusListener(adapter);
dialog.addComponentListener(new ComponentAdapter() {
public void componentShown(ComponentEvent ce) {
// reset value to ensure closing works properly
pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
}
});
pane.addPropertyChangeListener(listener);
dialog.add(pane);
//dialog.pack();
//dialog.setLocationRelativeTo(null);
dialog.setSize(970, 300); // This is bad idea, use an EmptyBorder instead
dialog.setLocation(950, 0);
dialog.setVisible(true);
String pick = null;
Object value = pane.getInputValue();
if (value != UNINITIALIZED_VALUE) {
pick = value.toString();
}
return pick;
}
}
}
The reason you're having problems with JFrame is because it's not designed to block the code execution when displayed, a JDialog can, see How to Make Dialogs for more details

JComboBox changinging other JComboBoxes (multiple times) error

need some help with ComboBoxes in Java. Looked through similar questions, found one slightly related, but not what im dealing with.
I need to load certain arrays into combo boxes depending on the items selected in the precious combo box:
think getting some procedure done at a medical center: Choose a procedure->get a list of doctors who do it, choose a doctor->get a list of available hours etc.
A single choice is working fine(whether it's "procedure->list of doctors", or "list of doctors->their working hours"), but doing more than a single one of those changes doesn't work.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
public class GUIbandymas extends JFrame {
String[] start={"Choose","Choice1", "Choice2"};
String[] Option1={"Choose","A1"};
String[] Option2={"Choose","A2","A3"};
String[] Option3={"Choose","a","b","c","d"};
String[] Option4={"Choose","1","2","3","4"};
String[] Option5={"Choose","I","II","III","IV"};
String[] pradinis={"Pasirinkite Laika"};
String[] p1={"Pasirinkite Gydytoja"};
static double kainaR;
static double kainaK;
JComboBox<String> G=new JComboBox<String>(p1);
JComboBox<String> proc;
JComboBox<String> laikas=new JComboBox<String>(pradinis);
JComboBox<String> minutes;
JButton button = new JButton ("Registuotis");
JLabel label = new JLabel("Moketi uz vizita");
JLabel suma = new JLabel();
public GUIbandymas() throws Exception {
setValueProc(start);
frame();
}
public void frame()
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(500,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(proc);
panel.add(G);
panel.add(laikas);
panel.add(button);
button.setEnabled(false);
//panel.add(minutes);
frame.add(panel);
panel.add(label);
panel.add(suma);
proc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
if(proc.getSelectedItem().toString().equals("Choice1"))
{
setGyd(Option1);
}
if(proc.getSelectedItem().toString().equals("Choice2"))
{
setGyd(Option2);
}
}
});
G.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent a) {
if(G.getSelectedItem().toString().equals("A1"))
{
setLaikas(Option3);
}
if(G.getSelectedItem().toString().equals("A2"))
{
setLaikas(Option4);
}
if(G.getSelectedItem().toString().equals("A3"))
{
setLaikas(Option5);
}
}
});//JComboBox
}
public void setGyd(String[] s)
{
G.removeAllItems();
for(int i=0; i<s.length; i++)
{
G.addItem(s[i]);
}
}
public void setValueProc(String[] sarasas)
{
proc=new JComboBox<String>(sarasas);
}
public void setLaikas(String[] sarasas)
{
laikas.removeAllItems();
for(int i=0; i<sarasas.length; i++)
{
laikas.addItem(sarasas[i]);
}
}
}
Im in a dire need of any suggestions and possible fixes, im inclined to think that it has something to do with action listeners, since methods do work, but im at a loss since i cant determine what is it.
EDITED: the actual code should work, seems like there is no unneeded things from other files left.
NOTE: this is work with GUI, just launch it in you main() :)
While I don't really like the if-else approach you're using, it should work just fine. I agree with rrirower's suggestion that you should look at using a data model instead. Especially if you get a lot of choices, since the code turns messy quite fast.
The problem with your code is that you run into NullPointerException when rebuilding the combobox items. The reason for this is that G.actionPerformed() is called when you remove/add items. After you have removed all items (before you start adding new ones), G.getSelectedItem() will return null.
If you code a little bit more defensively, then it works as expected:
proc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object selectedItem = proc.getSelectedItem();
if ("Choice1".equals(selectedItem)) {
setGyd(Option1);
}
if ("Choice2".equals(selectedItem)) {
setGyd(Option2);
}
}
});
G.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
Object selectedItem = G.getSelectedItem();
if ("A1".equals(selectedItem)) {
setLaikas(Option3);
}
if ("A2".equals(selectedItem)) {
setLaikas(Option4);
}
if ("A3".equals(selectedItem)) {
setLaikas(Option5);
}
}
});//JComboBox
Instead of checking for null's, I just flipped the equals and skipped the unnecessary toString() (they are already strings, that's what you put in there).
Another thing, a pet peeve of mine, please follow the normal java code convention for all your class, field and method names. You're almost there, but Option1 etc. should start with lowercase. G should probably have a more descriptive name, as well as start with lowercase.
Finally, I didn't understand why you both create a JFrame in the constructor and extend JFrame in your class. You should choose one or the other.
You don't appear to be using a data model for the combo box. The data model controls the internal list of items. Have a look at this for more info.

Trying to create a simple applet but it won't run through the whole program

I'm creating an applet and all that happens is it opens displays "How many genres are there?" and then a textField appears. i enter a number and hit enter but nothing ever happens! (i dont get any errors but nothing happens)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class appletPracticw extends Applet implements ActionListener {
TextField numG;
TextField g ;
TextField numS;
TextField sog;
private int number;
private int numberOfSongs;
String gener;
String songName;
public void go(){
numG= new TextField(5);
numS= new TextField(5);
g= new TextField(5);
sog= new TextField(5);
numG.addActionListener(this);
g.addActionListener(this);
sog.addActionListener(this);
numS.addActionListener(this);
Tracker t=new Tracker();
add(new Label("How many genres are there? ")); add(numG);
for(int i=0;i<number;i++){
catogories c=new catogories();
add(new Label("Name of genere: ")); add(g);
t.addCatogory(c,gener);
}
for(int x=0;x<number;x++){
add(new Label("How many songs are there in "+t.getCatogories().get(x).getGenere())); add(numS);
for(int i=0;i<numberOfSongs;i++){
Songs s=new Songs();
add(new Label("The name of song "+(i+1)+" is")); add(sog);
t.getCatogories().get(x).addSong(s, songName);
}
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==numG){
String num=numG.getText();
number=Integer.parseInt(num);
}
if(e.getSource()==numS){
String num=numS.getText();
numberOfSongs=Integer.parseInt(num);
}
if(e.getSource()==g){
gener=g.getText();
}
if(e.getSource()==sog){
songName=sog.getText();
}
}
public void init() {
go();
}
public appletPracticw() {
}
}
The field number is initialized with the value 0.
You build the applet, adding labels and text fields. It looks like you are assuming that the program waits for a user input at this line:
add(new Label("How many genres are there? ")); add(numG);
In reality it is just creating the user interface and doesn't wait for inputs.
So the two for loops are executed, but as number is still 0, the loops are never entered.
What you should do instead is perform the actual action (in your case this is changing the GUI by adding new labels and fields) in the actionPerformed method, so that category labels and input fields are created after the user has entered the number of genres. The same must be done for the second loop, too.

Display output from a method on a JPanel in Java

I have a GUI the gets an input from a text area and on the click of button produces a report. The report is supposed to be displayed below the input area. On the click of the button, the input data are passed to a a void method called Calculate(), and right now the correct results are displayed on the console by System.out.printf(). How can I redirect this output to the report area?
public class Progress extends JFrame
{
JTextArea input;
JButton calculate;
JPanel report;
public void Notify()
{
calculate = new JButton("Calculate");
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Calculate();
}
});
}
}
...
public void Calculate()
{
GenerateReport m = new GenerateReport();
m.Parsecsv(input.getText());
}
So, as a newbie to Java, I wanted to know how I can redirect the output of my Calculate() method to the report panel?
Well you could modify your Calculate to return a string containing the information you want to print into the text area. I assume you know how to make simple methods that aren't void and return a data type:
public String Calculate() {
<something to get the text needed is done here>
return <text from report>;
}
Then you could make a "JOptionPane.showMessageDialog( Calculate() )" to show the report, or you could as mentioned create a JLabel to print the report within the frame your working with.
Something like:
JLabel lab1 = new JLabel(null, Calculate() );
If I understand you right?
I think what you're trying to ask is, "What is a JLabel?". You can use a JLabel to output your text from your calculate method.
Or you can return a String from your calculate method and somehow display it otherwise.

Categories