I am currently having trouble with a JTextPane not updating when a JButton ActionListener is telling it to update. In the code, I have a button that assigns a selected value from a JList to a global variable.
This process works because when I print out the variable when I press the button it prints the selected value in a list. However, when I push the button I also want that variable to populate the text pane so I know what value I am working with when using the UI. Does anyone know what might help with this?
I will try to get the relevant code from my large JavaSwing script as I'm using Eclipse WindowBuilder and it throws everything in the source in whatever order I created it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class MainMappingGui extends JFrame {
private JPanel contentPane;
String attSelected = "Hello";
String attButSelect = "";
JTextPane textPaneEdits;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMappingGui frame = new MainMappingGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainMappingGui() {
setTitle("Data Mapping");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1105, 892);
contentPane = new JPanel();
contentPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnConfigMap = new JButton("Configure Mapping");
btnConfigMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
attButSelect = attSelected;
System.out.println(attButSelect);
textPaneEdits.repaint();
textPaneEdits.revalidate();
}
});
btnConfigMap.setFont(new Font("Tahoma", Font.PLAIN, 9));
btnConfigMap.setBounds(206, 406, 122, 23);
contentPane.add(btnConfigMap);
textPaneEdits = new JTextPane();
textPaneEdits.setBounds(634, 38, 314, 357);
textPaneEdits.setEditable(false);
textPaneEdits.setText("Current Output Column: " + attButSelect);
contentPane.add(textPaneEdits);
}
}
For this example, please assume that attSelected is a value that changes dynamically with a ListSelectionListener and works properly for selected values in a list. I have set it to "Hello" for simplicity sake.
As the one of the comments says, you have to manually change the text in the text pane.
btnConfigMap.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
attButSelect = attSelected;
textPaneEdits.setText(attButSelect);
}
});
Repaint and revalidate are not necessary.
I am new to Java and have just tried out Java's swing, I tried making a log in form that would print the content of a JTextField to the console, but the console doesn't show anything when I tried it.
Here's my code:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
public class JavaTextField {
private JFrame frame;
private JTextField text1;
private JTextField text2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaTextField window = new JavaTextField();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public JavaTextField() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
text1 = new JTextField();
text1.setBounds(114, 38, 122, 40);
frame.getContentPane().add(text1);
text1.setColumns(10);
String majorText = text1.getText();
text2 = new JTextField();
text2.setBounds(114, 117, 86, 20);
frame.getContentPane().add(text2);
text2.setColumns(10);
String minorText = text2.getText();
JButton btnButton = new JButton("Button");
btnButton.setBounds(132, 192, 159, 40);
frame.getContentPane().add(btnButton);
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(majorText);
System.out.println(minorText);
}
}
);
}
}
I'm glad if anyone could point me in the right direction, because I haven't seen the solution to this problem on the internet yet.
The issue here is, that you retrieve the content from the JTextFields at the wrong time. Currently you call getText() right when the components are being initialized. Of course, the content returned from getText() will be an empty String.
So to fix the issue in your logic, you should actually retrieve the majorText and minorText from the JTextFields only once your JButton has been pressed. Because at that point in time, when your button is pressed, the content of your text fields should be correct. To do that, move the retrieval of the text to the ActionListener.
The updated ActionListener should look as follows:
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String majorText = text1.getText();
String minorText = text2.getText();
System.out.println(majorText);
System.out.println(minorText);
}
}
or simply:
btnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(text1.getText());
System.out.println(text2.getText());
}
}
Sidenote (as also mentioned by the other answer):
Using null layout is highly discouraged, as it is a frequent source for unnecessary errors. Have a look at the different LayoutManagers available and how and when to use them.
There are some improvements to do in your code:
Avoid the use of null-layout and setBounds(...), see why should you avoid it and a graphic example along with a suggestion to fix it by using layout managers
Your majorText is getting the text BEFORE you click on the button, and by that time it's empty and never update it, you need to get the text on button click, so move this line:
String majorText = text1.getText();
Inside your actionListener, same thing for minorText
And if you tagged your question with Java 8, then you could rewrite your listener using Java 8 lambdas
btnButton.addActionListener(e -> {
String majorText = text1.getText();
String minorText = text1.getText();
System.out.println(majorText);
System.out.println(minorText);
}
This is a simple JFrameapplication. It basically creates a new Frame on basis of the user choice. The first frame starts but the new one doesn't show up! It show the errors-
ie1 cannot be resolved & ie2 cannot be resolved. I want to see the new Frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Test2 {
public static void main(String[] args) {
JFrame jf = new JFrame("Java test");
Container c = jf.getContentPane();
jf.setBounds(450, 180, 450, 450);
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
c.add(jp);
JLabel jl = new JLabel("This is a text in a label",SwingConstants.CENTER);
jp.add(jl);
JComboBox jcb1 = new JComboBox();
jp.add(jcb1);
jcb1.addItemListener(new ItemListener() {
public void itemStateChanged(final ItemEvent ie1) {
ie1.getItem();
}
});
jcb1.addItem(" Select the Size ");
jcb1.addItem("100 x 100");
jcb1.addItem("200 x 200");
jcb1.addItem("300 x 300");
jcb1.addItem("400 x 400");
jcb1.addItem("500 x 500");
jcb1.addItem("600 x 600");
JComboBox jcb2 = new JComboBox();
jp.add(jcb2);
jcb2.addItemListener(new ItemListener() {
public void itemStateChanged(final ItemEvent ie2) {
ie2.getItem();
}
});
jcb2.addItem(" Select the Colour ");
jcb2.addItem("Blue");
jcb2.addItem("Red");
jcb2.addItem("Black");
jcb2.addItem("White");
jcb2.addItem("Yellow");
jcb2.addItem("Green");
JButton jb = new JButton("Create a new Frame");
jp.add(jb);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final JFrame jf1 = new JFrame("New Frame");
Container c = jf1.getContentPane();
jf1.setVisible(true);
jf1.setDefaultCloseOperation(jf1.EXIT_ON_CLOSE);
// The Size of the frame
if (ie1.getItem().equals(" Select the Size ")) {
JOptionPane.showMessageDialog(null, "Please select the size of the Frame");
}
if (ie1.getItem().equals("100 x 100"))
;
{
jf1.setBounds(450, 180, 100, 100);
}
if (ie1.getItem().equals("200 x 200"))
;
{
jf1.setBounds(450, 180, 200, 200);
}
if (ie1.getItem().equals("300 x 300"))
;
{
jf1.setBounds(450, 180, 300, 300);
}
if (ie1.getItem().equals("400 x 400"))
;
{
jf1.setBounds(450, 180, 400, 400);
}
if (ie1.getItem().equals("500 x 500"))
;
{
jf1.setBounds(450, 180, 500, 500);
}
if (ie1.getItem().equals("600 x 600"))
;
{
jf1.setBounds(450, 180, 600, 600);
}
// The size of the Frame ends
// The colour of the frame
if (ie2.getItem().equals(" Select the Colour ")) {
JOptionPane.showMessageDialog(null, "Please select the colour of the Frame");
}
final JPanel jp1 = new JPanel();
c.add(jp1);
if (ie2.getItem().equals("Blue")) {
jp1.setBackground(Color.blue);
}
if (ie2.getItem().equals("Red")) {
jp1.setBackground(Color.red);
}
if (ie2.getItem().equals("Black")) {
jp1.setBackground(Color.black);
}
if (ie2.getItem().equals("White")) {
jp1.setBackground(Color.white);
}
if (ie2.getItem().equals("Yellow")) {
jp1.setBackground(Color.yellow);
}
if (ie2.getItem().equals("Green")) {
jp1.setBackground(Color.green);
}
// the colour of the frame ends
}
});
}
}
You are not instantiating, nor initializing the ie1 and ie2 variables anywhere. I can see these represent ItemEvent references, but their scope is limited to the ItemListener 'changed' method.
If you are using Eclipse, it should provide you with a quick fix. But if I were you, I would start reading on Java for Beginners first, and after that move onto the AWT/Swing and SWT/JFace stuff.
Try starting with more basic stuff. It occurs to me that the code above is a bit overwhelming for you. Good luck lil programmer.
Several things:
You don't need ItemListeners to get the selected value of the combo boxes, instead just do
Object ie1 = jcb1.getSelectedItem();
Object ie2 = jcb2.getSelectedItem();
right above
if(ie1.equals(" Select the Size "))
{
JOptionPane.showMessageDialog(null,"Please select the size of the Frame");
}
And since you're using an anonymous inner class, you'll need to make sure jcb1 and jcb2 are declared final, like so:
final JComboBox jcb1 = new JComboBox();
Also, change ie1.getItem().equals(...) to just ie1.equals(...), and do the same for ie2.
On another note, don't put semicolons after if statements.
Right:
if(ie1.equals("100 x 100"))
{
...
}
Wrong:
if(ie1.equals("100 x 100"));
{ //^
...
}
So remove the semicolons that you have after those if statements.
With all that said, I would definitely recommend going with GGrec's advice, and start reading some Java tutorials.
I can't get my program to compile!
i think im missing a curly brace but can't for the life of me see where!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.text.*;
import java.net.*;
import java.util.Scanner;
public class AddressBook extends JFrame
{
FlowLayout leftLayout;
JFrame frame;
JPanel panel;
JTextField txtname,txtsurname, txtphone, txtmobile, txtaddress, txtpostcode;
JButton btnadd, btnnext, btnprevious, btnsave, btndelete;
JLabel jlbname, jlbsurname, jlbphone, jlbmobile, jlbaddress, jlbpostcode;
String fileInput,readline;
ArrayList<String> arrayOfFile = new ArrayList<String>();
ArrayList<Contact> records = new ArrayList<Contact>();
int index = 0;
public static void main(String[] args) throws IOException
{
new AddressBook();
}
public AddressBook()
{
//sets window
frame = new JFrame();
frame.setTitle("Bournemouth University Address Book");
frame.setSize(760, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//sets up panel
panel = new JPanel();
panel.setLayout(null);
frame.getContentPane().add(panel);
//Labels
jlbname = new JLabel("Name:");
jlbname.setBounds(10, 50, 100, 20);
panel.add(jlbname);
jlbsurname = new JLabel("Surname:");
jlbsurname.setBounds(350, 50, 100, 20);
panel.add(jlbsurname);
jlbphone = new JLabel("Home Number:");
jlbphone.setBounds(10, 90, 150, 20);
panel.add(jlbphone);
jlbmobile = new JLabel("Mobile:");
jlbmobile.setBounds(350, 90, 150, 20);
panel.add(jlbmobile);
jlbaddress = new JLabel("Address:");
jlbaddress.setBounds(10, 130, 200, 20);
panel.add(jlbaddress);
jlbpostcode = new JLabel("PostCode:");
jlbpostcode.setBounds(10, 170, 250, 20);
panel.add(jlbpostcode);
//Text Fields
txtname = new JTextField("");
txtname.setBounds(120, 50, 200, 20);
panel.add(txtname);
txtsurname = new JTextField("");
txtsurname.setBounds(440, 50, 200, 20);
panel.add(txtsurname);
txtphone = new JTextField("");
txtphone.setBounds(120, 90, 200, 20);
panel.add(txtphone);
txtmobile = new JTextField("");
txtmobile.setBounds(440, 90, 200, 20);
panel.add(txtmobile);
txtaddress = new JTextField("");
txtaddress.setBounds(120, 130, 520, 20);
panel.add(txtaddress);
txtpostcode = new JTextField("");
txtpostcode.setBounds(120, 170, 250, 20);
panel.add(txtpostcode);
//Buttons
btnadd = new JButton("Add", new ImageIcon("../files/add.png"));
btnadd.setBounds(330, 320, 100, 50);
btnadd.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnadd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
txtname.setText("Add new details here");
txtsurname.setText("");
txtphone.setText("");
txtmobile.setText("");
txtaddress.setText("");
txtpostcode.setText("");
}
});
panel.add(btnadd);
btndelete = new JButton("Delete", new ImageIcon("../files/delete2.png"));
btndelete.setBounds(390, 250, 100, 50);
btndelete.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btndelete.setForeground(Color.red);
// btndelete.addActionListener(this);
panel.add(btndelete);
btnsave = new JButton("Save", new ImageIcon("../files/save.png"));
btnsave.setBounds(490, 250, 100, 50);
btnsave.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnsave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
BufferedWriter fileOut = new BufferedWriter(new FileWriter("../files/contacts.buab", true));
fileOut.append(txtname.getText());
fileOut.append("\n");
fileOut.append(txtsurname.getText());
fileOut.append("\n");
fileOut.append(txtphone.getText());
fileOut.append("\n");
fileOut.append(txtmobile.getText());
fileOut.append("\n");
fileOut.append(txtaddress.getText());
fileOut.append("\n");
fileOut.append(txtpostcode.getText() + "\r");
fileOut.close();
}
catch (IOException ioe)
{
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
}
});
panel.add(btnsave);
btnprevious = new JButton("Prev", new ImageIcon("../files/left.png"));
btnprevious.setBounds(280, 250, 100, 50);
btnprevious.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnprevious.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent event)
{
index--;
displaycontact();
}
});
panel.add(btnprevious);
btnnext = new JButton("Next", new ImageIcon("../files/right.png"));
btnnext.setBounds(180, 250, 100, 50);
btnnext.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnnext.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
index ++;
displaycontact();
}
});
panel.add(btnnext);
frame.setVisible(true);
panel.setVisible(true);
JMenuBar mb = new JMenuBar();
frame.setJMenuBar(mb);
JMenu insert = new JMenu("Import");
mb.add(insert);
JMenuItem imp = new JMenuItem("Add New Contacts");
insert.add(imp);
imp.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent event)
{
JFileChooser fileopen = new JFileChooser();
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION)
{
try {
BufferedReader fileStream = new BufferedReader(new FileReader("src/contacts.buab"));
while (true)
{
String fileInput = fileStream.readLine();
if(fileInput==null)
break;
Contact a = new Contact();
a.setname(fileInput);
a.setsurname(fileStream.readline());
a.setphone(fileStream.readLine());
a.setmobile(fileStream.readLine());
a.setaddress(fileStream.readLine());
a.setpostcode(fileStream.readline());
Contacts.add(a);
System.out.println(a.getname());
}
fileStream.close();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
displaycontact();
}});
}
public void displaycontact()
{
txtname.setText(contacts.get(index).name);
txtsurname.SetText(contacts.get(index).surname);
txtphone.setText(contacts.get(index).phone);
txtmobile.setText(contacts.get(index).mobile);
txtAddress.setText(contacts.get(index).address);
}
}
}
please help i've been here for 3 hours!!
You are missing a curly brace here:
displaycontact();
}}}); // <- HERE
This is nearly impossible to see with your code because it is formatted very poorly. You should use a text editor which highlights matching braces. This lets you see quickly what that closing brace closes.
I advise you to reformat the code so that there is proper indentation. You have quite a lot of indentation so you may want to consider using two spaces or a tab size with the tab width set to two. Proper indentation lets you scan the code veritcally to see where the braces are closing things.
I reformatted your code in Eclipse and the ActionListener which is causing your problem now looks like this:
imp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser fileopen = new JFileChooser();
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
try {
BufferedReader fileStream = new BufferedReader(new FileReader("src/contacts.buab"));
while (true) {
String fileInput = fileStream.readLine();
if (fileInput == null)
break;
Contact a = new Contact();
a.setname(fileInput);
a.setsurname(fileStream.readline());
a.setphone(fileStream.readLine());
a.setmobile(fileStream.readLine());
a.setaddress(fileStream.readLine());
a.setpostcode(fileStream.readline());
Contacts.add(a);
System.out.println(a.getname());
}
fileStream.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
displaycontact();
}
}
});
Notice that the last curly brace blob is now in three lines and that each line is less indented than the previous? This would make it immediately obvious where you were missing a curly brace.
new should be all lower-case
ioe should be ex
Remove the bottom-most curly-bracket
Add one more closing curly bracket after JOptionPane.showMessageDialog(null, ioe.getMessage()); displaycontact();
Use the prescribed coding conventions, especially the indentation ones
You appear to have a spurious open curly brace in front of public void actionPerformed.
But really, you need to be able to sort these out yourself. You can't post your code to SO every time it doesn't compile... Something that may help here is an editor that can do folding (just about every IDE would do this), or even the functionality that vi has when you press % on a brace/bracket/quote etc. (which jumps to the closing symbol letting you match up start and end).
Plus, whenever you ask a question, always provide the diagnostic information - which in this case would be the compiler output. It's basically rude to expect people to help you while withholding pertinent information.
You're short one closing curly brace after the last displaycontact();
You then need to remove the final curly brace.
addiosamigo, I would really recommend that you be able to deal with these kinds of errors youself, since it will help you much more in the future.
To help in that, here are the steps that I would take to solve this kind of thing:
Delete all the code from the file, except the minimum necessary to compile. See if this compiles (if not, you have a serious problem that's not part of the code. Perhaps a problem with a project definition or something).
Start adding code back in very small chunks.
Each time you add code back, make sure it compiles.
Eventually, you'll add something that doesn't compile, and you'll know the bad code is there.
Please note that doing this is not always so simple, since sometimes you need to add code in a certain order for it to compile.
For example, adding the code for function Foo, which calls function Bar, without adding the code for Bar will obviously cause a compile error. In this kind of case, you'll have to do smart tricks (like adding Bar back in, without any actual implementation, etc).
All in all, the strategy is the same as for every bug: find the smallest case that reproduces it, and work from there.
Hope this helps
The if statement
if (ret == JFileChooser.APPROVE_OPTION)
is missing it's closing brace, you must add it just after
displaycontact();
at the end of the source is an extra brace.
A few hints to help yourself in the future:
make sure your code indenting is correct, fixing your whitespacing and indenting would have lead you to the culprit
anonymous classes can make code unreadable if they consist of more than a few lines, your action listener is a fine example of this. code becomes much more readable if you create a separate nested class for it instead of inserting large anonymous classes.
Edit: to get started have a look at Sun's Java code conventions like and its indenting chapter. IDE's like eclipse supoort formatting and indenting of your code too.