event "if" and click enough 2 buttons - java

i have two button is btn_turn1 and btn_turn2 , i want when user click Enough btn_turn1 and btn_turn2 after event "if" will printf to screen at txt_turn but it just printf "0", help me

First of all JButton in swing can not be selected. it is a button, it can be clicked, entered, pressed, etc.
it is hard to understand what you are asking for, but i assume you are trying to count clicks from 2 Jbuttons and have to display it in Jtextfield. most simple and easy approach is next.
public class Cit extends JPanel implements ActionListener {
JButton btn_dahn1;
JButton btn_dahn2;
JTextField textField;
static int step ;
public Cit(){
btn_dahn1 = new JButton("Button1");
btn_dahn1.addActionListener(this);
btn_dahn2 = new JButton("Button2");
btn_dahn2.addActionListener(this);
textField = new JTextField();
btn_dahn1.setPreferredSize(new Dimension(100,30));
btn_dahn1.setMaximumSize(new Dimension(100,30));
btn_dahn2.setPreferredSize(new Dimension(100,30));
btn_dahn2.setMaximumSize(new Dimension(100,30));
textField.setMaximumSize(new Dimension(100,30));
textField.setMaximumSize(new Dimension(100,30));
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setPreferredSize(new Dimension(300, 30));
add(btn_dahn1);
add(btn_dahn2);
add(textField);
}
you can add Cit class to frame or dialog or whatever you use, then click button1 and button2, jtextfield will display the steps.
if you are not familiar how to do that. look at next code part.
public static void main(String[] args) {
JFrame frame = new JFrame();
Cit cit = new Cit();
frame.getContentPane().add(cit);
frame.setVisible(true);
frame.pack();
}

Related

Set 3x3 grid layout with swing

Im trying to build a tic tac toe game with swing. Using grid layout its coming out to weird numbers of rows and columns and cant seem to get it to 3x3. What am I doing wrong? Should I just use a float layout and set positions?
import java.awt.*;
import javax.swing.*;
public class main {
public static void main(String[] args) {
JFrame frame = new JFrame("Tic Tac Toe");
JPanel panel = new JPanel();
frame.add(panel);
GridLayout grid = new GridLayout(3,3);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLayout(grid);
frame.setResizable(false);
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
JButton button4 = new JButton();
JButton button5 = new JButton();
JButton button6 = new JButton();
JButton button7 = new JButton();
JButton button8 = new JButton();
JButton button9 = new JButton();
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.add(button5);
frame.add(button6);
frame.add(button7);
frame.add(button8);
frame.add(button9);
}
}
Although you have already accepted #JustinCoding answer, I feel obliged to also answer since that answer doesn't really explain why your code did not produce your desired result.
Your problem is that you are adding an empty JPanel to the JFrame as well as your JButtons. Just remove that part of the code. Here is your corrected code. I commented the lines that need to be removed.
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
//import javax.swing.JPanel;
public class main {
public static void main(String[] args) {
JFrame frame = new JFrame("Tic Tac Toe");
// JPanel panel = new JPanel();
// frame.add(panel);
GridLayout grid = new GridLayout(3, 3);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLayout(grid);
frame.setResizable(false);
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
JButton button4 = new JButton();
JButton button5 = new JButton();
JButton button6 = new JButton();
JButton button7 = new JButton();
JButton button8 = new JButton();
JButton button9 = new JButton();
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.add(button4);
frame.add(button5);
frame.add(button6);
frame.add(button7);
frame.add(button8);
frame.add(button9);
}
}
This is how it looks when I run the code.
Explanation
Originally, in order to add components to a JFrame, you had to first call method getContentPane which returned a Container that you could add components to. JFrame is referred to as a top level container and its content pane is the container for all the components that you add to it. The default content pane is a JPanel whose layout manager is BorderLayout. Hence no need to add your components to a JPanel and add that JPanel to the JFrame. You can add components directly to the JFrame. Just be aware that when you are adding components directly to a JFrame, you are actually adding them to a JPanel with BorderLayout.
And since the content pane is a JPanel, you are free to also change its layout manager – as you have done in your code via this line:
frame.setLayout(grid);
Note that you only need to set one of the dimensions in the GridLayout constructor. Here is a quote from the javadoc of that constructor.
One, but not both, of rows and cols can be zero, which means that any number of objects can be placed in a row or in a column.
In other words, for your tic-tac-toe game, you need only set the columns to 3. That means that each row will contain no more than three columns so when you add nine buttons, GridLayout will ensure that they will be arranged in three rows of three columns each. Hence, for your tic-tac-toe board, you can use the following code.
GridLayout grid = new GridLayout(0, 3); // zero rows and three columns
First of all, Thanks to #Abra for pointing out that I had not added any explanation, because I was writing the answer in a bit hurry.
Follow these steps first:
Assign the layout to your panel like this: panel.setLayout(grid);
Then, add the panel to your frame like this: frame.add(panel);
Then, add all your widgets to the panel by replacing frame with panel where you're adding your Buttons.
And now, your JFrame bugged out a bit because you were also adding an empty JPanel to your Frame. I made you add the JPanel to the JFrame and assign the grid layout to the Panel just because I thought that a Tic-Tac-Toe game would include the showing of results of the game. So, you can simply use the remove() method to remove the JPanel and add the Results JPanel.

swing BoxLayout not working

I have read many subjects here but I can't make my window with the layout I want.
I simply want all my graphic object to be in a row style like in the first picture here : http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
I've tried GridLayout but it still make my first button giant and then, as I add textfields, it's getting smaller and smaller?!
Here is my code without all the imports:
public class TestScrollPane extends JFrame implements ActionListener{
Dimension dim = new Dimension(200 , 50);
JButton button;
JPanel panel = new JPanel();
JScrollPane scrollpane = new JScrollPane(panel);
public TestScrollPane(){
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.add(scrollpane);
//panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
this.setSize(300, 400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
button = new JButton("click me");
button.setPreferredSize(dim);
panel.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == button ){
JTextField txt = new JTextField(); // we add a new button
txt.setPreferredSize(dim);
panel.add(txt);
SwingUtilities.updateComponentTreeUI(this); // refresh jframe
}
}
public static void main(String[] args){
TestScrollPane test = new TestScrollPane();
}
}
I just want to have one button per row.
A BoxLayout will respect the minimum/maximum sizes of a component.
For some reason the maximum height of a text field is unlimited so the text field gets all the space available.
So you can do something like:
JTextField txt = new JTextField(10); // we add a new button
//txt.setPreferredSize(dim); // don't hardcode a preferrd size of a component.
txt.setMaximumSize(txt.getPreferredSize());
Also:
//SwingUtilities.updateComponentTreeUI(this); // refresh jframe
Don't use the above method. That is used for a LAF change.
Instead when you add/remove components from a visible GUI you should use:
panel.revalidate();
panel.repaint();

Java Button Layouts and Displays

My objective here is to display a message to the console, showing which button I have pressed (the buttons go from 1-6). This is the furthest I have gotten.
CODE:
public class excercise5_1 extends JFrame {
public excercise5_1() {
setLayout(new FlowLayout());
// Create two panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
// Add three buttons to each panel
panel1.add(new JButton(" Button 1 "));
panel1.add(new JButton(" Button 2 "));
panel1.add(new JButton(" Button 3 "));
panel2.add(new JButton(" Button 4 "));
panel2.add(new JButton(" Button 5 "));
panel2.add(new JButton(" Button 6 "));
// Add panels to frame
add(panel1);
add(panel2);
}
public static void main(String[] args) {
excercise5_1 frame = new excercise5_1();
frame.setTitle(" Exercise 12_1 ");
frame.setSize(600,75);
frame.setLocationRelativeTo(null); // center frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I just don't know what to do to make it display "Button 2" if I press it.
Don't create your JButton's inline -- in the add method parameter. So not panel1.add(new JButton(...)),
Instead create your JButton on its own line: but rather JButton myButton = new JButton(...); and then panel1.add(myButton);
Use a for loop to simplify things.
Add an ActionListener to your button via its addActioListener(...) method, and have the ActionListener print the ActionEvent's getActionCommand() String. The ActionEvent is the parameter passed into the actionPerformed(ActionEvent e) method.
Read the JButton tutorials as it's all spelled out for you there. It appears as if you've read nothing about JButtons yet.

My GUI window doesn't show anything

I'm trying to use a grid layout to make a GUI window. I add all my components and it compiles but when it runs it doesn't show anything. I'm trying to make a simple layout grouped and stacked like this.
{introduction message}
{time label
time input text}
{gravity label
gravity input text}
{answer label
answer text box}
{calculate button clear button}
Here is my code
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
setTitle("Falling Distance Calculator");
setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 5));
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setVisible(true);
}
public static void main(String[] args)
{
new TurnerRandyFallingGUI();
}
}
You've added nothing to the JFrame that your class above extends. You need to add your components to containers whose hierarchy eventually leads to the top level window, to the this if you will. In other words, you have no add(someComponent) or the functionally similar this.add(someComponent)method call in your code above.
Consider adding all of your JPanels to a single JPanel
Consider adding that JPanel to the JFrame instance that is your class by calling add(thatJPanel).
Even better would be to not extend JFrame and just to create one when needed, but that will likely be the subject of another discussion at another time.
Before setVisible (true) statement add following statements:
add (introP);
add (timeP);
add (gravityP);
add (answerP);
add (buttonsP);
There is nothing in your JFrame. That is the reason
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setLayout(new GridLayout(5, 1));
this.add(introP);
this.add(timeP);
this.add(gravityP);
this.add(answerP);
this.add(buttonsP);
setTitle("Falling Distance Calculator");
this.pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.validate();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TurnerRandyFallingGUI();
}
});
}
}
Consider the following
In GridLayout, the first parameter is Rows, Second is columns
Never set the size of JFrame manually. Use pack() method to decide
the size
Use SwingUtilities.InvokeLater() to run the GUI in another thread.

Problem with the layouts in making a JAVA GUI

Here is a screenshot of my JFrame. This will be the main window to my application.
So the problem is that all the buttons are inline with each other, whereas I want them to be one under the other i.e. Add Contact under Show Contacts.
So how can I do that?
Here is my code for the JFrame.
public class CRUDFrame extends JFrame {
public CRUDFrame(){
super("AppCRUD");
setLayout(new FlowLayout());
JButton button1, button2, button3, button4;
button1 = new JButton(" Show Contacts ");
button2 = new JButton(" Add Contact ");
button3 = new JButton(" Update Number in a Contact ");
button4 = new JButton(" Delete a Contact ");
add(button1);
add(button2);
add(button3);
add(button4);
}
}
`
There have been some good answers centered around 'use a layout'. This example espouses the same advice, but also introduces the concept of nesting one layout within another. E.G. the JPanel containing the JButtons has a GridLayout. That panel is placed in the NORTH of a panel that is then added to the WEST of the main 'gui' panel.
The other components are added in order to show how the column of buttons might go together with other components in the main user interface.
Contact.java
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class Contact {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(5,5));
gui.setBorder( new EmptyBorder(3,3,3,3) );
JPanel controls = new JPanel( new BorderLayout(5,5) );
JPanel buttons = new JPanel(new GridLayout(0,1,4,4));
buttons.add( new JButton("Show") );
buttons.add( new JButton("Add") );
buttons.add( new JButton("Update Number") );
buttons.add( new JButton("Delete") );
buttons.setBorder( new TitledBorder("Contact") );
controls.add( buttons, BorderLayout.NORTH );
controls.add(new JScrollPane(new JTree()), BorderLayout.CENTER);
gui.add(controls, BorderLayout.WEST);
gui.add(new JTextArea("CardLayout for CRUD components.",10,30));
gui.add(new JLabel("Output label.."), BorderLayout.SOUTH);
JToolBar toolbar = new JToolBar();
toolbar.add(new JCheckBox("Auto save", true));
toolbar.add(new JCheckBox("Always On Top"));
gui.add(toolbar, BorderLayout.NORTH);
JOptionPane.showMessageDialog(null, gui);
}
};
SwingUtilities.invokeLater(r);
}
}
Screenshot
Use box layout and set dimension for each button. Check the below link.
http://download.oracle.com/javase/tutorial/uiswing/layout/box.html
Take a look at http://download.oracle.com/javase/tutorial/uiswing/layout/visual.html which discusses the various layout managers that Swing offers. GridBagLayout is probably what you need.

Categories