how to retrieve a text from textfield out of main method - java

What I want to design is with this code is when I enter any text into the Textfield, then hit the button to save it. So I've been trying few ways, but I could not solve that command prompt shows me an empty space...
When I tried the source code into the "main" method, it was working well like what I expected..
Here is my source code:
package test;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
class testListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s = new TxtField().savedTxt();
System.out.println("ActionPerformed :" + s);
}
}
public class TxtField {
static JTextField jtf;
JFrame jf;
JButton jbtn;
static String temp;
public TxtField() {
jtf = new JTextField(10);
jf = new JFrame("JFrame");
jbtn = new JButton("OK");
jf.add(jtf);
jf.add(jbtn);
jf.setVisible(true);
jf.setSize(300, 300);
jf.setLayout(new GridLayout(2, 0));
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf.addActionListener(new testListener());
jbtn.addActionListener(new testListener());
}
public String savedTxt() {
temp = jtf.getText();
System.out.println("Temp is :" + temp);
return temp;
}
public static void main(String[] args) {
new TxtField();
}
}

You are creating a new TxtField when the action is called, instead of referencing the one that invoked the action:
String s = new TxtField().savedTxt();
Try making TxtField itself the ActionListener:
public class TxtField implements ActionListener
Then reference the current instance:
jtf.addActionListener(this);
jbtn.addActionListener(this);
Then reference the JTextField in the current instance:
String s = savedTxt();

You are close...You can do something like this:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Test {
Test t;
static JTextField jtf;
JFrame jf;
JButton jbtn;
static String temp;
public Test() {
t = this;
class testListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s = jtf.getText();
t.savedTxt();
System.out.println("ActionPerformed :" + s);
}
}
jtf = new JTextField(10);
jf = new JFrame("JFrame");
jbtn = new JButton("OK");
jf.add(jtf);
jf.add(jbtn);
jf.setVisible(true);
jf.setSize(300, 300);
jf.setLayout(new GridLayout(2, 0));
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf.addActionListener(new testListener());
jbtn.addActionListener(new testListener());
}
public String savedTxt() {
temp = jtf.getText();
System.out.println("Temp is :" + temp);
return temp;
}
public static void main(String[] args) {
Test t1 = new Test();
}
}
The problem is you are creating a new Instance of your class in the actionPerformed event instead of using the one you already have...
String s = new TxtField().savedTxt();
This is calling savedTxt() on the new instance instead of the one you already have which has the text you typed.

Related

getSelectedIndex() for JList always return -1 eventhough an item is selected

http://prntscr.com/9jhrwa "How the GUI looks"
public class Okno1 extends javax.swing.JFrame {
static Konto[]konto;
static DefaultListModel listModel;
static int indexKonta;
public Okno1() {
initComponents();
napolniKonto();
jScrollPane1.setVisible(false);
button_potrdiKonto.setVisible(false);
}
here I fill my array with Objects and add them to DefaultListModel, also I create a new list with the mentioned DefaultListModel
listModel=new DefaultListModel();
list_konto.setModel(listModel);
konto=new Konto[4];
konto[0]=new Konto("10000/20000", "Test konto primer1");
konto[1]=new Konto("20000/30000", "Test konto primer2");
konto[2]=new Konto("50000/60000", "Test konto primer3");
konto[3]=new Konto("30000/50000", "Test konto primer4");
for (int i = 0; i < konto.length; i++) {
listModel.addElement(konto[i].getID()+" | "+konto[i].getOpis());
}
list_konto=new JList(listModel);
jScrollPane1.repaint();
}
Here I show the jScrollPanel when this button is pressed, I also show the button which must be pressed if I want to get the index of the selected element in the JList displayed
private void button_prikaziKontoActionPerformed(java.awt.event.ActionEvent evt) {
jScrollPane1.setVisible(true);
button_potrdiKonto.setVisible(true);
//revalidate();
//repaint();
}
Here I press a button and it should get me the index of the selected item, but it keeps giving me -1 and it doesn't matter if an item on the JList is selected or is not
private void button_potrdiKontoActionPerformed(java.awt.event.ActionEvent evt) {
//indexKonta=list_konto.getSelectedIndex();
text_opisKonta.setText(Integer.toString(list_konto.getSelectedIndex()));
}
It's not clear where your code is going awry. This compete example may allow you to study the problem in isolation. Also consider adding a ListSelectionListener to see the effect.
myList.addListSelectionListener((ListSelectionEvent e) -> {
myLabel.setText(getSelectionIndex());
});
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
/** #see http://stackoverflow.com/a/34497773/230513 */
public class Test extends JPanel {
private final String[] values = {"Value1", "Value2", "Value3", "Value4"};
private final JList myList = new JList(values);
private final JLabel myLabel = new JLabel();
public Test() {
myList.setSelectedIndex(values.length - 1);
myLabel.setText(getSelectionIndex());
this.add(myList);
this.add(myLabel);
this.add(new JButton(new AbstractAction("Show Selected Index") {
#Override
public void actionPerformed(ActionEvent e) {
myLabel.setText(getSelectionIndex());
}
}));
}
private String getSelectionIndex() {
return String.valueOf(myList.getSelectedIndex());
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Test());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
});
}
}
don't use static variables
always to test if (list.getSelectedIndex() > -1) {
use ListSelectionListener for JList, by always testing if (list.getSelectedIndex() > -1) {
for example (without using ListSelectionListener)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class JListAndSelection {
private JFrame frame = new JFrame();
private DefaultListModel listModel = new DefaultListModel();
private JList list = new JList(listModel);
private JScrollPane scrollPane = new JScrollPane(list);
private JLabel label = new JLabel("nothing is selected");
private JButton button1 = new JButton("print me selected value");
public JListAndSelection() {
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (list.getSelectedIndex() > -1) {
label.setText((String) list.getSelectedValue());
} else {
label.setText("nothing is selected");
}
}
});
listModel.addElement("10000/20000 - Test konto primer1");
listModel.addElement("20000/30000 - Test konto primer2");
listModel.addElement("50000/60000 - Test konto primer3");
listModel.addElement("30000/50000 - Test konto primer4");
list.setVisibleRowCount(5);
frame.setTitle("JFrame");
frame.add(label, BorderLayout.NORTH);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(button1, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new JListAndSelection();
});
}
}

Calling a java class from a parent directory

I have two java classes
SortsGui.java
import javax.swing.*;
import java.awt.*;
import net.miginfocom.swing.MigLayout;
import Sorts.*;
import javax.swing.event.*;
import java.awt.event.*;
public class SortsGui
{
JFrame myMainWindow = new JFrame("Sorts");
JPanel sortPanel = new JPanel();
MyMenuBar mbr = new MyMenuBar();
//first panel components
JTextField txtField = new JTextField();
JTextField txtField2 = new JTextField();
JTextField txtField3 = new JTextField();
JTextField txtField4 = new JTextField();
JTextField txtField5 = new JTextField();
JTextField txtField6 = new JTextField();
JTextField txtField7 = new JTextField();
JTextField txtField8 = new JTextField();
JTextField txtField9 = new JTextField();
String sortsArray[]={"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20"};
JComboBox sortComboBox = new JComboBox(sortsArray);
//end first panel
public void runGUI()
{
myMainWindow.setBounds(10, 10, 800, 800);
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createSortTestPanel();
myMainWindow.getContentPane().add(sortPanel);
myMainWindow.setJMenuBar(mbr);
myMainWindow.setVisible(true);
}
public void createSortTestPanel()
{
MigLayout layout = new MigLayout("" , "[grow]");
sortPanel.setLayout(layout);
sortPanel.add(txtField,"growx");
sortPanel.add(txtField2,"growx");
sortPanel.add(txtField3,"growx");
sortPanel.add(txtField4,"growx");
sortPanel.add(txtField5,"wrap,growx");
sortPanel.add(txtField6,"growx");
sortPanel.add(txtField7,"growx");
sortPanel.add(txtField8,"growx");
sortPanel.add(txtField9,"growx");
selectNothing();
}
public void selectNothing()
{
sortPanel.addAncestorListener(new RequestFocusListener(false));
}
public static void main(String[] args)
{
SortsGui sG = new SortsGui();
sG.runGUI();
}
class RequestFocusListener implements AncestorListener
{
private boolean removeListener;
public RequestFocusListener()
{
this(true);
}
public RequestFocusListener(boolean removeListener)
{
this.removeListener = removeListener;
}
#Override
public void ancestorAdded(AncestorEvent e)
{
JComponent component = e.getComponent();
component.requestFocusInWindow();
if (removeListener)
component.removeAncestorListener( this );
}
#Override
public void ancestorMoved(AncestorEvent e) {}
#Override
public void ancestorRemoved(AncestorEvent e) {}
}
}
MyMenuBar.java
package Sorts;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.io.*;
import java.lang.*;
public class MyMenuBar extends JMenuBar
{
JLabel lblSorts = new JLabel("Select amount of numbers to sort");
String sortsArray[]={"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20"};
JComboBox sortComboBox = new JComboBox(sortsArray);
SortsGui sG= new SortsGui();
public MyMenuBar()
{
setBorderPainted(true);
makePopUpMenu();
}
void makePopUpMenu()
{
add(lblSorts);
sortComboBox.addItemListener(new sortComboBoxChanged());
add(sortComboBox);
}
class sortComboBoxChanged implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
System.out.println(sortComboBox.getSelectedItem());
sG.selectNothing();
System.out.println("Losing Focus");
}
}
}
In this you can see that I have tried to call SortsGui into MyMenuBar however that produces a cannot find symbol error for SortsGui. So is it possible to call a class from a parent directory? And if it is could someone please correct my error?
Parent Directory
Sorts Directory
You need create a new package for SortsGui as it is in the default package and there is ambiguity.
e.g.:
package abc;
class sortGui {
}
Then you have to import the package in Mymenubar
Classes in the default package cannot be imported by classes in packages.

Java JFrame cannot create button(arraylist)

I wanted to create dynamic list of buttons using ArrayList. If I copy the method which is written AddButton in constructor , it works. However, If I run this method in ActionListener, it won't work. How do I resolve this ?
Code:
package HelloJFrame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Main extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextField text1;
public static void main(String[] args) {
// TODO Auto-generated method stub
new Main().setVisible(true);
}
public Main() {
super("Hello JFrame");// Set Title from JFrame constructor
setSize(600, 600);
setResizable(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
text1 = new JTextField(20);
// text.setSize(200, 20);
add(text1);
JButton submit = new JButton("Add Button");
submit.addActionListener(this);
submit.setActionCommand("ekle");
add(submit);
}
#Override
public void actionPerformed(ActionEvent e) {
AddButton(2);
}
public void AddButton(int number) {
ArrayList<JButton> buttons = new ArrayList<JButton>();
for (int i = 0; i < number; i++) {
buttons.add(new JButton("Button #" + i));
}
/*
* JButton button = new JButton("Click!");
* button.addActionListener(this); add(button);
*/
for (int i = 0; i < buttons.size(); i++) {
this.add(buttons.get(i));
}
}
}
After adding all the buttons to the frame you need to add
revalidate();
repaint();
to make sure the layout manager is invoked.
Also, method names should NOT start with an upper case character. "AddButton" should be "addButton".

Void is invalid for the variable main?

How do i fix the error, Void is invalid for the variable main? I tried looking this up online but couldn't find anything. Also I am kind of new to this so please take it easy on me. I am learning as I go.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Text extends JFrame
{
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField("Month",30);
JTextField jt2 = new JTextField("Date",30);
JButton jb = new JButton("Enter");
public Text()
{
public static void main (String[] args); {
setTitle("Tutorial");
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp.add(jt);
jp.add(jt2);
jt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = jt.getText();
jl.setText(input);
}
});
jp.add(jb);
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = jt.getText();
String input2 = jt2.getText();
jl.setText(input);
jl.setText(input2);
int day = Integer.parseInt(input2);
if ((input.equals("Test")) && (input2.equals(day >= 26)))//||(input2.equals("27")))))
JOptionPane.showMessageDialog(null, "" , "" ,JOptionPane.PLAIN_MESSAGE,aries);
}
});
add(jp);
}
}
}
You have placed your main method inside the constructor for class Text. It belongs outside the constructor, at the same level as the constructor. Move it outside the constructor.
public class Text extends JFrame
{
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField("Month",30);
JTextField jt2 = new JTextField("Date",30);
JButton jb = new JButton("Enter");
public static void main (String[] args); {
setTitle("Tutorial");
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
...
}
public Text()
{
...
}
...
}
Java doesnt allow methods to be defined within other methods. Move the main method out of the Text constructor and remove the semi-colon which is terminating the statement early.
In addition you have a number of methods (e.g. setTitle and setVisible) which belong to the JFrame - these need to be moved to an instance code block to make them are accessible.
public class Text extends JFrame {
JPanel jp = new JPanel();
JLabel jl = ...
public Text() {
setTitle("Tutorial");
setVisible(true);
...
add(jp);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Text().setVisible(true);
}
});
}
}
Delete the ; after the main method declaration:
public static void main (String[] args);
^-------- Delete this
And put the main method out of the constructor:
public Text() {
...
}
public static void main(...) {
...
}

How to wait for JOptionPane to be closed before dispatching any more events

I have a couple text fields that I'm tabbing between. On focusLost() I am opening a JOptionPane. I would like the code in focusGained() to be executed AFTER the JOptionPane has been closed. Even though the dialog is modal, focusGained() is being called before the JOptionPane is closed. Is there any way around this?
Found this similar question, but it doesn't seem to have been solved either.
Postpone Event Queue after Focus Lost
Here's a code sample. You'll notice "Focus Gained" is printed before the JOptionPane is closed.
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ShortTest implements FocusListener
{
private void go()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JTextField text1 = new JTextField();
text1.setName("text1");
text1.addFocusListener(this);
JTextField text2 = new JTextField();
text2.setName("text2");
text2.addFocusListener(this);
panel.add(new JLabel("tex1"));
panel.add(text1);
panel.add(new JLabel("text2"));
panel.add(text2);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String [] args)
{
ShortTest test = new ShortTest();
test.go();
}
#Override
public void focusGained(FocusEvent e)
{
if (!e.isTemporary() && (e.getSource() instanceof JTextField))
{
System.out.println("Focus Gained: " + ((JTextField)e.getSource()).getName());
}
}
#Override
public void focusLost(FocusEvent e)
{
if (!e.isTemporary() && (e.getSource() instanceof JTextField))
{
JOptionPane.showOptionDialog(null, ((JTextField)e.getSource()).getName() + " lost focus", "Title", JOptionPane.DEFAULT_OPTION, 0, null, null, null);
}
}
}
Perhaps what you want is not a focus listener (a very low-level construct) but rather an input verifier (a higher level construct). This should respond before the focus has shifted. For example, in the code below the verifier reacts if the user tries to enter non-numeric data into the text field. Yes this can also be done using a DocumentFilter.
import javax.swing.*;
public class VerifierEg extends JPanel {
private static final int FIELD_COUNT = 3;
public VerifierEg() {
InputVerifier inputVerifier = new InputVerifier() {
#Override
public boolean verify(JComponent input) {
final JTextField textField = (JTextField) input;
String text = textField.getText();
for (char c : text.toCharArray()) {
if (!Character.isDigit(c)) {
textField.setText("");
JOptionPane.showMessageDialog(VerifierEg.this, "Text: \""
+ text + "\" must hold only digits", "Text Field Error",
JOptionPane.ERROR_MESSAGE);
return false;
}
}
return true;
}
};
for (int i = 0; i < FIELD_COUNT; i++) {
JTextField field = new JTextField(6);
field.setInputVerifier(inputVerifier);
add(field);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Enter Numbers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new VerifierEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit:
The InputVerifier could work for your purpose, even if you're not verifying the input in any specific way. For example, to modify your code:
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.BoxLayout;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ShortTest2 {
private void go() {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
InputVerifier inputVerifier = new InputVerifier() {
#Override
public boolean verify(JComponent input) {
JOptionPane.showMessageDialog(frame,
"Focus Lost on " + input.getName());
return true;
}
};
FocusListener focusListener = new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
String name = ((JComponent)e.getSource()).getName();
System.out.println("Focus Lost: " + name );
}
#Override
public void focusGained(FocusEvent e) {
String name = ((JComponent)e.getSource()).getName();
System.out.println("Focus Gained: " + name );
}
};
JTextField[] textFields = new JTextField[2];
for (int i = 0; i < textFields.length; i++) {
JTextField textField = new JTextField(10);
String name = "text " + (i + 1);
textField.setName(name);
textField.setInputVerifier(inputVerifier);
textField.addFocusListener(focusListener);
panel.add(new JLabel(name));
panel.add(textField);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ShortTest2 test = new ShortTest2();
test.go();
}
}
1+ for your SSCCE by the way!

Categories

Resources