i have a question regarding my jspinner, i figured out how to get the value by using the jspinner.getvalue(); method. but what i need to accomplish is the value from the spinner to be printed onto a panel that at the time is hidden, (it will be visible once the user presses on the "order" section of my program) here is the components of my code regarding my spinner, the button "add to order" which is supposed to add the variable from the jspinner to the textbox in the panel. then i will also show the code for my panel
spinner
int min = 0;
int max = 9;
int step = 1;
int initValue = 0;
SpinnerModel model = new SpinnerNumberModel(initValue, min, max, step);
JSpinner a1 = new JSpinner(model);
a1.setBounds(6, 200, 33, 26);
contentPane.add(a1);
JFormattedTextField tf = ((JSpinner.DefaultEditor) a1.getEditor()).getTextField();
tf.setEditable(false);
tf.setBackground(Color.white);
the add to order button which is supposed to print the variable from the spinner to the panel
JButton btnAddToOrder = new JButton("Add To Order");
btnAddToOrder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
and finally my panel
orderDeet = new JTextField((Integer) a1.getValue());
orderDeet.setEditable(true);
orderDeet.setBounds(20, 33, 296, 235);
panel.add(orderDeet);
orderDeet.setColumns(10);
i can also show the code for the button to make the panel visible if needed but i dont want to make the question too complicated.
Related
I am trying to create a window that shows a dynamic list of textFields and
if the number of textfields is large then I want to add a scroller.
I am using GridLayout.
The problem is that the panel I added the Jlist and scroller doesn't show anything, neither the list nor the scroller. Below you will find a part of my code.
//Label
JLabel numberOfTxt = new JLabel("Please enter the number in every TextField");
int n = 11; //A random number of TextFields
firstPanel.add(numberOfTxt, BorderLayout.NORTH); //Add label to panel
JList textFieldList = new JList(); //Create a list of TextFields
for (int i = 0; i < n; i++) {
//Add TextFields to list
JTextField textField = new JTextField();
textField.setBounds(0, 0, 6, 0);
textFieldList.add(textField);
System.out.println("textFieldList" + textFieldList);
}
textFieldList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
textFieldList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
textFieldList.setVisibleRowCount(8);
//Create scroller
JScrollPane listScroller = new JScrollPane(textFieldList);
listScroller.setBounds(0, 20, 600, 600);
//Create layout for panel where the textfields will be added
if (n % 2 != 0) {
n = n + 1;
}
thirdPanel.setLayout(new GridLayout(n / 2, 2, 10, 6));
thirdPanel.add(textFieldList);
thirdPanel.setVisible(true);
//ContentPane has BoxLayout
contentPane.add(firstPanel);
contentPane.add(thirdPanel);
contentPane.repaint();
window.pack();
}
window.revalidate();
}
});
JList does not works this way. If you really need a JList of TextFields you should use ListCellRenderer (probably you don't, see p.3).
You adding textFieldList both to listScroller and thirdPanel. Probably, you should replace thirdPanel.add(textFieldList); by thirdPanel.add(listScroller);.
thirdPanel uses GridLayout, but only one control is ever added to it. You should either add TextField directly to thirdPanel (easier way), or let the JList manage them.
This is my first post on stackOverflow and I would love to hear about the proper etiquette for posting question on this website.
My problem in a brief couple statements:
I want to be able to change the numbers of a label in a Java GUI by clicking a button. As I click the button the 15 labels on the screen should go from 1-15, to 16-31. And with every click the labels should generate the labels with the next 15 numbers.
Images:
Currently what happens is when I press the "Next" button is the following:
GUI screen prior to pressing the next button
After the next button is pressed, the screen changes to the following
The problem I face is, that after I press the next button again, the screen does not change and stays with the labels from 16-31.
Objective: To have a functional "Previous" and "Next button that orderly refreshes the GUI with the previous 15 or next 15 labels, respectively.
The following is the code for the event handlers for the "Previous" and Next" buttons:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
int updateLabelBy = 16;
int multiplyingFactor = 1;
int sum = multiplyingFactor * updateLabelBy ;
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//When this button is pressed, JPanel2,3,4,5 will all show the next instance of solutions
if (NumOfExplanations > 15)
{
//Clearing out JPannels
jPanel1.removeAll();
jPanel1.updateUI();
jPanel2.removeAll();
jPanel2.updateUI();
jPanel3.removeAll();
jPanel3.updateUI();
jPanel4.removeAll();
jPanel4.updateUI();
jPanel5.removeAll();
jPanel5.updateUI();
//To update the label index numbers
//int multiplied = multiplyingFactor * updateLabelBy;
for ( int i = 16; i < NumOfExplanations; i++ )
{
JLabel label = new JLabel( "Exp " + i );
label.setSize(100,35);
label.setMaximumSize(new Dimension (140,40));
label.setMinimumSize(new Dimension (100,30));
label.setFont(new Font("Serif", Font.BOLD, 15));
jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.Y_AXIS));
jPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 15, 0));
label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jPanel2.add(label);
}
}
else
{
final JFrame parent = new JFrame();
JButton button = new JButton();
button.setText("This document only contains " + NumOfExplanations + " explanations" );
parent.add(button);
parent.pack();
parent.setVisible(true);
parent.setSize(400,200);
parent.setLocationRelativeTo(null);
}
}
This is quite easy to do. To change the text displayed on a button, just do
btn.setText( "New message" )
In my Java GUI there are 4 JTextFields. The goal is to enter default values for 3 textfields (example .8 in code below) and calculate the value and display the calculation into the 4th textfield. The user should then be able to change the values of the numbers within the JTextField and then press the calculate button again to get the new values to recalculate and display them.
Problem: when the JTextfields are edited and the calculate button is pressed it does not calculate with the new numbers but instead with the old initial values.
JTextField S = new JTextField();
S.setText(".8");
String Stext = S.getText();
final double Snumber = Double.parseDouble(Stext);
.... *same setup for Rnumber*
.... *same setup for Anumber*
....
JButton btnCalculate_1 = new JButton("Calculate");
btnCalculate_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int valuec = (int) Math.ceil(((Snumber*Rnumber)/Anumber)/8);
String stringValuec = String.valueOf(valuec);
NewTextField.setText(stringCalc);
}
I have checked several posts and tried:
How Do I Get User Input from a TextField and Convert it to a Double?
Using JTextField for user input
for the basics. However whenever trying to adapt it to my code eclipse returns various errors.
use S.getText() inside the actionPerformed() method.
The code inside actionperformed block is invoked on the button press and the code outside it remains unaffected.
So once you run your code and insert values to text fields, it assigns the a value but it does not change the same when you change the value and press calculate button
try using This code.
class a extends JFrame implements ActionListener
{
JTextField t1,t2,t3;
a()
{
setLayout(null);
t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();
JButton B1 = new JButton("Calculate");
t3.setEditable(false);
t1.setBounds(10,10,100,30);
t2.setBounds(10,40,100,30);
t3.setBounds(10,70,100,30);
B1.setBounds(50, 110, 80, 50);
add(t1);
add(t2);
add(t3);
add(B1);
B1.addActionListener(this);
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new a();
}
#Override
public void actionPerformed(ActionEvent e)
{
double Snumber = Double.parseDouble(t1.getText());
double Rnumber = Double.parseDouble(t2.getText());
double Anumber = Snumber+Rnumber;
t3.setText(String.valueOf(Anumber));
}
}
I setup a gridlayout, with 16 buttons in the center. I placed an icon on the first button.
How would I loop through, and when the user select the next button on the grid, it moves the icon from old position to new position?
private ArrayList<JButton> grid = new ArrayList<JButton>();
JPanel gridBtnPanel = new JPanel();
gridBtnPanel.setLayout(new GridLayout(4, 4));
for(int i = 0; i <= 16; i++){
JButton innerButton = new JButton();
gridBtnPanel.add(innerButton);
grid.add(innerButton);
}
ImageIcon player= new ImageIcon("player.JPG");
//starting position
grid.get(0).setIcon(player);
//wanting to move to next button when I select the near by button
for(int i = 0; i < grid.lastIndexOf(theifPerson); i++){
grid.get(i).setIcon(null);
}
Any help would be great.
Thank you.
You could add actionlisteners to the buttons, and once a button is pressed it searches through all the buttons to find one with a non-null icon, and switches the pressed button's icon with the non-null icon
Presumably you have some kind of ActionListener attached to each JButton so you know when the user clicks on one, if you don't, take a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener
When the user clicks on a button, the actionPerformed method is called. Here you want to determine which button was clicked, set the icon property of the last button to null and set the icon of the clicked button...
This will require you to know the last "active" button
private int activeButton;
private ImageIcon player;
//...
grid.get(0).setIcon(player);
activeButton = 0;
Then you simply want to update the current state...
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source instanceof JButton) {
JButton clicked = (JButton)source;
grid.get(activeButton).setIcon(null);
clicked.setIcon(player);
activeButton = grid.indexOf(clicked);
}
}
For example...
I have been creating a system by which I am listing various seats on a train within a GUI. I had decided to use a simple grid layout with numbered JButtons representing the seats and the seatNo and empty JLabels to represent empty space (I realise this may be trivial but it was simple). I have used a Gridlayout and I have created the Buttons and Labels as shown below.
I have an List (compArray2) in a separate class that consists of 0s and 1s and a direction that represent where there should be a seat and where the shouldn't be a seat. the .getNum gets the value either 0 for empty space or 1 for a seat and the .getDir gets the direction the seat will be facing.
public JPanel rowPanelCreation(int type, int rowNo, int width){
theNoOfSeats=0;
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0,width));
List<seatLayout> layout = new ArrayList<>();
layout = ModelConstants.compArray2;
for (seatLayout isit : x2){
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();
if (isit.getNum()==0){
if (isit.getDir()=='x'){
panel.add(buttonDis);
}
}
else if (isit.getNum()==1){
theNoOfSeats++;
if (isit.getDir()=='N'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultN.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='E'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultE.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
buttonEna.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){JOptionPane.showMessageDialog(null,"You have chosen : ");}});
panel.add(buttonEna);
}
else if (isit.getDir()=='S'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultS.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='W'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultW.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
}
}
return panel;
}
the main problem I am having is that when I press one of the seat buttons I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo. Is there a better way I could do this ? I'm assuming that as all the buttons are fundamentally the same, there is no way to differentiate between them ?
"I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo."
Here's your problem. It's a reference problem. In the end, all the buttons will have the same JButton and JLabel reference. So all the buttons and labels will get the last button and label reference created, hence "displays the very last seatNo."
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();
You need to create a new JButton and new JLabel reference each iteration
JBUtton buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
JLabel buttonDis = new JLabel();
Another approach would be to have an array of JButton, loop to set the buttons, and add them to the Panel. Say you have a GridLayout(2, 2). You then would need a array of 4 JButtons
JButton[] buttons = new JButton[9];
...
for (int i = 0; i < 4; i++){
buttons[i] = new JButton();
buttons[i].setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
// set other properties for button
panel.add(buttons[i]);
}