Appear automatically JTextField - java

Please, how can I appear automatically some JTextField from what user choose in JComboBox ?
My example is simple. I have a JComboBox in my box with some operation. And depending on what the user choose from this JComboBox, I appear one or more JTextField.
I have this code:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CalculatriceFenetre fenetre = new CalculatriceFenetre();
fenetre.setVisible(true);
}
});
}
.
public class CalculatriceFenetre extends JFrame {
private JTextField field1, field2;
private JComboBox liste;
public CalculatriceFenetre() {
super();
build();
}
private void build() {
setTitle("Calculatrice");
setSize(400, 200);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(buildContentPane());
}
private JPanel buildContentPane() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setBackground(Color.white);
field1 = new JTextField();
field1.setColumns(10);
field2 = new JTextField();
field2.setColumns(10);
field2.setVisible(false);
panel.add(field1);
panel.add(field2);
liste = new JComboBox(new OperateursModel());
liste.addActionListener(new CustomActionListener());
panel.add(liste);
return panel;
}
class CustomActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (liste.getSelectedItem().equals("op1")) {
field2.setVisible(true);
}
}
}
.
public class OperateursModel extends DefaultComboBoxModel {
private ArrayList<String> operateurs;
public OperateursModel(){
super();
operateurs = new ArrayList<String>();
operateurs.add("op1");
}
public String getSelectedOperateur(){
return (String)getSelectedItem();
}
#Override
public Object getElementAt(int index) {
return operateurs.get(index);
}
#Override
public int getSize() {
return operateurs.size();
}
#Override
public int getIndexOf(Object element) {
return operateurs.indexOf(element);
}
}

And depending on what the user choose from this JComboBox, I appear one or more JTextField.
Then you can write an ActionListener to handle the selection of an item from the combo box.
You can start by reading the section from the Swing tutorial on How to Use a Combo Box for a working example that uses an ActionListener.
In your case you want to add a text field to the frame so the code would be something like:
JTextField textField = new JTextField(10);
frame.add( textField );
frame.revalidate();
frame.repaint();
Also, there is no need for you to create a custom ComboBoxModel. You can just add items to the default model. Again, the tutorial will show you how to do this.

Like I mentioned, this is an easy approach for your question. Create all the JTextFields you need first and toggle its visibility instead of removing and adding it on run time.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DynamicTextFieldsApp
{
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("JTextField Toggler");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.add(new DisplayPanel());
f.pack();
f.setLocationRelativeTo(null);
}});
}
}
A simple JPanel with comboBox and several JTextFields.
class DisplayPanel extends JPanel
{
public static final int PLAYERS = 5;
private JComboBox cmbPlayerNumber;
private JTextField[] txtPlayerName;
private JLabel lblPlayerNumber;
public DisplayPanel(){
setPreferredSize(new Dimension(170, 240));
createComponents();
initComponents();
loadComponents();
setBoundsForComponents();
}
private void createComponents(){
cmbPlayerNumber = new JComboBox(new String[]{"1", "2", "3", "4", "5"});
txtPlayerName = new JTextField[PLAYERS];
lblPlayerNumber = new JLabel("Num of Players");
}
private void initComponents(){
for(int x=0; x<PLAYERS; x++){
txtPlayerName[x] = new JTextField("No Name " + (x+1));
txtPlayerName[x].setVisible(false);
}
cmbPlayerNumber.setSelectedIndex(-1);
cmbPlayerNumber.addActionListener(new CmbListener());
}
private void loadComponents(){
add(cmbPlayerNumber);
add(lblPlayerNumber);
for(int x=0; x<PLAYERS; x++)
add(txtPlayerName[x]);
}
private void setBoundsForComponents(){
setLayout(null);
lblPlayerNumber.setBounds(10, 0, 150, 30);
cmbPlayerNumber.setBounds(10, 30, 150, 30);
for(int x=0; x<PLAYERS; x++)
txtPlayerName[x].setBounds(10, (30*x)+70, 150, 30);
}
private class CmbListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int numOfPlayers = cmbPlayerNumber.getSelectedIndex() + 1;
for(int x=0; x<numOfPlayers; x++)
txtPlayerName[x].setVisible(true);
for(int x=numOfPlayers; x<PLAYERS; x++){
txtPlayerName[x].setVisible(false);
txtPlayerName[x].setText("No name " + (x+1));
}
}
}
}
And of course, you can work with some layout manager instead of null layout.

Related

How to add parameter in mouselistener

I want to make the JLabel answer print out the answer when users press the label. But I found line 104 does not use the "input" from HanoisFrames. It keeps using 0 as "input" and prints out "0". I tried to write line 96 as
"private class MouseHandler extends HanoisFrames implements MouseListener, MouseMotionListener" and I used "super (int)" but it does not work. What should I do?
package Hanois;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Hanoi {
private JFrame frame;
JButton[][] buttons= new JButton[3][3];
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Hanoi window = new Hanoi();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Hanoi() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 901, 696);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar=new JMenuBar();//Menu
frame.setJMenuBar(menubar);
JMenu file= new JMenu("File");
file.setFont(new Font("Segoe UI", Font.PLAIN, 21));
menubar.add(file);
JMenuItem exit= new JMenuItem("Exit");//provide users a way to exit
exit.setFont(new Font("Segoe UI", Font.PLAIN, 21));
file.add(exit);
class exitaction implements ActionListener{
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new exitaction());
JPanel panelone = new JPanel();
frame.getContentPane().add(panelone, BorderLayout.CENTER);
panelone.setBackground(Color.WHITE);
panelone.setLayout(new GridLayout(3,4,3,3));
JPanel paneltwo = new JPanel();
frame.getContentPane().add(paneltwo, BorderLayout.NORTH);
paneltwo.setBackground(Color.WHITE);
JLabel lblFunHanoiTower = new JLabel("Fun Hanoi Tower");
frame.getContentPane().add(paneltwo, BorderLayout.NORTH);
lblFunHanoiTower.setForeground(Color.BLACK);
lblFunHanoiTower.setBackground(SystemColor.activeCaption);
lblFunHanoiTower.setFont(new Font("Viner Hand ITC", Font.PLAIN, 36));
paneltwo.add(lblFunHanoiTower);
ActionListener listener =new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int row = 0; row < buttons.length ; row++) {
for(int col= 0; col < buttons[0].length ;col++) {
if(e.getSource()==buttons[row][col]){
buttons[row][col].setBackground(Color.lightGray);
HanoisFrames f= new HanoisFrames(((row*3)+(col+3)));
f.setVisible(true);//
}
}
}
}
};
for(int row = 0; row < buttons.length ; row++) {
for(int col= 0; col < buttons[0].length ;col++) {
buttons[row][col] = new JButton("level "+String.valueOf((row*3)+(col+3)-2));
buttons[row][col].setFont(new Font("Tempus Sans ITC", Font.BOLD, 32));
buttons[row][col].setBackground(SystemColor.controlHighlight);
buttons[row][col].setSize(6, 6);
buttons[row][col].addActionListener(listener);
panelone.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panelone.add(buttons[row][col]);
}
}
}
}
package Hanois;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class HanoisFrames extends JFrame {
private JPanel contentPane;
private JButton ret ;
private JButton next;
private JButton last;
private JLabel answer;
private JMenu menu;
private JButton reset;
private JLabel move;
private JPanel panel;
static int input;
private JLabel lblLevel;
boolean showAnswer=false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HanoisFrames frame = new HanoisFrames(input);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public HanoisFrames(int input) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 901, 696);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
MouseHandler handler=new MouseHandler();
panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
panel.setLayout(new GridLayout(2,3));
move = new JLabel(" Move");
panel.add(move);
reset = new JButton("Reset");
panel.add(reset);
answer = new JLabel();
answer.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(answer);
answer.setText("Answer");
answer.addMouseListener(handler);
answer.addMouseMotionListener(handler);
last = new JButton("Last");
panel.add(last);
ret = new JButton("Return");
panel.add(ret);
next = new JButton("Next");
panel.add(next);
lblLevel = new JLabel("LEVEL "+ String.valueOf(input-2));
lblLevel.setHorizontalAlignment(SwingConstants.CENTER);
lblLevel.setFont(new Font("Viner Hand ITC", Font.PLAIN, 36));
contentPane.add(lblLevel, BorderLayout.NORTH);
}
public int hanoiCalculator(int input) {
if (input==0){
return 0;
}else if (input==1){
return 1;
}else{
return 2*(hanoiCalculator(input-1)+1)-1;
}
}
private class MouseHandler implements MouseListener,MouseMotionListener {
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
answer.setText("Answer: "+String.valueOf(hanoiCalculator(input)).toString());
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent e) {
answer.setText("Answer: ");
}
}
}
Here:
public class HanoisFrames extends JFrame {
private JPanel contentPane;
// ...
private JPanel panel;
static int input;
You never set your input value in your HanoiFrames constructor, and so it remains the default value for an int field, 0. But even if you did set the field because it's a static field, any changes made to it in any HanoiFrames class will change the value in all HanoiFrames classes, and so it cannot be a static field.
So, change input declaration to non-static:
public class HanoisFrames extends JFrame {
private JPanel contentPane;
private JButton ret;
//.....
private JPanel panel;
private int input; // private non-static field now
and set it in the constructor:
public HanoisFrames(int input) {
this.input = input;
This way each HanoisFrames will have a unique and durable input value
Side Recommendation:
I would advise against creating and then swapping a bunch of JFrames. Instead gear your code towards creating JPanels, and then swap them when needed, using a CardLayout.

Closing and reopeing of frame happens with increasing frequency each a button is pressed a single time

I am using a self made toolbar to navigate through my application and the toolbar is present on all pages. Each time a new page is displayed I am closing the current frame and opening a new one, using the following code:
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
I am doing it this way as the ActionListeners are declared in the toolbar class, whilst the frames for each page are declared at runtime and are not static.
This all works fine except for one particular case-the "cancel" button, where the first time the frame is accessed it will close once. The second time it will close and re open 2 times, the third 3 and so on. I have tracked this using the "counter" in the code.
I have minimised the code to recreate the same behaviour, as below:
Toolbar Class
public class Toolbar {
static JButton buttonCancel = new JButton("Cancel");
static int counter;
public static JPanel Toolbar(String panelname){
FlowLayout layout = new FlowLayout();
JPanel Toolbar = new JPanel(new BorderLayout());
Toolbar.setLayout(layout);
GridLayout GLayout = new GridLayout(2,1);
GLayout.setVgap(0);
JPanel container2 = new JPanel();
if(panelname.matches("Customers")){
container2.setLayout(GLayout);
JButton buttonAddCust = new JButton("Add Cust");
container2.add(buttonAddCust, BorderLayout.PAGE_START);
buttonAddCust.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
Customers.AddCustomersGui();
}
});
}
JPanel container21 = new JPanel();
if(panelname.matches("Add Customers")){
container21.setLayout(GLayout);
container21.add(buttonCancel, BorderLayout.PAGE_START);
buttonCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter ++;
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
System.out.println("Coutner " + counter);
Customers.CustomersGui();
}
});
}
Toolbar.add(container2);
Toolbar.add(container21);
return Toolbar;
}
}
GUI class
public class Customers extends Toolbar{
public static void CustomersGui(){
final JFrame frame = new JFrame("Customers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel customers = new JPanel();
customers.add(Toolbar.Toolbar(frame.getTitle()));
frame.setContentPane(customers);
frame.setSize(1200,500);
frame.setVisible(true);
}
public static void AddCustomersGui(){
final JFrame frame1 = new JFrame("Add Customers");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel Addcustomers = new JPanel();
Addcustomers.add(Toolbar.Toolbar(frame1.getTitle()));
frame1.setContentPane(Addcustomers);
frame1.setSize(1200,500);
frame1.setVisible(true);
}
}
main class
public static void main(String[] args) {
Customers.CustomersGui();
}
You are adding a new ActionListener to the buttonCancel, with each iteration of your code and this is the reason for your program's behavior.
Also, as per my comment, you state,
Each time a new page is displayed I am closing the current frame and opening a new one.
A better design is probably not to swap windows which can be annoying, but rather to swap JPanel views using a CardLayout. Please read The Use of Multiple JFrames, Good/Bad Practice?.
For example, add this line of code to your program:
if (panelname.matches("Add Customers")) {
container21.setLayout(GLayout);
container21.add(buttonCancel, BorderLayout.PAGE_START);
buttonCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
java.awt.Window win[] = java.awt.Window.getWindows();
for (int i = 0; i < win.length; i++) {
win[i].dispose();
}
System.out.println("Coutner " + counter);
Customers.CustomersGui();
}
});
// ***** add this here **********
System.out.println("buttonCancel ActionListener count: "
+ buttonCancel.getListeners(ActionListener.class).length);
}
and you'll see that the ActionListeners get added multiple times to this button.
An example of swapping views:
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwapPanels extends JPanel {
public static final String CUSTOMER = "customer";
public static final String ADD_CUSTOMER = "Add Customer";
protected static final int PREF_W = 800;
protected static final int PREF_H = 600;
public static final String CANCEL = "Cancel";
private CardLayout cardLayout = new CardLayout();
public SwapPanels() {
setLayout(cardLayout);
add(createCustomerPanel(CUSTOMER), CUSTOMER);
add(createAddCustomerPanel(ADD_CUSTOMER), ADD_CUSTOMER);
}
public void showCard(String key) {
cardLayout.show(this, key);
}
public JPanel createAddCustomerPanel(String name) {
JPanel addCustPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
addCustPanel.setName(name);
addCustPanel.setBorder(BorderFactory.createTitledBorder(name));
addCustPanel.add(new JButton(new AbstractAction(CANCEL) {
{
int mnemonic = (int)getValue(NAME).toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (CANCEL.equals(e.getActionCommand())) {
SwapPanels.this.showCard(CUSTOMER);
}
}
}));
return addCustPanel;
}
private JPanel createCustomerPanel(String name) {
JPanel custPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
custPanel.setName(name);
custPanel.setBorder(BorderFactory.createTitledBorder(name));
custPanel.add(new JButton(new AbstractAction(ADD_CUSTOMER) {
{
int mnemonic = (int)getValue(NAME).toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (ADD_CUSTOMER.equals(e.getActionCommand())) {
SwapPanels.this.showCard(ADD_CUSTOMER);
}
}
}));
return custPanel;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SwapPanels");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SwapPanels());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Java Swing: Get text value from JOptionPane

I'd like to create a new window which is used in POS system. The user input is for an amount of money the customer has and the window has to display the exchange amount. I'm new with JOptionPane feature (I have been using JAVAFX and it's different).
This is my code:
public static void main(String[] argv) throws Exception {
String newline = System.getProperty("line.separator");
int cost = 100;
int amount = Integer.parseInt(JOptionPane.getText()) // this is wrong! This needs to come from user input box in the same window.
JFrame frame = new JFrame();
String message = "Enter the amount of money"+newline+"The exchange money is: "+amount-cost;
String text = JOptionPane.showInputDialog(frame, message);
if (text == null) {
// User clicked cancel
}
Is there any suggestion?
use InputDialog for get userinput
public static void main(String[] argv) throws Exception {
//JFrame frame = new JFrame();
//frame.setVisible(true);
int cost = 100;
JLabel l=new JLabel("The exchange money is");
JPanel p=new JPanel(new GridLayout(1, 2, 10, 10));
p.setPreferredSize(new Dimension(400, 50));
JTextField t=new JTextField("Enter the amount of money");
t.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
try{
int amount=Integer.parseInt(t.getText());
l.setText("The exchange money is: \n" + (amount - cost));
}catch(Exception ex){
// ex.printStackTrace();
}
}
});
p.add(t);
p.add(l);
int option = JOptionPane.showConfirmDialog(null,p,"JOptionPane Example : ",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(option==0){
System.out.println("ok clicked");
}else{
System.out.println("cancel clicked");
}
}
What you need to do, is to create your own custom JOptionPane, that has it's own components, instead of using the build in one's.
Place a JTextField in it, and add a DocumentListener to that, so that when you change something on it, it can be reciprocated on to the status label, as need be.
Try this small example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JOptionPaneExample {
private JLabel label;
private JTextField tfield;
private JLabel statusLabel;
private static final int GAP = 5;
private void displayGUI() {
JOptionPane.showMessageDialog(null, getPanel());
}
private JPanel getPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1));
label = new JLabel("Enter something: ", JLabel.CENTER);
tfield = new JTextField(10);
tfield.getDocument().addDocumentListener(new MyDocumentListener());
JPanel controlPanel = new JPanel();
controlPanel.add(label);
controlPanel.add(tfield);
panel.add(controlPanel);
statusLabel = new JLabel("", JLabel.CENTER);
panel.add(statusLabel);
return panel;
}
private class MyDocumentListener implements DocumentListener {
#Override
public void changedUpdate(DocumentEvent de) {
updateStatus();
}
#Override
public void insertUpdate(DocumentEvent de) {
updateStatus();
}
#Override
public void removeUpdate(DocumentEvent de) {
updateStatus();
}
private void updateStatus() {
statusLabel.setText(tfield.getText());
}
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new JOptionPaneExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
Try using this:
if( myJOptionPane.getValue() instanceOf String){
String myString = (String) myJOptionPane.getValue();
}
Then use the result of myString to do whatever you intend to do.

How can i pass the data from one JPanel to other...?

I have a JFrame which contains 3 JPanels. I want to pass the JTextField value of one panel to other. Each panel is shown using JTabbedPane. I am getting null when i access the value of other text field. How can i access?
You don't show any code, and so it's impossible to know why you're getting "null" values. Two possible solutions if you want all three JPanels to hold JTextFields with the same content:
Put the shared JTextField outside of the JPanels held by the JTabbedPane and instead in a JPanel that holds the JTabbedPane, so that the field is always visible no matter what tab is displayed, or
Use several JTextFields but have them share the same Document or "model".
e.g.,
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.text.PlainDocument;
public class SharedField extends JTabbedPane {
private static final int TAB_COUNT = 5;
private static final int MY_WIDTH = 600;
private static final int MY_HEIGHT = 300;
PlainDocument doc = new PlainDocument();
public SharedField() {
for (int i = 0; i < TAB_COUNT; i++) {
JTextField tField = new JTextField(10);
tField.setDocument(doc);
JPanel panel = new JPanel();
panel.add(tField);
add("Panel " + i, panel);
// to demonstrate some of the JTextFields acting like
// a label
if (i % 2 == 1) { // if i is odd
tField.setEditable(false);
tField.setBorder(null);
}
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(MY_WIDTH, MY_HEIGHT);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("SharedField");
frame.getContentPane().add(new SharedField());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Edit 1
I see that you've cross-posted this on java-forums.org/ where you show some of your code:
pacage Demotool;
Class:MainFrame
This is the actionPerformed code of first panel
both str and scrTxt is (public static)
public void actionPerformed(ActionEvent e)
{
String act=e.getActionCommand();
if(act.equals("ADD"))
{
str=scrnTxt.getText();
System.out.println("Hi :"+str);
Demotool.DemoTool.jtp.setSelectedIndex(1);
}
}
using the belove code i tried to access the data but I am getting null String:
System.out.println("Hello:"+Demotool.MainFrame.str);
Problems:
Don't use static variables or methods unless you have a good reason to do so. Here you don't.
You're may be trying to access the MainFrame.str variable before anything has been put into it, making it null, or you are creating a new MainFrame object in your second class, one that isn't displayed, and thus one whose str variable is empty or null -- hard to say.
Either way, this design is not good. You're better off showing us a small demo program that shows your problem with code that compiles and runs, an sscce, so we can play with and modify your code and better be able to show you a decent solution.
One such decent solution is to add a DocumentListener to the JTextField so that changes to the text held by the JTextField are "pushed" into the observers that are listening for changes (your other classes).
For example, using DocumentListeners:
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
public class SharedField2 extends JTabbedPane {
private static final int LABEL_PANEL_COUNT = 4;
private static final int MY_WIDTH = 600;
private static final int MY_HEIGHT = 300;
public SharedField2() {
TextFieldPanel tfPanel = new TextFieldPanel();
LabelPanel[] labelPanels = new LabelPanel[LABEL_PANEL_COUNT];
add("TextFieldPanel", tfPanel);
for (int i = 0; i < labelPanels.length; i++) {
labelPanels[i] = new LabelPanel();
// add each label panel's listener to the text field
tfPanel.addDocumentListenerToField(labelPanels[i].getDocumentListener());
add("Label Panel " + i, labelPanels[i]);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(MY_WIDTH, MY_HEIGHT);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("SharedField2");
frame.getContentPane().add(new SharedField2());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class TextFieldPanel extends JPanel {
private JTextField tField = new JTextField(10);
public TextFieldPanel() {
add(tField);
}
public void addDocumentListenerToField(DocumentListener listener) {
tField.getDocument().addDocumentListener(listener);
}
}
class LabelPanel extends JPanel {
private DocumentListener myListener;
private JLabel label = new JLabel();
public LabelPanel() {
add(label);
myListener = new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
updateLabel(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLabel(e);
}
private void updateLabel(DocumentEvent e) {
try {
label.setText(e.getDocument().getText(0,
e.getDocument().getLength()));
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
};
}
public DocumentListener getDocumentListener() {
return myListener;
}
}
One simple solution will be making JTextField global so all panel can access it.
Make sure all your panel can access JTextField that is textField is globally accessible.
Following code demonstrate this:
JTextField textField = new JTextField(25);
JLabel labelForPanel2 = new JLabel(),labelForPanel3 = new JLabel();
private void panelDemo() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", panel1);
tabbedPane.addTab("Tab 2", panel2);
tabbedPane.addTab("Tab 3", panel3);
panel1.add(textField);
panel2.add(labelForPanel2);
panel3.add(labelForPanel3);
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
labelForPanel2.setText(textField.getText());
labelForPanel3.setText(textField.getText());
}
});
frame.add(tabbedPane);
frame.setVisible(true);
}
I don't know what exactly are you going to achieve, but maybe try data binding?
Take a look at BetterBeansBinding library.

Problem with reusing the JScrollPane again for different custom Lists

I am trying to create a JScrollPane component which can be reused depending upon the string parameter that is being passed..
I have created the following code, it works if I use JFrame to embed the JScrollPane inside it,
but when I try to reuse the code in creating different JScrollPane the scrollPane is not displayed at all..
I am implementing it in a java swing project..
Please let me know what should be done in this..any suggestions are highly appreciated.
The same problem I have with regards to the JComboBox, it doesn't display...
public class ListComponent extends JScrollPane {
private String[] selectedNames;
private String[] listNames;
private JButton submit, reset;
private JPanel subPanel = new JPanel();
private JList list;
private JScrollPane scroll;
public String getFirstSelectionInList() {
return selectedNames[0];
}
ListComponent() {
/*submit = new JButton("Submit");
reset = new JButton("Reset");*/
subPanel.setLayout(new FlowLayout());
/*subPanel.add(submit);
subPanel.add(reset);*/
}
ListComponent(String[] listNames) {
this();
/*JFrame frame = new JFrame("Creating a JList Component");*/
this.listNames = new String[listNames.length];
this.listNames = listNames;
//this.setLayout(new BorderLayout());
//this.setLayout(new ScrollPaneLayout());
JPanel panel = new JPanel();
list = new JList(listNames);
scroll = new JScrollPane(list);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
/*panel.add(scroll);
panel.add(subPanel,BorderLayout.SOUTH);*/
/*frame.add(panel);
frame.pack();
frame.setVisible(true);*/
this.setVisible(true);
list.addListSelectionListener(listSelectionListener);
}
ListSelectionListener listSelectionListener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent listSelectionEvent) {
boolean adjust = listSelectionEvent.getValueIsAdjusting();
//System.out.println(", Adjusting? " + adjust);
if (!adjust) {
JList list = (JList) listSelectionEvent.getSource();
int selections[] = list.getSelectedIndices();
Object selectionValues[] = list.getSelectedValues();
int n = selections.length;
selectedNames = new String[n];
for (int i = 0; i < n; i++) {
if (i == 0) {
System.out.print(" Selections: ");
}
selectedNames[i] = (String) selectionValues[i];
System.out.print(selectedNames[i]
+ "/" + selectionValues[i]);
}
}
}
};
/** #return the selectedNames */
public String[] getSelectedNames() {
return selectedNames;
}
/** #param selectedNames the selectedNames to set */
public void setSelectedNames(String[] selectedNames) {
this.selectedNames = selectedNames;
}
public static void main(String args[]) {
String subject[] = {"Math", "Computer", "Phisics", "Chemestry"};
new ListComponent(subject);
}
}
#camickr is correct; JPanel is a better "general-purpose container for lightweight components." You can add additional components to the other areas of the BorderLayout used in the example below. It's also a good habit to build your GUI on the event dispatch thread.
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.event.*;
/** #see http://stackoverflow.com/questions/4176343 */
public class ListPanel extends JPanel {
private JList list;
public ListPanel(String[] data) {
super(new BorderLayout());
list = new JList(data);
list.addListSelectionListener(new SelectionHandler());
JScrollPane jsp = new JScrollPane(list);
this.add(jsp, BorderLayout.CENTER);
}
private class SelectionHandler implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println(Arrays.toString(list.getSelectedValues()));
}
}
}
private void display() {
JFrame f = new JFrame("ListPanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
String[] data = {"Math", "Computer", "Physics", "Chemistry"};
new ListPanel(data).display();
}
});
}
}
public class ListComponent extends JScrollPane
What? You should not be extending a JScrollPane. You are not adding new functionality to the scroll pane.
If you are trying to add a JList to a JScrollPane, then I suggest you read the JList API and follow the link to the Swing tutorial on "How to Use Lists" for a working example.

Categories

Resources