I'm trying to simply create four jtextfields and a jbutton. Once the button is pushed, i want the text inputted into the jtextfields to be passed as parameters (p, var, s, f) to another window to which displays a mathematical function using the parameters given.
I don't want this second window to show up and display a mathematical function until the initial button was pushed.
How can I do this? I'm sorry if this is a newbie question but I'm learning..
So far, I have graphing part done, and so all I need to do now is create the first window with the textboxes and buttons which link to the graphing window.
Here is the beginning of the code that I think is worth showing so you know which variables I'm talking about:
public class Cartesian {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CartesianFrame frame = new CartesianFrame();
frame.showUI();
}
});
}
}
class CartesianFrame extends JFrame {
CartesianPanel panel;
public CartesianFrame() {
panel = new CartesianPanel();
add(panel);
}
public void showUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Polynomial Grapher");
setSize(700, 700);
setVisible(true);
}
}
class CartesianPanel extends JPanel {
//These are the variables I want to be assigned to textfields(I'm assuming using "gettext" from another window.
String p="something from textbox one";//Variable 1
String var="something from textbox two";//Variable 2
double s=-2;//ANY double value from textbox 3
double f=2;//ANY double value from textbox 4
...
...
...
The rest of the code used after this is just a paint component, etc. which is used to display the cartesian plane and the mathematical function.
I've looked on the web for some other examples, but they haven't applied to what I'm doing.. I'm interested in any feedback! Thank you!
Don't create a second JFrame. If you absolutely must show a second window, show a dialog such as a JDialog or JOptionPane. As to how to do this, simply create a JPanel that displays the information that you'd like to show the user, perhaps in a JLabel, and then show it in a JOptionPane using its showMessage(...) method. It's pretty easy, actually.
If this doesn't help, then you'd better tell us more about exactly where you're stuck.
Related
This question already has answers here:
Need to read input of two JTextfields after a button is clicked
(2 answers)
Closed 8 years ago.
So I made a fully functional credit card validator which uses Luhn's Algorithm and all that jazz to validate the card type and number. It currently only uses Scanner and the console to print out stuff, but I wanted to take my program to the next level.
I wanted to make an application with Java graphics that can take in a credit card number entered into my applet/japplet/whatever you suggest and can essentially do the same process as the previously mentioned program, but I want to give it the aesthetic appeal of graphics.
So I'm honestly a little overwhelmed with the graphics in Java (not sure if that's weird), but here's what I want advice on.
How should I approach my graphics project? Should I use JApplet, Applet, JFrame, or something else?
I want to make a text field that the user enters his or her credit card into, what is the method of doing that? I looked up JTextFields but I'm at a loss on how to use it. I looked at the API but it doesn't do a very good job of explaining things in my opinion.
My main problem is the textfield, can someone give me an example of a textfield that can take in data that the user types? Sort of like Scanner in the console but in my graphics application.
Sorry for my word wall, you guys have been very helpful to me in the past :)
Tips, tricks, and anything else you think would help me out would be greatly appreciated.
Here is an example of a text field using swing:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JFrame { // The JFrame is the window
JTextField textField; // The textField
public GUI() {
textField = new JTextField(10); // The user can enter 10 characters into the textField
textField.addActionListener(new ActionListener() { // This will listen for actions to be performed on the textField (enter button pressed)
#Override
public void actionPerformed(ActionEvent e) { // Called when the enter button is pressed
// TODO Auto-generated method stub
String inputText = textField.getText(); // Get the textField's text
textField.setText(""); // Clear the textField
System.out.println(inputText); // Print out the text (or you can do something else with it)
}
});
JPanel panel = new JPanel(); // Make a panel to be displayed
panel.add(textField); // Add the textField to the panel
this.add(panel); // Add the panel to the JFrame (we extend JFrame)
this.setVisible(true); // Visible
this.setSize(500, 500); // Size
this.setDefaultCloseOperation(EXIT_ON_CLOSE); // Exit when the "x" button is pressed
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
I am trying to make a simple GUI word dragging game and the way I structured the code is that I have a Driver class that sets up the main JFrame and a JPanel where the words are to be contained in and a JButton that prompts a Popup class to ask for a new word to add. and then creates a WordBox. My problem seems to arise from the fact that the Popup class is a sub-class (I think thats the correct term) and so it seems that there seems to be an extra Popup class as a layer between the Driver and the actual Popup with the WordBox. I know its confusing, but here is some of the code:
public class Popup extends JFrame implements ActionListener {
JLabel lblPrompt;
JTextField txtWord;
JButton btnOK;
BoxWord w;
static BoxWord word;
public Popup(){
//window formatting was here
btnOK.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
w = new BoxWord(txtWord.getText());
//word = new BoxWord("it works");
}
public static void main(String[] args) {
Popup p = new Popup();
//System.out.println(word.getWord());
}
and
public class BoxWord extends JButton {
private String s = "";
public BoxWord(String word){
this.s = word;
this.setText(word);
}
public String getWord(){
return s;
}
}
and the Driver:
public class Driver extends JFrame implements ActionListener{
JButton addWord;
JPanel panel;
int x, y;
public Driver(){
//Window formatting was here
addWord.addActionListener(this);
}
public static void main(String[] args) {
Driver d = new Driver();
}
#Override
public void actionPerformed(ActionEvent e){//make a new popup to ask for word
Popup p = new Popup();
BoxWord w = p.w;
System.out.println(w.getWord());
w.setLocation(100,100);
}
My error is (at least the begining of it. the whole thing is like 20 lines long):
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at worddrag.Driver.actionPerformed(Driver.java:42)
The line 42 is the
System.out.println(w.getWord());
I feel this is a very trivial and simple problem but I cannot figure out why I keep getting the error. I essentially need to be able to access the BoxWord in the Popup actionPerformed method from the Popup main method. any and all help is appreciated. My apologies for the wall of text
w is obviously null when you try to access it.
Your problem is that you're using a JFrame where a modal dialog or JOptionPane would work better. If you used the dialog, then your calling code would wait until the dialog is no longer visible, and at that time, w would likely no longer be null.
Edit
You ask:
and can you elaborate on why JFrame will not work? Just telling me that its my problem doesnt help very much -
What? I didn't just tell you that it was the problem -- I offered a solution -- use a modal JDialog. Again, a modal dialog will freeze code flow from the calling code when it is launched, and the calling code will remain frozen until the dialog is no longer visible.
Your problem is that your attempting to use the w variable before the dialog window has had a chance to do anything with it. A JFrame does not pause the calling code's program flow, and that is causing your problem.
Edit 2
So a JFrame doesn't actually execute the code until it is closed?
No, not true at all. Look where your w is given a valid reference -- in your JFrame's button's ActionListener. So w will not receive a valid reference until the ActionListener has been called, which only will happen when the button is pressed. Your code as written tries to use w immediately before the user has had any chance to push your pop-up's buttons. If you used a modal JDialog instead, and made sure that w was set prior to closing the dialog, your code could work.
But a JDialog will do so as it gets the input?
Nope. See above.
I am fairly new to Java programming and want to make a basic game that shows an image when clicked once, a different image when clicked twice and etc.
I know how to do all this but I don't know how to keep track of how any clicks and then do an actions based on how many clicks have been done (Hard to explain, my apologies...)
I ... want to make a basic game that shows an image when clicked once, a different image when clicked twice and etc. I know how to do all this but I don't know how to keep track of how any clicks
As per my comment, give the class with the ActionListener an int field, say called buttonCount, and increment it each time the button is pressed -- inside of the button ActionListener's actionPerformed method: buttonCount++
and then do an actions based on how many clicks have been done (Hard to explain, my apologies...)
In the ActionListener's actionPerformed method change the image displayed. How you change it all depends on how you show it, something that you've yet to show us, and so I can't give you any code.
One way to make it easy is to create an ArrayList of ImageIcons to hold your images (as ImageIcons of course), and then call get(buttonCount) on the ArrayList to get the appropriate ImageIcon and display it in a JLabel via its setIcon(...) method. Make sure that the buttonCount is less than the size of the ArrayList so as not to get an ArrayIndexOutOfBoundsException. One way to do this is to mod your buttonCount by the size of the ArrayList. This will allow you to cycle through your collection of images.
Again, you will want to read the Swing tutorials on how to use JButtons and then break down your big problem into small steps, trying to solve each step one at a time.
Again if you need greater detail and more specific help, then you must show what you've tried and explain in detail what problems you may be having with it. It is my sincere believe and philosophy that you learn most by by forcing your brain to do new and unfamiliar things, by mental effort and sweat. So have at it, you've nothing to lose.
You can count the the mouse clicks in this way. By using an if-else or switch case you can display the images.
public class ButtonStart extends Frame {
private int mouseclicked = 0;
TextField objTextField;
public static void main(String args[]) {
ButtonStart BS = new ButtonStart();
}
public ButtonStart() {
Frame objFrame;
Button objButton;
TextField objTextField;
objFrame = new Frame("Clicking Buttons");
objButton = new Button("Click me!");
objTextField = new TextField("0");
objFrame.addMouseListener(new MyMouseListener());
objFrame.add(objButton);
objFrame.add(objTextField);
objFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
int mouseclicked = me.getClickCount();
objTextField.setText("Mouse clicked this many times:"
+ mouseclicked);
}
}
}
I am designing an application in NetBeans, as illustrated in the screenshot below.
When the user clicks on a JButton on a JFrame, a JDialog pops-up asking the user to enter a numeric value using a numeric keypad. I would like the JDialog to dynamically add 2 JPanels. JPanel 1 will contain a textbox for input. JPanel 2 will contain a numeric keypad. I designed them this way so that I could reuse the numeric keypad whenever I need it. The problem I am facing is displaying dynamically these 2 JPanels on the JDialog that pops-up. JDialog pops-up empty. Please take a look at my code below. Thank you all, I appreciate your help
This is the sample code of JDialog:
public class MyDialog extends javax.swing.JDialog {
public MyDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {//Add JPanel 2 (Numeric Keypad) to JDialog
Container contentPane = getContentPane();
NumericKeypadPanel nkp = new NumericKeypadPanel();
nkp.setLayout(new java.awt.BorderLayout());
contentPane.removeAll();
contentPane.add(nkp);
contentPane.validate();
contentPane.repaint();
}
});
}
This is the sample code for JPanel 2 (Numeric Keypad):
public class NumericKeypadPanel extends javax.swing.JPanel {
/** Creates new form NumericKeypadPanel */
public NumericKeypadPanel() {
initComponents();//Draws 10 number buttons
}
}
basicall there are two ways
1) add a new JComponent by holding JDialog size (in pixels) on the screen, all JCompoenets
or part of them could be shrinked
2) resize JDialog by calling pack(), then JDialog will be resized
both my a.m. rulles works by using Standard LayoutManagers (excepting AbsoluteLayout)
What is in the initComponents() function of the NumericKeypadPanel? If it's not actually creating components, you're not going to see anything in the dialog. I added a single line to the NumericKeypadPanel's constructor to change the background color of this panel, and indeed, it shows up in the dialog as a green panel.
public NumericKeypadPanel() {
//initComponents();//Draws 10 number buttons
setBackground(Color.green);
}
I have a main jFrame with the help of which i press button and open new JFrames but the problem is that when i open other JFrame the previous ones still remains there where as what i want is that when i press next button then i move forward to the new JFrame (the previous one should not be there) and when i press previous button i move back to the previous JFrame.
I know there are functions of dispose,they do well like jframe1.dispose() but i dont get it how to hide the very first JFrame whose code in the main is written like this
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{
new GraphicalInterface().setVisible(true);
}
});
}
how do i set this as .setVisible(false) in the button code?
You need to retain a reference to the JFrame, so you can set it's visibility later.
private JFrame myFrame;
public void run() {
myFrame = new GUI();
myFrame.setVisible(true);
}
public void hide() {
myFrame.setVisible(false);
}
Note that a JFrame is a top-level container, you are only really supposed to have one per application. It may be better if instead of using multiple JFrames you use just one, and swap in various JPanels instead.
It would safe resources if you keep just one frame and set a new panel as content.
Your question was how to handle the reference to the frame? Please provide the code where the next frame is created.
You could assign your GUI (extends JFrame I suppose) to a variable and call .setVisible(false) on that object. Since your object from the code above is more or less anonymous, you won't have access on that.
You could also check this.