Replace dot with a space and reverse using java swing [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to display the dot instead of space whenever click on the View-spaces checkbox MenuItem.My problem is when I click the checkbox it is replacing space with dot but,After when I add some extra text to textarea and click on Viewspace JCheckBox menuitem,it had taken the previous text only and replaced.I have Tried this,Please run my code You can easily understand the problem.Please give some suggestions.....Thank you.
Here is my code:
public class VisibleSpaces extends javax.swing.JFrame {
int i=0;
JTextArea tx,lnNum;
JScrollPane scrollpane;
public VisibleSpaces() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Create = new javax.swing.JMenuItem();
ViewSpace = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
Create.setText("Create");
Create.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CreateActionPerformed(evt);
}
});
jMenu1.add(Create);
ViewSpace.setSelected(true);
ViewSpace.setText("ViewSpaces");
ViewSpace.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ViewSpaceActionPerformed(evt);
}
});
jMenu1.add(ViewSpace);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void ViewSpaceActionPerformed(java.awt.event.ActionEvent evt) {
ViewSpace.addItemListener(new ItemListener() {
String str=tx.getText();
String previous=str;
#Override
public void itemStateChanged(ItemEvent ie) {
if(ViewSpace.getState()){
tx.setText(previous.replace(" ","."));
}
else
tx.setText(str);
}
});
}
private void CreateActionPerformed(java.awt.event.ActionEvent evt) {
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
internalFrame.setAutoscrolls(true);
tx=new JTextArea();
tx.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
scrollpane=new JScrollPane(tx);
internalFrame.add(scrollpane);
tp.add(internalFrame);
internalFrame.setSize(internalFrame.getMaximumSize());
internalFrame.pack();
internalFrame.setVisible(true);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VisibleSpaces.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VisibleSpaces.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VisibleSpaces.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VisibleSpaces.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new VisibleSpaces().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Create;
private javax.swing.JCheckBoxMenuItem ViewSpace;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tp;
// End of variables declaration
}

Your code is not proper, its full with bad practice. After a lot of effort I understood your problem. I am just giving the solution of the specific problem, but try to follow the comments given to your question for better understanding of the uses of Java swing components.
Solution:
change this portion of your code
public void itemStateChanged(ItemEvent ie) {
if(ViewSpace.getState()){
tx.setText(previous.replace(" ","."));
}
else
tx.setText(str);
}
with this one
public void itemStateChanged(ItemEvent ie) {
if(ViewSpace.getState()){
tx.setText(tx.getText().replace(" ","."));
}
else
{
String last = tx.getText().substring(tx.getText().length()-1, tx.getText().length());
String rest = tx.getText().substring(0, tx.getText().length()-1);
if(!last.equals("."))
tx.setText(tx.getText().replace("."," "));
else
{
rest=rest.replace("."," ");
tx.setText(rest+".");
}
}

Related

Why this actionEvent on a Java Swing menu item does not work?

I have created a basic JFrame using NetBeans form designer. I have reduced it to just a couple of menu items.
I intend to do something when user clicks on "Open", my understanding is that I have to add an "actionPerformed" through a listener, which can be done using NetBeans Designer.
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("ACTION PERFORMED");
}
But when I click on "Open" nothing happens I can not see the output message.
This is my main routine:
package test.dbviewer;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SealionDBViewer {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel ("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
JFrame databaseViewer = new DatabaseViewer();
databaseViewer.setVisible(true);
}
}
This is the reproducible code that NetBeans generate:
package test.dbviewer;
public class DatabaseViewer extends javax.swing.JFrame {
/**
* Creates new form DatabaseViewer
*/
public DatabaseViewer() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuBar2 = new javax.swing.JMenuBar();
jMenu3 = new javax.swing.JMenu();
jMenu4 = new javax.swing.JMenu();
jMenuItem1.setText("jMenuItem1");
jMenuItem2.setText("jMenuItem2");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu3.setText("Open");
jMenu3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu3ActionPerformed(evt);
}
});
jMenuBar2.add(jMenu3);
jMenu4.setText("Exit");
jMenuBar2.add(jMenu4);
setJMenuBar(jMenuBar2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 267, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("ACTION PERFORMED");
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DatabaseViewer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar jMenuBar2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JSplitPane jSplitPane1;
// End of variables declaration
}

Blank screen integrating JavaFX Scene in Swing using Netbeans

I am not able to understand where my code is wrong. I tried to integrate several example, but the result is that nothing is displayed. In pure JavaFX environment, everything is correct; but in mixed mode, no. The goal is to use the NetBeans designer and integrate existing code with the new one without losing NetBeans facility.
public class VisualizzaFattureXML extends javax.swing.JFrame {
private final JFXPanel fxPanel;
/**
* Creates new form VisualizzaFattureXML
*/
public VisualizzaFattureXML() {
fxPanel = new JFXPanel();
initComponents();
}
private void initFX(JFXPanel fxPanel) {
// This method is invoked on the JavaFX thread
Scene scene = createScene();
fxPanel.setScene(scene);
}
private Scene createScene() {
Group root = new Group();
Scene scene = new Scene(root, Color.ALICEBLUE);
Text text = new Text();
text.setX(40);
text.setY(100);
text.setFont(new Font(25));
text.setText("Welcome JavaFX!");
root.getChildren().add(text);
return (scene);
}
#Override
public void setVisible(boolean t) {
super.setVisible(t);
Platform.runLater(new Runnable() {
#Override
public void run() {
initFX(fxPanel);
}
});
jScrollPane1.add(fxPanel);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setToolTipText("");
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 660, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 449, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(811, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(25, 25, 25))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Platform.runLater(new Runnable() {
#Override
public void run() {
initFX(fxPanel);
jScrollPane1.add(fxPanel);
}
});
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VisualizzaFattureXML.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VisualizzaFattureXML.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VisualizzaFattureXML.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VisualizzaFattureXML.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VisualizzaFattureXML().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
Don't add() the fxPanel to the JScrollPane. Instead, invoke setViewportView():
jScrollPane1.setViewportView(fxPanel);
A complete example may be seen here. Also, don't invoke initFX() in your button handler. Finally, consider the approach outlined here to minimize your reliance on the GUI editor.

Frame closing command _variable

so, my first post.
I study Java. There I got an issue. I want to get a pop.up window open, when attempting to close a window 0 frame.
So, I insert this. From an example code of the teacher.
Check it out please
here it goes
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int reply = JOptionPane.showConfirmDialog(this, "Really close?", "Close?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
this.dispose();
if (reply == JOptionPane.NO_OPTION)
this.setVisible(true);
}
}
It does nothing. no pop up window that gives me what is demanded
Your method most likely won't ever be called. You need to use a WindowListener. Here is how you set it up:
JFrame mainFrame = new JFrame(); //that's your frame
mainFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE) //enable windowlistener handling
mainFrame.addWindowListener(new WindowListener() { //you need to add a windowlistener
#Override
public void windowClosing(WindowEvent e) {
formWindowClosing(e); //call your method
}
#Override
public void windowOpened(WindowEvent e) {}
#Override
public void windowClosed(WindowEvent e) {}
#Override
public void windowIconified(WindowEvent e) {}
#Override
public void windowDeiconified(WindowEvent e) {}
#Override
public void windowActivated(WindowEvent e) {}
#Override
public void windowDeactivated(WindowEvent e) {}
});
This will call your closing method when your program requests to exit.
I use the NetBeans platform.
So my code is as follows:
package my.exercise21;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class Exercise21 extends javax.swing.JFrame {
/**
* Creates new form Exercise21
*/
public Exercise21() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("Exit");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
// TODO add your handling code here:
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int reply = JOptionPane.showConfirmDialog(this, "Really close?", "Close?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
this.dispose();
if (reply == JOptionPane.NO_OPTION)
this.setVisible(true);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Exercise21.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new Exercise21().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
// End of variables declaration
}
I guess my problem lies in not calling the JOptionPane library
I have had just fixed the issue. Thank you for helpful participation and your kind inspiration.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package my.exercise21;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Exercise 2.1");
setCursor(new java.awt.Cursor(java.awt.Cursor.NW_RESIZE_CURSOR));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("Exit");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void formWindowClosed(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {
int r = JOptionPane.showConfirmDialog(this, "Really close?", "Close?", JOptionPane.YES_NO_OPTION);
if (r == JOptionPane.YES_OPTION) {
dispose(); // This closes the program
if (r == JOptionPane.YES_OPTION)
setVisible(false); // This just hides the window but program keeps running.
}// TODO add your handling code here:
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
dispose(); // TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
// End of variables declaration
}

How to sort item in java combobox [duplicate]

This question already has answers here:
How to sort the jComboBox elements in java swing?
(3 answers)
Closed 6 years ago.
I have a java form using JCombobox. There is a "text field", "combobox" and "add" button. When I enter text in the text field, then click Add button, the text in the text field will fill into combobox, but it doesn't sort by a-z.
form screenshot
Below is my code in Add button.
private void cmdAddActionPerformed(java.awt.event.ActionEvent evt) {
if(MyInput.checkText(txtField)){ //MyInput is my own method code to check if the text is entered.
String st=txtField.getText();
combox.addItem(st);
String st1="";
String st2="";
int com=st1.compareTo(st2);
if(com<0){ //I create this string comparison
//I need to add the "sort" code here
}else{
}
}else
JOptionPane.showMessageDialog(this, "Please enter text."); //When no text is entered, this message appears.
}
Full source code:
import PlugIn.MyInput;
import javax.swing.JOptionPane;
public class JCombo extends javax.swing.JFrame {
/**
* Creates new form JCombo
*/
public JCombo() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
txt = new javax.swing.JTextField();
combo = new javax.swing.JComboBox();
cmdAdd = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
txt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtActionPerformed(evt);
}
});
combo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboActionPerformed(evt);
}
});
cmdAdd.setText("Add");
cmdAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdAddActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(88, 88, 88)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt)
.addComponent(combo, 0, 188, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cmdAdd)
.addContainerGap(63, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmdAdd))
.addContainerGap(206, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void txtActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void cmdAddActionPerformed(java.awt.event.ActionEvent evt) {
if(MyInput.checkText(txtField)){ //MyInput is my own method code to check if the text is entered.
String st=txtField.getText();
combox.addItem(st);
String st1="";
String st2="";
int com=st1.compareTo(st2);
if(com<0){ //I create this string comparison
//I need to add the "sort" code here
}else{
}
}else
JOptionPane.showMessageDialog(this, "Please enter text."); //When no text is entered, this message appears.
}
private void comboActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JCombo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton cmdAdd;
private javax.swing.JComboBox combo;
private javax.swing.JTextField txt;
// End of variables declaration
}
Use a SortedComboBoxModel: (How to sort the jComboBox elements in java swing?)
String[] items = { "one", "two", "three" };
SortedComboBoxModel<String> model = new SortedComboBoxModel<String>(items);
JComboBox<String> comboBox = new JComboBox<String>(model);
comboBox.addItem("four");
comboBox.addItem("five");
comboBox.setSelectedItem("one");
You have to take care of the order yourself.
Use getModel() for getting the current list
Figure out where the item should go
Use insertItemAt(E item, int index) to place the item int the correct position.

How do I pass data between cards in Java CardLayout

I am new to working with Java GUI, I know this may sound ridiculous but I have been trying for days to pass data between cards on the CardLayout layout. I am using netbeans, the first card displays a list clients. When a client is selected, the choice selection is passed to a variable on that card. The next card queries the database to show more details about the client selected. I can handle the switching between cards but my problem is I can't pass the data stored in the variable on card 1 to card 2.
I have visited several forums and read through similar questions asked but I just cannot get any of the proposed solutions to work. Please help, I'm new at this so please go easy on me, thanks.
Here is the class that holds the panels
public class mainframe extends javax.swing.JFrame {
public mainframe() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
displayScrollPane = new javax.swing.JScrollPane();
displaypanel = new javax.swing.JPanel();
viewclientspanel1 = new viewclientspanel();
addclientpanel1 = new addclientpanel();
clientdetails1 = new clientdetails();
mainmenu = new javax.swing.JMenuBar();
clients = new javax.swing.JMenu();
viewclients = new javax.swing.JMenuItem();
addclient = new javax.swing.JMenuItem();
transactions = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
displaypanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
displaypanel.setLayout(new java.awt.CardLayout());
viewclientspanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
viewclientspanel1MouseClicked(evt);
}
});
displaypanel.add(viewclientspanel1, "viewclientscard");
displaypanel.add(addclientpanel1, "addclientcard");
displaypanel.add(clientdetails1, "clientdetailscard");
displayScrollPane.setViewportView(displaypanel);
clients.setText("Clients");
viewclients.setText("View Clients");
viewclients.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewclientsActionPerformed(evt);
}
});
clients.add(viewclients);
viewclients.getAccessibleContext().setAccessibleParent(mainmenu);
addclient.setText("Add Client");
addclient.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addclientActionPerformed(evt);
}
});
clients.add(addclient);
mainmenu.add(clients);
transactions.setText("Transactions");
mainmenu.add(transactions);
setJMenuBar(mainmenu);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(displayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 1059, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(99, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(66, Short.MAX_VALUE)
.addComponent(displayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 570, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33))
);
pack();
}// </editor-fold>
private void addclientActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) displaypanel.getLayout();
card.show(displaypanel, "addclientcard");
}
private void viewclientsActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) displaypanel.getLayout();
card.show(displaypanel, "viewclientscard");
}
private void viewclientspanel1MouseClicked(java.awt.event.MouseEvent evt) {
//viewclientspanel1.getComponentListeners();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new mainframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem addclient;
private addclientpanel addclientpanel1;
private clientdetails clientdetails1;
private javax.swing.JMenu clients;
private javax.swing.JScrollPane displayScrollPane;
private javax.swing.JPanel displaypanel;
private javax.swing.JMenuBar mainmenu;
private javax.swing.JMenu transactions;
private javax.swing.JMenuItem viewclients;
private viewclientspanel viewclientspanel1;
// End of variables declaration
}
The class of the card that displays a list of the clients to choose from has a mouse event listener which gets the value of the client selected and switches the the next card
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
CardLayout card = (CardLayout) jPanel1.getParent().getParent().getParent().getParent().getLayout();
card.show(jPanel1.getParent().getParent().getParent().getParent(), "clientdetailscard");
}
Lastly the class that I need to transfer the client selected information to which dsiplays the more details.
public class clientdetails extends javax.swing.JPanel {
public clientdetails() {
initComponents();
}
public static void main(String [] args) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
JFrame f = new JFrame("Window");
f.add(new clientdetails());
f.setSize(500, 700);
f.setVisible(true);
}
private javax.swing.JPanel jPanel1;
}
You could pass the client information from one pane to the other using setters/getters...
clientDetailsPane.setClient(clientListPanel.getClient());
// Switch panels...
I was also thinking that you could use some kind of model or Map, but that is probably overkill for what you want to achieve...
Thanks a lot guys, I ended up using a class container to hold the variables I need transferred.
public class varcontainer {
public String variablename;
private static varcontainer instance = null;
public static varcontainer getInstance(){
if(instance == null){
instance = new varcontainer();
}
return instance;
}
}
I then call the getInstance from another class to get the current instance of the container and access the variables
varcontainer.getInstance().variablename
Thanks again for the feedback, I appreciate it.

Categories