I've created an array of buttons, added them to my frame and (inefficiently) created action listeners for each of them which open a JOptionPane to take an input and add it to a String array, yet the text on the array button does not update after the popup is closed, while a button not part of an array updates its text fine.
The string array grabs the data from the JOptionPane fine, it just wont update the button's caption.
In my full program I'm writing ar_str_vals to a .xml file, and it can properly save and load the array, and surprisingly the array buttons properly set their text but only at the beginning of my program.
package wtf;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Wtf extends JFrame{
JButton[] ar_btn_vals = new JButton[2];
String[] ar_str_vals = new String[2];
public Wtf(){
super("Title");
setLayout(null);
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
constructor();
actionlisteners();
}
public void constructor(){
for (int x = 0;x<=1;x++){
ar_btn_vals[x] = new JButton();
ar_btn_vals[x].setText(ar_str_vals[x]);
ar_btn_vals[x].setBounds(5,(100 * x)+20, 100,40);
ar_btn_vals[x].setVisible(true);
add(ar_btn_vals[x]);
System.out.println(ar_str_vals[x]);
}
}
public void actionlisteners(){
for (int x=0;x<=1;x++){
switch (x){
case 0:
ar_btn_vals[0].addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ar_btn_vals0ActionPerformed(evt);
}
});
break;
case 1:
ar_btn_vals[1].addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ar_btn_vals1ActionPerformed(evt);
}
});
break;
}
}
}
private void ar_btn_vals0ActionPerformed(java.awt.event.ActionEvent evt) {
JFrame frm_val0change = new JFrame();
String newval = JOptionPane.showInputDialog(frm_val0change, "Enter new Button 1 Value");
ar_str_vals[0] = newval;
constructor();
}
private void ar_btn_vals1ActionPerformed(java.awt.event.ActionEvent evt) {
JFrame frm_val1change = new JFrame();
String newval = JOptionPane.showInputDialog(frm_val1change, "Enter new Button 2 Value");
ar_str_vals[1] = newval;
constructor();
}
public static void main(String[] args) {
Wtf frame = new Wtf();
}
}
I'm aware that this isn't as efficient as it could be, but I've got limited time to finish this and I have absolutely no idea why this isn't working properly.
This is also my first time asking a question, so please have mercy if I've formatted anything wrong.
As MadProgrammer said, all I had to do was update the button text in my action listener instead of calling the constructor again.
Related
I have made a program, which allows users to have as many text boxes as they want in which they can input a text string. I want to save each user input into different variables. I also want to print all of those variable or access the data stored in them when ever I want.
If you can help me that it would be really nice, thanks in advance. If you have any question please let me know in comment and I will answer them.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public GUI()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add Another");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate();
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new GUI().displayGUI();
}
});
}
}
What you're looking for is an ArrayList<String>.
Declare a private ArrayList<String> userStrings; where you have your private fields.
In your constructor, add userStrings = new ArrayList<String>();
And then when you receive a string, just add it into your list with userStrings.add(myNewString). (Use your String instead of myNewString)
ArrayLists are indexed like an array, but using a method get, so you can get the first item in your list by using userStrings.get(0).
My JLabel isn't being set to all of these text values.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MultipleLables{
static JFrame framey;
static JLabel lbl;
static JButton btn;
public static void GUIWindow () {
framey = new JFrame("Test");
framey.setSize(100, 100);
framey.setLayout(new FlowLayout());
lbl = new JLabel("Example Text");
btn = new JButton("Change Text");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
lbl.setText("First Text");
Thread.sleep(1000);
lbl.setText("Second Text");
Thread.sleep(1000);
lbl.setText("Third Text");
}catch (Exception e) {
//Don't really care if the program dies
}
}
});
framey.add(lbl);
framey.add(btn);
framey.setVisible(true);
}
public static void main(String[] args) {
GUIWindow();
}
}
The output would waits two seconds, then set the value of the JLabel to "Text Three" instead of displaying the three values one after another. I don't see what I'm doing wrong here.
From the question, It is not clear what is the problem you are facing. Please add an example of the code that others can run and test.
If you are trying to see the value of the variables a, b or 'c' in the JLabel , you will need code like
GUIWindow.text.setText(a.toString());
What you are doing now is setting the text "a" and not the value of variable a.
I am not sure what is the data type of the variables a, b or 'c'. If they do have a proper toString() implementation (they probably do as the System.out.println() is giving you the desired output), the above code should work. Else you might need to call the right method on these variables that will give you the desired text.
I was able to fix this issue by creating and running a swing timer. Here is the code, with the fix inside it.
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MulttipleLables{
static JFrame framey;
static JLabel lbl;
static JButton btn;
static Timer t;
static int i;
public static void GUIWindow () {
framey = new JFrame("Test");
framey.setSize(100, 100);
framey.setLayout(new FlowLayout());
lbl = new JLabel("Example Text");
btn = new JButton("Change Text");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e1) {
t = new Timer (1000,new ActionListener() {
public void actionPerformed(ActionEvent e2) {
;
lbl.setText("First Text");
switch (i) {
case 1:
lbl.setText("Second Text");
i++;
break;
case 2:
lbl.setText("Third Text");
i++;
break;
default:
i++;
}
if (i == 3) {
t.stop();
i = 0;
}
}
});
t.start();
}
});
framey.add(lbl);
framey.add(btn);
framey.setVisible(true);
}
public static void main(String[] args) {
GUIWindow();
}
}
I don't have a compiler on me, but I am sure this code should work for what you need.
Im making a jframe with two components. A list and a button. The list starts at 0 and everytime i press the button it increases by 1. So if i press the button, the value in the jlist changes from 0 to 1.
My question is, how can I add an integer to a jlist? (i tried the setText method just in case - only works for Strings)
Thanks
EDIT: PART OF MY CODE (ActionListener)
increase.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
counter++;
System.out.println(counter);
listModel.addElement(counter);
// listModel.clear();
}
});
I'm assuming that you want to add an int item to the JList, meaning a new int pops up in the list's display each time the button is pushed. You can create a JList<Integer> and add Integers (or boxed ints) to the JList's model, usually using listModel.addElement(myInteger).
If you need to clear previous elements, do so before adding the element, not after. For example,
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Foo2 extends JPanel {
private DefaultListModel<Integer> dataModel = new DefaultListModel<>();
private JList<Integer> intJList = new JList<>(dataModel);
public Foo2() {
add(new JScrollPane(intJList));
intJList.setFocusable(false);
add(new JButton(new AbstractAction("Add Int") {
private int count = 0;
#Override
public void actionPerformed(ActionEvent e) {
dataModel.clear(); // if you need to clear previous entries
dataModel.addElement(count);
count++;
}
}));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Foo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Foo2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I've created two JFrames.
The main JFrame contains the text area. My sub JFrame contains a drop down list.
The task is to pass the value that I've selected in the drop down list and display in the text area in the main JFrame.
Code in the sub JFrame:
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {
close();
room=cmbRoom.getSelectedItem().toString();
}
Code in the main JFrame:
private void btnDisplayActionPerformed(java.awt.event.ActionEvent evt) {
roomNo r=new roomNo();
txtArea2.append("\nRoom Number: " + r.getroom());
}
class NextPage extends JFrame
{
NextPage(String st)
{
setLayout(null);
setDefaultCloseOperation(javax.swing. WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Welcome");
JLabel lab=new JLabel("Welcome "+st);
lab.setBounds(10,10,500,20);
add(lab);
setSize(300, 100);
}
}
This might not be exactly correct answer but this will do the job.
Suppose you have 2 Jframes namely Home.java and Second.java
the code for Second.java as below,
public static String selection = "";//static variable to store seletced value from combobox
Home h = new Home();//instance of Home Jframe
/**
* return selected value (called from Home Jframe)
*/
public static String getSeletced() {
return selection;
}
/**
* get selected value from comboBox event
*/
private void cmbLapActionPerformed(java.awt.event.ActionEvent evt) {
selection = cmbLap.getSelectedItem().toString();
h.isSelected = true;//this is to control data duplication
}
Now for the Home.java file we can use formWindowGainedFocus event to update the jTextArea. Home .java file contains following code,
public static boolean isSelected = false;//flag to check combo box is selected
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {
System.out.println(isSelected);
if (isSelected) {
String text = new Second().getSeletced();
System.out.println(text);
txaData.append("Your Laptop: " + text + "\n");//appending data
isSelected = false;//to prevent duplication
}
}
This method can use to update jTextArea using data from another jFrame.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class PassData extends JFrame
{
JTextField text;
PassData(){
JLabel l=new JLabel("Name: ");
text=new JTextField(20);
JButton b=new JButton("Send");
setLayout(null);
l.setBounds(10,10,100,20);
text.setBounds(120,10,150,20);
b.setBounds(120,40,80,20);
add(l);
add(text);
add(b);
setVisible(true);
setSize(300,100);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String value=text.getText();
NextPage page=new NextPage(value);
page.setVisible(true);
}
});
}
public static void main(String[] args)
{
new PassData();
}
}
I am trying to create an UI which has two panes.
In the left pane I display the list of files and right pane displays the contents.
Now, I want list of files in the left pane to look as a normal list. But when I click an entry in this list, the contents of the particular file should be displayed in the right pane.
How can I achieve this using Swing?
Here I have done a short example, with the help of JList on the left and JTextArea on right. I have used ListSelectionListener to get the item list change. Use a LayoutManager as per your convenience.
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JListTest {
private JList jList1;
private JPanel jPanel1;
private JTextArea jTextArea1;
public JListTest() {
initComponents();
}
private void initComponents() {
JFrame f = new JFrame();
jPanel1 = new JPanel();
jList1 = new JList();
jTextArea1 = new JTextArea();
jList1.setModel(new AbstractListModel() {
String[] strings = {"Item 1", "Item 2"};
#Override
public int getSize() {
return strings.length;
}
#Override
public Object getElementAt(int i) {
return strings[i];
}
});
jList1.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jPanel1.add(jList1);
jPanel1.add(jTextArea1);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.add(jPanel1);
f.pack();
f.setVisible(true);
}
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
//set text on right here
String s = (String) jList1.getSelectedValue();
if (s.equals("Item 1")) {
jTextArea1.setText("You clicked on list 1");
}
if (s.equals("Item 2")) {
jTextArea1.setText("You clicked on list 2");
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JListTest();
}
});
}
}
Check out this tutorial. It explains how to use lists in Swing, including event handlers that are necessary to register for click events.
You might want to look at this JTree example.
first off, you have not even tried yet, right? Swing does almost everything input related with listeneres. Check out the mouse listener, or adjust the awnser giving below
https://stackoverflow.com/a/4344762/258418
For completness I quote it here:
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
JList list = (JList)evt.getSource();
if (evt.getClickCount() == 2) {
int index = list.locationToIndex(evt.getPoint());
} else if (evt.getClickCount() == 3) { // Triple-click
int index = list.locationToIndex(evt.getPoint());
}
}
});
I am sure you can make it take single clicks as well,... if not write a comment
Some examples for reference:
FileBrowser uses a JTree on the left and nested detail panels on the right.
ImageDisplay embeds a custom JFileChooser on the left and displays a scrollable image on the right.
CheckTable shows a JTable on the left and a DisplayPanel on the right.
Use JList.addListSelectionListener(ListSelectionListener).
See How to Write a List Selection Listener for more examples.