I have a problem where I have a comboBox that causes an action that sets the text in a textField. Here's the code:
public class Main extends JFrame implements ActionListener{
private JPanel contentPane;
private JTextField textField;
private JComboBox comboBox;
//public static void main - nothing much in it except Main frame = new Main();
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 563, 407);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
comboBox.addActionListener(frame);
textField = new JTextField();
textField.setBounds(42, 99, 445, 235);
textField.setText("HERE");
contentPane.add(textField);
textField.setColumns(10);
comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Bob", "Dan ", "Emily"}));
comboBox.setBounds(42, 48, 140, 29);
contentPane.add(comboBox);
/*ONE WAY OF DOING IT: comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText(studentOutputString((String)comboBox.getSelectedItem()));
textField.setText("BLAH");
}
});*/
}
public String studentOutputString(String student){
String s = student + "is printed.";
return s;
}
public void actionPerformed(ActionEvent e) {
comboBox = (JComboBox) e.getSource();
String selectedStudent = (String) comboBox.getSelectedItem();
textField.setText(studentOutputString(selectedStudent));
}
Nothing shows up in the textField. Any idea about what I'm doing wrong?
I reformatted it and caught up on my past threads.
You need to generate an action on the ComboBox in order for the action listener to be called and set the text of the TextField. Try selecting an item in the ComboBox
Also, comboBox.getSelectedItem() might return null if there are other events besides change of selected items (e.g. an event is generated before a selection was made). In that case your call to student + "is printed." inside studentOutputString() will throw a null-pointer exception
Related
I am trying to making a calculator.
Here the user can add multiple JTextFields to take his/her desired input with just one button click.
Now I want that the user will take the input in multiple JTextFields added by him and on clicking the Result button will show the sum of all. But I am always getting 0 as output.
Code:
public class Button extends JFrame {
private JPanel contentPane;
private JButton btnAdd;
private JButton btnResult;
private JTextField resultField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Button frame = new Button();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Button() {
initComponents();
}
static JTextField field = null;
//static JTextField fields[] = new JTextField[10];
private static int y = 0;
ArrayList<String> arr = new ArrayList<String>();
int ans, sum = 0;
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 527, 414);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
field = new JTextField();
field.setBounds(45, y += 60, 284, 32);
field.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(field);
contentPane.revalidate();
contentPane.repaint();
}
});
btnAdd.setBounds(170, 341, 89, 23);
contentPane.add(btnAdd);
btnResult = new JButton("Result");
btnResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < arr.size(); i++) {
arr.add(field.getText());
sum += Integer.parseInt(arr.get(i));
}
resultField.setText(String.valueOf(sum));
}
});
btnResult.setBounds(383, 306, 89, 23);
contentPane.add(btnResult);
resultField = new JTextField();
resultField.setBounds(361, 275, 129, 20);
contentPane.add(resultField);
resultField.setColumns(10);
}
}
Please help how can I find the correct output?
Suggestions:
Again, when you create a data-entry text field, add it to the GUI and add it to an ArrayList of the data entry field type.
Then in the result button's ActionListener, iterate through this list using a for loop.
Inside of the for loop, get the entry field, get its text (via .getText() if using a JTextField), parse it to number via Integer.parseInt(...), and add it to a sum variable that is initialized to 0 prior to the for loop. Then display the result after the loop.
Also,
Best to use JSpinners that use a SpinnerNumberModel such as JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1)); instead of JTextField for number entry. This will limit the user to entering numbers only, and won't allow non-numeric text entry, a danger inherent in your current design.
Having to add your entry fields by button may be an over-complication
But if it is necessary, then best to add the spinners (or text fields if you must) to a JPanel that uses a proper layout manager, such a new GridLayout(0, 1) (variable number of rows, 1 column) and then add that to a JScrollPane so that you can see as many fields as has been entered.
If using a JSpinner, then you don't even need a "calculate result" button, since if you add a ChangeListener to each JSpinner, you can calculate the result on the fly whenever a spinner has had its data changed.
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Button2 extends JPanel {
private List<JSpinner> spinnerList = new ArrayList<>();
private JButton resultButton = new JButton("Result");
private JButton addEntryFieldBtn = new JButton("Add Entry Field");
private JTextField resultField = new JTextField(6);
private JPanel fieldPanel = new JPanel(new GridLayout(0, 1, 4, 4));
public Button2() {
resultField.setFocusable(false);
resultButton.addActionListener(e -> calcResult());
resultButton.setMnemonic(KeyEvent.VK_R);
addEntryFieldBtn.addActionListener(e -> addEntryField());
JPanel topPanel = new JPanel();
topPanel.add(addEntryFieldBtn);
topPanel.add(resultButton);
topPanel.add(new JLabel("Result:"));
topPanel.add(resultField);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(fieldPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(centerPanel);
scrollPane.setPreferredSize(new Dimension(300, 300));
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane);
}
private void calcResult() {
int sum = 0;
for (JSpinner spinner : spinnerList) {
sum += (int) spinner.getValue();
}
resultField.setText(String.valueOf(sum));
}
private void addEntryField() {
JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, 1000, 1));
spinner.addChangeListener(evt -> {
calcResult();
});
fieldPanel.add(spinner);
spinnerList.add(spinner);
revalidate();
repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Button2 mainPanel = new Button2();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
This is the submit button code:
JComboBox cb1 = new JComboBox();
Object[] row = new Object [4];
JButton btnSubmit = new JButton("SUBMIT");
btnSubmit.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
btnSubmit.setBounds(35, 153, 84, 23);
panel_1.add(btnSubmit);
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
row[0] = txtfieldname.getText();
row[1] = txtfieldemail.getText();
row[2] = txtfieldphone.getText();
row[3] = cb1.getSelectedItem();
model.addRow(row);
}
});
This is the table code:
table_5 = new JTable();
scrollPane.setViewportView(table_5);
model = new DefaultTableModel();
Object[] column = {"Name","Employeed ID", "Phone No.", "Schedule"};
model.setColumnIdentifiers(column);
table_5.setModel(model);
This is the data of jcombobox:
cb1.setBounds(114, 113, 94, 22);
panel_1.add(cb1);
cb1.addItem("6:00-8:00 AM");
cb1.addItem("8:00-10:00 AM");
cb1.addItem("10:00-11:00 AM");
My concern is if i select the first option in the jcheckbox I want to removed it completely so It will not choose again.
After you clarified that you actually meant JComboBox instead of JCheckBox this clearly makes more sense. I quickly put together a minimal reproducible example, which contains a JComboBox including your timeframes and a submit button. On the click of the submit button the currently selected timeframe will be removed from the combobox.
public static void main(String args[]) {
SwingUtilities.invokeLater(() -> {
buildGui();
});
}
private static void buildGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Select your timeframe: ");
frame.add(label, BorderLayout.WEST);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("6:00-8:00 AM");
comboBox.addItem("8:00-10:00 AM");
comboBox.addItem("10:00-11:00 AM");
frame.add(comboBox);
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// add row to your model
// then remove the selected timestamp from your box
comboBox.removeItemAt(comboBox.getSelectedIndex());
}
});
frame.add(submitButton, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
I have written a frame in java swing . In it I have a checkbox . I want , that after clicking checkbox others Item will change it visibility. I was trying to do it as in code below but is not working as i wish .
public InFrm() {
setTitle("In");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new GridLayout(1, 1, 0, 0));
seeMe=false;
JSplitPane splitPane = new JSplitPane();
splitPane.setResizeWeight(0.7);
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
getContentPane().add(splitPane);
JPanel panel = new JPanel();
splitPane.setLeftComponent(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
splitPane.setRightComponent(panel_1);
panel_1.setLayout(null);
JLabel lblKind= new JLabel("Kind");
lblKind.setBounds(10, 8, 33, 14);
lblKind.setVisible(seeMe);
panel_1.add(lblKind);
JComboBox ChoiceOd = new JComboBox();
ChoiceOd.setBounds(53, 5, 28, 20);
ChoiceOd.setVisible(seeMe);
panel_1.add(ChoiceOd);
// more items using seeMe
JCheckBox chckbxOd = new JCheckBox("Od");
chckbxOd.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
seeOd();
}
});
chckbxOd.setBounds(6, 150, 97, 23);
panel.add(chckbxOd);
}
protected void seeOd() {
if(seeMe){
seeMe=false;
}
else
{
seeMe=true;
}
}
In your see method you only set the flag but of course it does not set the visibility of your component. Set the visibility direct to the component, than it will work
Your Listener should look something like this:
public void itemStateChanged(ItemEvent ev) {
Object item = ev.getItem();
if (ev.getStateChange() == ItemEvent.DESELECTED) {
//hide the component associated with this item
} else {
//show the component associated with this item
}
}
what i want to do is my table should automatically add row depends on the number of rows i input in a textbox. example if the user input 3 in the textbox and i click he clicked the jbutton the table will automatically have 3 rows with null values.. i'm just new to programming and this is a lab activity we did yesterday but no one seems did it
private JPanel contentPane;
private JTable table;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WindowwwTry frame = new WindowwwTry();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WindowwwTry() {
DefaultTableModel dm = new DefaultTableModel();
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
table.setModel(dm);
dm.addColumn("PROCESS");
dm.addColumn("CPU Time");
dm.addColumn("Arrival Time");
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table = new JTable();
table.setBounds(177, 123, 1, 1);
contentPane.add(table);
textField = new JTextField();
textField.setBounds(92, 24, 86, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
int ps = Integer.parseInt(textField.getText());
for(int x=0; x<ps; x++){
dm.addRow(new Object[]{x});
}
}catch(Exception e){
e.printStackTrace();
}
}
});
btnNewButton.setBounds(206, 23, 89, 23);
contentPane.add(btnNewButton);
}
Your code works perfectly fine. The problem you experience is that you don't see the results, because the size of your table is very, very small. Change the line where you set bounds to something like this:
table.setBounds(177, 123, 200, 100);
As #gawi said your table is too small (its width and height are 1 pixel). You should set it to some higher value (I tried using table.setBounds(177, 123, 100, 100) and it fits quite nicely in the window.
Also your for loop incorrect. You want that
table will automatically have 3 rows with null values
so the for loop should look something like this
for(int x=0; x<ps; x++){
dm.addRow(new Object[]{null, null, null});
}
to set to null all the 3 columns in your table
when i select something in combobox :
it show joptionPane Dialog box wiht two inputs.
here i want to first focusing amount field and then, when i entered in amount field its goes to no of App field then enter go to OK .
Here is my code for JOption Dialog:
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Amount:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("No of App:"));
myPanel.add(yField);
int value = 0;
xField.requestFocus();
int result = JOptionPane.showConfirmDialog(null, myPanel, "Please Enter Amount and No.of app", JOptionPane.OK_CANCEL_OPTION);
You simply try to focus a component which is not layout in a window.
Replace
xField.requestFocus();
by
SwingUtilities.invokeLater(new Runnable() {
public void run() {
xField.requestFocusInWindow();
}
});
You can create your own JDialog on the event that an item has changed to a new item. Then, you can get values entered in the JDialog and appropriately set the information in your parent. If you want to change the order of focus, use a custom focus policy. If you want to change the traversal focus key to the Enter key, you should re-map the key so that it reacts the same as the Tab key. There are several resources online and on this site with information on how to do that.
You should note that the default focus traversal policy is dependent on the order in which you add you elements to your content panel.
I have created a simple example for you on using a JDialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class RankSelection extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RankSelection frame = new RankSelection();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public RankSelection() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel<String>(new String[] {"Slave", "Peasant", "Minion", "Knight", "Bishop", "Prince", "Coder King"}));
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
Amount amount = new Amount();
textField.setText(Integer.toString((Integer) amount.getStinkiness().getValue()));
}
}
});
contentPane.add(comboBox, BorderLayout.CENTER);
JLabel lblYourRank = new JLabel("Your Rank");
contentPane.add(lblYourRank, BorderLayout.NORTH);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
JLabel lblYourStinkiness = new JLabel("Your Stinkiness:");
panel.add(lblYourStinkiness);
textField = new JTextField();
textField.setEditable(false);
textField.setEnabled(false);
textField.setText("0");
panel.add(textField);
textField.setColumns(10);
pack();
}
}
The custom JDialog:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Amount extends JDialog {
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JSpinner amount;
private JSpinner stinkiness;
public Amount() {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
JLabel lblAmount = new JLabel("Amount:");
amount = new JSpinner();
JLabel lblStinkiness = new JLabel("Stinkiness:");
stinkiness = new JSpinner();
contentPanel.add(lblAmount);
contentPanel.add(amount);
contentPanel.add(lblStinkiness);
contentPanel.add(stinkiness);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
pack();
setVisible(true);
}
public JSpinner getAmount() {
return amount;
}
public JSpinner getStinkiness() {
return stinkiness;
}
}