Related
I am trying to do a simple Jform and call it from another class.
I want to use this Jframe in a server client application, but I don't know how to open the JFrame class from another class.
Like user has to chose
1- to open Jframe.
2- To Exit.
So What am I doing wrong?
Below are the codes:
Jframe Class named Calculas.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author user
*/
public class Calculas extends javax.swing.JFrame {
/**
* Creates new form Calculas
*/
public Calculas() {
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() {
a1Text = new javax.swing.JTextField();
a2Text = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
answer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
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(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60)
.addComponent(jLabel1)
.addGap(34, 34, 34)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int a;
a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
answer.setText("Answer" + a);
// 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(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculas.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 Calculas().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField a1Text;
private javax.swing.JTextField a2Text;
private javax.swing.JLabel answer;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Test Class named Test.java
public class Test extends JFrame {
public static void main(String args[])
{
Calculas CAL = new Calculas();
CAL.Calculus();
}
}
Forgive me if this is naive, as Im not anything of a Java programmer...
But isnt it just because you need to set visible?
Calculas CAL = new Calculas();
CAL.setVisible(true);
The constructor of Calculas doesn't show (setVisible) the frame.
If you want to interact with the Calculas class in this manner, you should also be calling CAL.setVisible(true)
Also, by convention, all Java instance variables, should start with a lower case character and use camelCase conventions
In it's current form of your code, you can call the main method of your Calculas class in Test class or move the code to the Test class.
Warning: Extending JFrame is not a good Idea.
First alternative: You don't need to extend JFrame in Test
public class Test{
public static void main(String args[])
{
Calculas.main(new String[0]);
}
}
You haven't mentioned in your question how you want to be able to chose close or open, in console or in another JFrame or something...
Second Alternative:
But If I were you I could do something like this: wrap the code for look and feel in a separate method and call this from Test' s main.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author user
*/
public class Calculas extends javax.swing.JFrame {
/**
* Creates new form Calculas
*/
public Calculas() {
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() {
a1Text = new javax.swing.JTextField();
a2Text = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
answer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
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(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60)
.addComponent(jLabel1)
.addGap(34, 34, 34)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int a;
a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
answer.setText("Answer" + a);
// TODO add your handling code here:
}
public static setNimbusFeel(){
/* 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(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
// Variables declaration - do not modify
private javax.swing.JTextField a1Text;
private javax.swing.JTextField a2Text;
private javax.swing.JLabel answer;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
And test class like this:
public class Test{
public static void main(String args[])
{
Calculas cal=new Calculas();
//</editor-fold>
Calculas.setNimbusFeel();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Calculas().setVisible(true);
}
});
}
}
Like this:
Here's an example of a basic structure you can use:
import java.awt.*;
import javax.swing.*;
class MyGui {
private JFrame window = new JFrame("This is the title");
public MyGui() {
initComponents();
window.setBounds(100, 50, 600, 400); //location, size
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void initComponents() {
Container cp = window.getContentPane();
cp.setLayout(new FlowLayout() );
cp.add(new JLabel("Hello world") );
}
}
public class MyProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
And in separate files:
MyGui.java
import java.awt.*;
import javax.swing.*;
public class MyGui {
private JFrame window = new JFrame("This is the title");
public MyGui() {
initComponents();
window.setBounds(100, 50, 600, 400); //location, size
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void initComponents() {
Container cp = window.getContentPane();
cp.setLayout(new FlowLayout() );
cp.add(new JLabel("Hello world") );
}
}
MyProg.java
import javax.swing.*;
public class MyProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Calculas CAL = new Calculas();
CAL.Calculus();
maybe, CAL.Calculas(); I dont know java but I realized that, sorry about my english:)
This is a simple code to clarify my question:
this is the main class from where I declared the two panels.
/*
* 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.
*/
/**
*
* #author sakib
*/
public class MainPane {
private JPanel contentPane;
private Firstcard1 p1;
private SecondCard1 p2;
public void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
//a=S1;
contentPane.setLayout(new CardLayout());
p1 = new Firstcard1(contentPane);
p2 = new SecondCard1(contentPane);
contentPane.add(p1, "Panel 1");
contentPane.add(p2, "Panel 2");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new MainPane().displayGUI();
}
}
);
}
}
this is the first card:
public class Firstcard1 extends javax.swing.JPanel {
private JPanel contentpane;
/**
* Creates new form Firstcard1
*/
public Firstcard1(JPanel cp) {
this.contentpane=cp;
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() {
jTextField1 = new javax.swing.JTextField();
Login = new javax.swing.JButton();
Login.setText("Login");
Login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(Login)))
.addContainerGap(145, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(105, 105, 105)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Login)
.addContainerGap(134, Short.MAX_VALUE))
);
}// </editor-fold>
private void LoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardLayout layout = (CardLayout)contentpane.getLayout();
layout.show(contentpane, "Panel 2");
}
// Variables declaration - do not modify
private javax.swing.JButton Login;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
this is the second card:
public class SecondCard1 extends javax.swing.JPanel {
private JPanel contentpane;
/**
* Creates new form SecondCard1
*/
public SecondCard1(JPanel cp) {
this.contentpane=cp;
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() {
jTextField1 = new javax.swing.JTextField();
back = new javax.swing.JButton();
back.setText("Back");
back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(127, 127, 127)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(157, 157, 157)
.addComponent(back)))
.addContainerGap(137, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(121, 121, 121)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(back)
.addContainerGap(102, Short.MAX_VALUE))
);
}// </editor-fold>
private void backActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardLayout layout = (CardLayout)contentpane.getLayout();
layout.show(contentpane, "Panel 1");
}
// Variables declaration - do not modify
private javax.swing.JButton back;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
My question is.if I put a value in the textarea of the first card and press the login button.the value will appear in the text area of the second card.how can i do it?
You somehow have to pass a reference of the second panel to the first one:
Main class:
public class MainPane
{
public void displayGUI()
{
....
p1 = new Firstcard1(contentPane);
p2 = new SecondCard1(contentPane);
p1.setSecondCard(p2);
....
}
}
First card:
public class Firstcard1 extends javax.swing.JPanel {
....
private SecondCard secondCard;
void setSecondCard(SecondCard secondCard)
{
this.secondCard = secondCard;
}
....
private void LoginActionPerformed(java.awt.event.ActionEvent evt)
{
CardLayout layout = (CardLayout)contentpane.getLayout();
layout.show(contentpane, "Panel 2");
secondCard.getTextField().setText(jTextField1.getText());
}
}
Second card:
public class SecondCard1 extends javax.swing.JPanel
{
...
JTextField getTextField()
{
return jTextField1;
}
...
}
But when you continue like this, the program will probably become a mess pretty soon. I'd recommend to create these components manually, without using any visual GUI builders.
I'm using jEditorPane to act kinda as some editor, the one who asked for this of me, also needed a find replace search... so I wanted to let him select in find and then do replace on need.
so I provide this simple code:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
int start = (jEditorPane1.getSelectionStart()>jEditorPane1.getSelectionEnd())?jEditorPane1.getSelectionEnd():jEditorPane1.getSelectionStart();
int max = (start>jEditorPane1.getSelectionStart())?start:jEditorPane1.getSelectionStart();
String searchWord = jTextField3.getText();
int searchIndex = jEditorPane1.getText().indexOf(searchWord, max);
if(searchIndex != -1){
jEditorPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jEditorPane1.setSelectionStart(-1);
jEditorPane1.setSelectionEnd(-1);
}
}
fortunatelly the application return good indexes, but unfortunatelly on view windows I see no selection.
I'm also new to java, please help
PS. buttons action are provided by netbeans itself
THe sample you requested
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* test.java
*
* Created on Jun 12, 2013, 8:23:19 PM
*/
package wordchecker;
/**
*
* #author Hassan
*/
public class test extends javax.swing.JFrame {
/** Creates new form test */
public test() {
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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(jTextPane1);
jTextField1.setText("jTextField1");
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(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int startFrom = jTextPane1.getSelectionStart();
if(jTextPane1.getSelectionStart() == jTextPane1.getSelectionEnd()){
startFrom = -1;
}
String searchWord = jTextField1.getText();
int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);
if(searchIndex != -1){
jTextPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jTextPane1.setSelectionStart(0);
jTextPane1.setSelectionEnd(0);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
}
The selection of a text component is only displayed when the text component has focus. When you click on the button it gains focus so you don't see the text selection. You could make the button non-focusable or you can add the following to the bottom of your actionPerformed() method:
jTextPane1.requestFocusInWindow();
Also, don't use the getText() method. This will cause problems with offsets.
int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);
See Text and New Lines for more information and a solution. The basics of this link is to use:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
The above will only return "\n" as the EOL string so the offsets will match when you do a search and then select the text.
Edit:
I generally use code like the following:
int startFrom = jTextPane1.getCaretPosition();
I am trying to do a simple Jform and call it from another class.
I want to use this Jframe in a server client application, but I don't know how to open the JFrame class from another class.
Like user has to chose
1- to open Jframe.
2- To Exit.
So What am I doing wrong?
Below are the codes:
Jframe Class named Calculas.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author user
*/
public class Calculas extends javax.swing.JFrame {
/**
* Creates new form Calculas
*/
public Calculas() {
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() {
a1Text = new javax.swing.JTextField();
a2Text = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
answer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
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(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60)
.addComponent(jLabel1)
.addGap(34, 34, 34)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int a;
a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
answer.setText("Answer" + a);
// 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(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculas.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 Calculas().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField a1Text;
private javax.swing.JTextField a2Text;
private javax.swing.JLabel answer;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Test Class named Test.java
public class Test extends JFrame {
public static void main(String args[])
{
Calculas CAL = new Calculas();
CAL.Calculus();
}
}
Forgive me if this is naive, as Im not anything of a Java programmer...
But isnt it just because you need to set visible?
Calculas CAL = new Calculas();
CAL.setVisible(true);
The constructor of Calculas doesn't show (setVisible) the frame.
If you want to interact with the Calculas class in this manner, you should also be calling CAL.setVisible(true)
Also, by convention, all Java instance variables, should start with a lower case character and use camelCase conventions
In it's current form of your code, you can call the main method of your Calculas class in Test class or move the code to the Test class.
Warning: Extending JFrame is not a good Idea.
First alternative: You don't need to extend JFrame in Test
public class Test{
public static void main(String args[])
{
Calculas.main(new String[0]);
}
}
You haven't mentioned in your question how you want to be able to chose close or open, in console or in another JFrame or something...
Second Alternative:
But If I were you I could do something like this: wrap the code for look and feel in a separate method and call this from Test' s main.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author user
*/
public class Calculas extends javax.swing.JFrame {
/**
* Creates new form Calculas
*/
public Calculas() {
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() {
a1Text = new javax.swing.JTextField();
a2Text = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
answer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
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(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)))
.addContainerGap(86, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(60, 60, 60)
.addComponent(jLabel1)
.addGap(34, 34, 34)
.addComponent(jButton1)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int a;
a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
answer.setText("Answer" + a);
// TODO add your handling code here:
}
public static setNimbusFeel(){
/* 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(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
// Variables declaration - do not modify
private javax.swing.JTextField a1Text;
private javax.swing.JTextField a2Text;
private javax.swing.JLabel answer;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
And test class like this:
public class Test{
public static void main(String args[])
{
Calculas cal=new Calculas();
//</editor-fold>
Calculas.setNimbusFeel();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Calculas().setVisible(true);
}
});
}
}
Like this:
Here's an example of a basic structure you can use:
import java.awt.*;
import javax.swing.*;
class MyGui {
private JFrame window = new JFrame("This is the title");
public MyGui() {
initComponents();
window.setBounds(100, 50, 600, 400); //location, size
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void initComponents() {
Container cp = window.getContentPane();
cp.setLayout(new FlowLayout() );
cp.add(new JLabel("Hello world") );
}
}
public class MyProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
And in separate files:
MyGui.java
import java.awt.*;
import javax.swing.*;
public class MyGui {
private JFrame window = new JFrame("This is the title");
public MyGui() {
initComponents();
window.setBounds(100, 50, 600, 400); //location, size
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void initComponents() {
Container cp = window.getContentPane();
cp.setLayout(new FlowLayout() );
cp.add(new JLabel("Hello world") );
}
}
MyProg.java
import javax.swing.*;
public class MyProg {
private static void createAndShowGUI() {
new MyGui();
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Calculas CAL = new Calculas();
CAL.Calculus();
maybe, CAL.Calculas(); I dont know java but I realized that, sorry about my english:)
I realize that if you are having a same selection in JComboBox, using up/down arrow key, will not help you to navigate the selection around. How I can avoid this behavior?
See the screenshot below:
alt text http://sites.google.com/site/yanchengcheok/Home/jcombobox.png
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
/* If you are having 3 same strings here. Using, up/down arrow key,
* will not move the selection around.
*/
this.jComboBox1.addItem("Intel");
this.jComboBox1.addItem("Intel");
this.jComboBox1.addItem("Intel");
}
/** 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() {
jComboBox1 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.setEditable(true);
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(105, 105, 105)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(137, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(63, 63, 63)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(217, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
// End of variables declaration
}
Quit cross posting.
The answer has already been given in that posting.