I'm making one jInternalFrame where I'am adding tabs dynamically.
now adding a new TAB I have coded,
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ui;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JTabbedPane;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.plaf.basic.BasicInternalFrameUI;
/**
*
* #author santoshg
*/
public class jTAB extends javax.swing.JFrame {
/**
* Creates new form jTAB
*/
JTabbedPane tabList = new JTabbedPane();
int nUserCount = 1;
boolean isDrag = true;
private static int pressedX = 0, pressedY = 0;
JDesktopPane sDesktoppane = new JDesktopPane();
JComponent northPane;
public jTAB() {
this.setUndecorated(true);
initComponents();
drag();
jInternalFrame1.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("maximum")) {
if (jInternalFrame1.isMaximum()) {
try { // Maximizing TAB window with the size of Screen.
jInternalFrame1.setMaximum(true);
Toolkit tk = getToolkit();
jInternalFrame1.setSize((int) getToolkit().getScreenSize().getWidth(), (int) getToolkit().getScreenSize().getHeight());
setLocation(0, 0);
isDrag = false;
} catch (Exception e) {
e.printStackTrace();
}
} else {
try { // Setting it to it's actual size.
jInternalFrame1.setMaximum(false);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
isDrag = true;
setLocation(pressedX, pressedY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
public final void drag() {
setContentPane(sDesktoppane);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
jInternalFrame1.addInternalFrameListener(new InternalFrameListener() {
#Override
public void internalFrameOpened(InternalFrameEvent e) {
}
#Override
public void internalFrameClosing(InternalFrameEvent e) {
}
#Override
public void internalFrameClosed(InternalFrameEvent e) {
}
#Override
public void internalFrameIconified(InternalFrameEvent e) {
jInternalFrame1.setIconifiable(true);
}
#Override
public void internalFrameDeiconified(InternalFrameEvent e) {
}
#Override
public void internalFrameActivated(InternalFrameEvent e) {
}
#Override
public void internalFrameDeactivated(InternalFrameEvent e) {
}
});
jInternalFrame1.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("maximum")) {
if (jInternalFrame1.isMaximum()) {
try { // Maximizing TAB window with the size of Screen.
jInternalFrame1.setMaximum(true);
Toolkit tk = getToolkit();
jInternalFrame1.setSize((int) getToolkit().getScreenSize().getWidth(), (int) getToolkit().getScreenSize().getHeight());
`enter code here` setLocation(0, 0);
isDrag = false;
} catch (Exception e) {
e.printStackTrace();
}
} else {
try { // Setting it to it's actual size.
jInternalFrame1.setMaximum(false);
jInternalFrame1.setSize(jInternalFrame1.preferredSize());
isDrag = true;
setLocation(pressedX, pressedY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
if (northPane == null) {
northPane = ((BasicInternalFrameUI) jInternalFrame1.getUI()).getNorthPane();
northPane.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
if (isDrag) {
System.out.println("pressedX and pressedY " + pressedX + " " + pressedY);
pressedX = e.getX();
pressedY = e.getY();
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
northPane.addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
if (isDrag) {
int draggedObjX = getLocation().x + e.getX() - pressedX;
int draggedObjY = getLocation().y + e.getY() - pressedY;
setLocation(draggedObjX, draggedObjY);
getjInternalFrame().setLocation(0, 0);
}
}
public void mouseMoved(MouseEvent e) {
}
});
}
sDesktoppane.add(jInternalFrame1);
jInternalFrame1.setVisible(true);
jInternalFrame1.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
setSize(jInternalFrame1.getSize().width, jInternalFrame1.getSize().height);
}
});
setSize(jInternalFrame1.getSize());
if (northPane == null) {
setLocation(new Point(pressedX, pressedY));
}
super.setVisible(true);
}
public JInternalFrame getjInternalFrame() {
return jInternalFrame1;
}
public JComponent getNorthPane() {
return northPane;
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jInternalFrame1 = new javax.swing.JInternalFrame();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jInternalFrame1.setMaximizable(true);
jInternalFrame1.setVisible(true);
jButton1.setText("Add TAB");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup()
.addGap(0, 512, Short.MAX_VALUE)
.addComponent(jButton1))
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jInternalFrame1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 301, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1, javax.swing.GroupLayout.Alignment.TRAILING)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jInternalFrame1)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
tabList.addTab("User " + nUserCount, new ChatWindow("user " + nUserCount).getFrameComponent());
JComponent jif = (JComponent) jInternalFrame1.getContentPane();
jif.setLayout(new BorderLayout());
jif.add(tabList);
nUserCount++;
}//GEN-LAST:event_jButton1ActionPerformed
/**
* #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(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(jTAB.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(jTAB.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 jTAB().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JInternalFrame jInternalFrame1;
// End of variables declaration//GEN-END:variables
}
Where ChatWindow,java is
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ui;
import javax.swing.JComponent;
/**
*
* #author santoshg
*/
public class ChatWindow extends javax.swing.JFrame {
/**
* Creates new form ChatWindow
*/
public ChatWindow() {
initComponents();
}
public ChatWindow(String userName) {
initComponents();
lblUserName.setText(userName);
}
public JComponent getFrameComponent(){
return jPanel1;
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblUserName = new javax.swing.JLabel();
lblAvatar = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea2 = new javax.swing.JTextArea();
lblUserDept = new javax.swing.JLabel();
lblContactInfo = new javax.swing.JLabel();
lblSendFile = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblUserName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblUserName.setText("UserName");
lblUserName.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
lblAvatar.setText("Avatar");
lblAvatar.setAlignmentX(0.5F);
lblAvatar.setAlignmentY(0.2F);
lblAvatar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lblAvatar.setIconTextGap(2);
lblAvatar.setPreferredSize(new java.awt.Dimension(35, 15));
jTextArea1.setEditable(false);
jTextArea1.setBackground(new java.awt.Color(249, 251, 252));
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jTextArea2.setColumns(20);
jTextArea2.setRows(2);
jTextArea2.setMinimumSize(new java.awt.Dimension(3, 22));
jScrollPane2.setViewportView(jTextArea2);
lblUserDept.setText("Department");
lblContactInfo.setToolTipText("User Info");
lblSendFile.setToolTipText("Send File");
jLabel1.setToolTipText("View History");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(6, 6, 6)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 213, Short.MAX_VALUE)
.addComponent(lblUserDept, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 355, Short.MAX_VALUE)
.addComponent(lblContactInfo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblSendFile)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblContactInfo)
.addComponent(lblSendFile))
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblUserDept))
.addComponent(lblAvatar, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* #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(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatWindow.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 ChatWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private javax.swing.JLabel lblAvatar;
private javax.swing.JLabel lblContactInfo;
private javax.swing.JLabel lblSendFile;
private javax.swing.JLabel lblUserDept;
private javax.swing.JLabel lblUserName;
// End of variables declaration//GEN-END:variables
}
Hit the add button twice you'll get 2 TABS not when I maximize it "Add TAB" moved to Middle and Textareas are in top.
I want jTextAtrea1 to expand till the bottom of the page during maximize and restore to actual size during toggle.
I want jTextAtrea1 to expand till the bottom of the page during maximize
Sounds like you should be using a BorderLayout for the panel you add to the tab. Then you add the text area to the BorderLayout.CENTER and the other components to the BorderLayout.NORTH.
It looks like your layout code is generated by an IDE. Don't use the IDE to generate layout code. Do the layout yourself and you will be in full control.
Related
This is the JFrame class. When I click the button the Canvas class doesn't open and I don't know why.
I use the NetBeans auto compiler.
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package giochino;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
/**
*
* #author spriz
*/
public class Giochinoo extends JFrame implements KeyListener {
public Giochinoo() throws IOException {
initComponents();
A();
jTextField1.setText("inserisci "+random);
}
String random;
public final void A(){
random = "";
String characters = "aBcDeFgHiJkLmNoPqRsTuVwXyZ1234567890";
Random rnd = new Random();
int lunghezza = rnd.nextInt(7);
char[] text = new char[lunghezza];
for (int i = 0; i < lunghezza; i++) {
text[i] = characters.charAt(rnd.nextInt(characters.length()));
}
for (int i = 0; i < text.length; i++) {
random += text[i];
}
jTextField1.setText("inserisci "+random);
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
jButton1.setText("Gioca");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
jTextField1.setToolTipText("");
jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextField1FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField1FocusLost(evt);
}
});
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N
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()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(197, 197, 197))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(102, 102, 102)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(115, 115, 115)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(107, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(57, 57, 57)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(115, 115, 115))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
new Mossa().setVisible(true);
if (jTextField1.getText().equals(random)) {
A();
jLabel1.setText("bravo!");
}else{
// Mossa mossa = new Mossa();
// mossa.setVisible(true);
// try {
// Thread.sleep(2000);
// } catch (InterruptedException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// }
// try {
// String url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
// java.awt.Desktop myNewBrowserDesktop = java.awt.Desktop.getDesktop ();
// java.net.URI myNewLocation = new java.net.URI (url);
// myNewBrowserDesktop.browse (myNewLocation);
// } catch (URISyntaxException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// } catch (IOException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {
if (jTextField1.getText().equals("inserisci "+random)) {
jTextField1.setText("");
}
}
private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {
// if (jTextField1.getText().equals("")) {
// jTextField1.setText(random);
// }
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
//<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(Giochinoo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Giochinoo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Giochinoo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Giochinoo.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() {
try {
new Giochinoo().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify
public javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
#Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
#Override
public void keyPressed(KeyEvent e) {
// int keycode = e.getKeyCode();
//
// if (keycode == KeyEvent.VK_ENTER) {
//
// if (jTextField1.getText().equals(random)) {
// A();
// }else{
// try {
// String url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
// java.awt.Desktop myNewBrowserDesktop = java.awt.Desktop.getDesktop ();
// java.net.URI myNewLocation = new java.net.URI (url);
// myNewBrowserDesktop.browse (myNewLocation);
// } catch (URISyntaxException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// } catch (IOException ex) {
// Logger.getLogger(Giochinoo.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
// }
}
#Override
public void keyReleased(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
}
This is the Canvas class and if I change Canvas to JFrame I get an error on the finestra.add(mossa); line
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package giochino;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* #author spriz
*/
public class Mossa extends JPanel /*javax.swing.JFrame Canvas*/ implements Runnable{
BufferedImage mossaImg = null;
boolean attivo = false;
public Mossa(){
caricaRisorse();
}
public static void main(String[] args) {
Mossa mossa = new Mossa();
JFrame finestra = new JFrame();
Dimension dimensione = new Dimension(400,582);
finestra.setPreferredSize(dimensione);
finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
finestra.add(mossa);
finestra.pack();
finestra.setVisible(true);
Thread thread = new Thread(mossa);
thread.start();
}
private void caricaRisorse(){
CaricaImmagini loader = new CaricaImmagini();
mossaImg = loader.caricaImg("/Immagini/mossa.png");
}
private void disegna(){
Graphics g = this.getGraphics();
g.drawImage(mossaImg, 0, 0, 400,582,this);
g.dispose();
}
#Override
public void run() {
attivo = true;
while (attivo) {
disegna();
}
}
}
I tried to make the Canvas a JFrame and I saw that it opened but doesn't load the image.
I'm not sure what the problem with this code is but whenever I run it I get a java.lang.StackOverflowError. How would I fix it? This is what is displayed in the output console of netbeans:
run:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222) at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222)
at java.awt.Window.init(Window.java:497)
at java.awt.Window.<init>(Window.java:536)
at java.awt.Frame.<init>(Frame.java:420)
at java.awt.Frame.<init>(Frame.java:385)
at javax.swing.JFrame.<init>(JFrame.java:180)
code
import java.awt.Color;
import java.awt.Font;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
/*
* 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 Nicholas Ferretti
*/
public class Section2 extends javax.swing.JFrame {
Section2 s2Frame = new Section2();
Section3 s3Frame = new Section3();
ResultSet section2Questions;
DB connection = new DB();
/**
* Creates new form Section2Question1
*/
TimerFrame timerFrame;
int timeRemaining = 60;
int s2QuestionNumber = 1;
public Section2() {
this.timerFrame = new TimerFrame(this);
initComponents();
groupButton();
section2QuestionBox.setEditable(false);
s2QuestionNumberLabel.setText("Question "+s2QuestionNumber+":");
try {
section2Questions=connection.queryTbl("SELECT * FROM tblQuestions WHERE Section = 2");
section2Questions.next();
String firstQuestion = section2Questions.getString("Questions");
System.out.println(firstQuestion);
section2QuestionBox.setText(firstQuestion);
String firstAnswers = section2Questions.getString("AllPossibleAnswers");
Scanner scLine = new Scanner(firstAnswers).useDelimiter(",");
while(scLine.hasNext()){
String answer1 = scLine.next();
S2Answer1.setText(answer1);
System.out.println(answer1);
String answer2 = scLine.next();
S2Answer2.setText(answer2);
System.out.println(answer2);
String answer3 = scLine.next();
S2Answer3.setText(answer3);
System.out.println(answer3);
String answer4 = scLine.next();
S2Answer4.setText(answer4);
System.out.println(answer4);
}
} catch (SQLException ex) {
Logger.getLogger(Section1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error with SQL firstQuestion");
}
/*boolean t = timerFrame.timer(Section2Timer, timeRemaining);
if(t == false){
JOptionPane.showMessageDialog(null, "Time up for section.");
s2Frame.setVisible(false);
//s3Frame.setVisible(true);
}*/
}
private void groupButton() {
ButtonGroup buttons = new ButtonGroup();
buttons.add(S2Answer2);
buttons.add(S2Answer3);
buttons.add(S2Answer1);
buttons.add(S2Answer4);
}
private void timer() {
try {
Score time = new Score();
int timeRemaining = time.getTime();
while(timeRemaining>0){
Section2Timer.setText(timeRemaining+"");
Section2Timer.setFont(new Font("Serif", Font.BOLD, 32));
Section2Timer.setForeground(Color.RED);
Thread.sleep(1000);
timeRemaining--;
if(timeRemaining==0){
time.setTime(60);
}
time.setTime(timeRemaining);
}
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
}
/**
* 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() {
jLabel7 = new javax.swing.JLabel();
s2QuestionNumberLabel = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
section2QuestionBox = new javax.swing.JTextArea();
S2Answer1 = new javax.swing.JRadioButton();
S2Answer2 = new javax.swing.JRadioButton();
S2Answer3 = new javax.swing.JRadioButton();
S2Answer4 = new javax.swing.JRadioButton();
nextS2Question = new javax.swing.JButton();
Section2Timer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel7.setText("SECTION 2:");
s2QuestionNumberLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
s2QuestionNumberLabel.setText("QUESTION 1:");
jLabel9.setText("Answers:");
section2QuestionBox.setColumns(20);
section2QuestionBox.setRows(5);
section2QuestionBox.setText("At a conference, 12 memeber shook hands with each other \nbefore & after the meeting. How many total number of\nhand shakes occurred?");
jScrollPane3.setViewportView(section2QuestionBox);
S2Answer1.setText("Monday");
S2Answer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer1ActionPerformed(evt);
}
});
S2Answer2.setText("Tuesday");
S2Answer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer2ActionPerformed(evt);
}
});
S2Answer3.setText("Wednesday");
S2Answer3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer3ActionPerformed(evt);
}
});
S2Answer4.setText("Friday");
S2Answer4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer4ActionPerformed(evt);
}
});
nextS2Question.setText("Next");
nextS2Question.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextS2QuestionActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(125, 125, 125)
.addComponent(s2QuestionNumberLabel)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(217, 217, 217)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(S2Answer1)
.addGap(53, 53, 53)
.addComponent(S2Answer2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addComponent(S2Answer3)
.addGap(45, 45, 45)
.addComponent(S2Answer4))
.addComponent(nextS2Question, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(139, 139, 139)
.addComponent(Section2Timer, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Section2Timer, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addComponent(s2QuestionNumberLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(S2Answer1)
.addComponent(S2Answer2)
.addComponent(S2Answer3)
.addComponent(S2Answer4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 140, Short.MAX_VALUE)
.addComponent(nextS2Question)
.addGap(125, 125, 125))
);
pack();
}// </editor-fold>
String answer = "";
private void S2Answer1ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer1.getText();
}
private void S2Answer2ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer2.getText();
}
private void S2Answer3ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer3.getText();
}
private void S2Answer4ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer4.getText();
}
private void nextS2QuestionActionPerformed(java.awt.event.ActionEvent evt) {
Score score = new Score();
try {
String actualAnswer = section2Questions.getString("Answer");
int currentScore = score.getS2Score();
if(answer.equalsIgnoreCase(actualAnswer)){
currentScore+=5;
score.setS2Score(currentScore);
}
} catch (SQLException ex) {
Logger.getLogger(Section1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error in Next Question method");
}
if(s2QuestionNumber ==4){
int timeLeft = score.getTime();
int currentBonusPoints = score.getBonusPoints();
score.setBonusPoints(timeLeft+currentBonusPoints);
s2Frame.setVisible(false);
s3Frame.setVisible(true);
}
try {
section2Questions.next();
String nextQuestion = section2Questions.getString("Questions");
section2QuestionBox.setText(nextQuestion);
s2QuestionNumber++;
s2QuestionNumberLabel.setText("Question "+s2QuestionNumber+":");
} catch (SQLException ex) {
Logger.getLogger(Section1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error in Next Question method");
}
}
/**
* #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(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Section2().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JRadioButton S2Answer1;
private javax.swing.JRadioButton S2Answer2;
private javax.swing.JRadioButton S2Answer3;
private javax.swing.JRadioButton S2Answer4;
private javax.swing.JLabel Section2Timer;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton nextS2Question;
private javax.swing.JLabel s2QuestionNumberLabel;
private javax.swing.JTextArea section2QuestionBox;
// End of variables declaration
}
The very first line in your class Section2 would cause the problem.
You have, Section2 s2Frame = new Section2();, which means, every time an object is created for Section2 you want to create another object of Section2 (which will create another object... and sooooooooo on...)
Hence the stackoverflow exception...
I am a newbie in Java, I need changing the background Color of a progress bar, but really I don't know how to do this
I have a progress bar called "barrita"
I am using Linux Ubuntu and Java 8 and I am using the palette of Swing
package loginprogressbar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;
import javax.swing.Timer;
/**
*
* #author fernando
*/
public class Inicio extends javax.swing.JFrame {
private Timer tiempo;
int contador;
public static final int TWO_SECOND = 2;
class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
contador += 1;
barrita.setValue(contador);
if (contador == 100) {
tiempo.stop();
esconder();
Menu1 m1 = new Menu1();
m1.setVisible(true);
m1.setLocationRelativeTo(null);
}
}
}
public void esconder() {
this.setVisible(false);
}
public void activar() {
tiempo.start();
}
public Inicio() {
initComponents();
setLocationRelativeTo(null);
barrita.setVisible(false);
}
public void inicionSesion() {
String usuario = panel2.getText();
String password = (String.valueOf(txtPassword.getText()));
if (usuario.equals("fernando") && password.compareTo("12345") == 0) {
barrita.setVisible(true);
contador = -1;
barrita.setValue(0);
barrita.setStringPainted(true);
tiempo = new Timer(TWO_SECOND, new TimerListener());
activar();
} else {
JOptionPane.showMessageDialog(null, "Error al ingresar usuario o contraseƱa incorrecta");
panel2.setText("");
txtPassword.setText("");
panel2.requestFocus();
}
}
/**
* 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() {
panel1 = new javax.swing.JPanel();
panel2 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtPassword = new javax.swing.JPasswordField();
btnEntrar = new javax.swing.JButton();
barrita = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
panel1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
panel1KeyPressed(evt);
}
});
panel2.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
panel2KeyPressed(evt);
}
});
jLabel1.setText("Nombre");
jLabel2.setText("ContraseƱa");
txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtPasswordKeyPressed(evt);
}
});
btnEntrar.setText("Ingresar");
btnEntrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEntrarActionPerformed(evt);
}
});
javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnEntrar)
.addGap(83, 83, 83))
.addGroup(panel1Layout.createSequentialGroup()
.addGap(58, 58, 58)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addComponent(barrita, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(panel1Layout.createSequentialGroup()
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPassword)
.addComponent(panel2, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))
.addGap(113, 113, 113))))
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(panel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(21, 21, 21)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26)
.addComponent(barrita, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnEntrar)
.addContainerGap(93, Short.MAX_VALUE))
);
getContentPane().add(panel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300));
pack();
}// </editor-fold>
private void panel1KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
inicionSesion();
}
}
private void btnEntrarActionPerformed(java.awt.event.ActionEvent evt) {
inicionSesion(); // TODO add your handling code here:
}
private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
btnEntrar.requestFocus();
}
}
private void panel2KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
txtPassword.requestFocus();
}
}
/**
* #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(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Inicio.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 Inicio().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JProgressBar barrita;
private javax.swing.JButton btnEntrar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel panel1;
private javax.swing.JTextField panel2;
private javax.swing.JPasswordField txtPassword;
// End of variables declaration
}
I'm trying to do a log in I've gotten the username to work but the password is failing hard, I've tried multiple techniques and different ways and all of them have failed, my last effort seems to do nothing at all no error messages either where my previous stuff displayed error.
Can you please help me fix this + show me how to navigate to another page if the access is verified and password and username is right?
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Arrays;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class MainMenu extends javax.swing.JFrame {
private JLabel username;
private JLabel passwordlbl;
private JLabel Welco;
private JPasswordField Passwordfld;
private JButton Cancelbtn;
private JButton OKbtn;
private JTextField Usernametxt;
private String Password = "pass";
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
//PASSWORD field to store new password inside
//Passwordfld.setEchoChar('*');
//Passwordfld.addActionListener(new AL());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainMenu inst = new MainMenu();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public MainMenu() {
super();
initGUI();
}
private static boolean isPasswordCorrect(char[] input) {
boolean isCorrect = true;
char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals (input, correctPassword);
}
//Zero out the password.
Arrays.fill(correctPassword,'0');
return isCorrect;
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
username = new JLabel();
getContentPane().add(username);
username.setText("User Name:");
username.setBounds(63, 113, 80, 16);
passwordlbl = new JLabel();
getContentPane().add(passwordlbl);
passwordlbl.setText("Password:");
passwordlbl.setBounds(63, 160, 72, 16);
Usernametxt = new JTextField();
getContentPane().add(Usernametxt);
Usernametxt.setBounds(198, 110, 79, 23);
OKbtn = new JButton();
getContentPane().add(OKbtn);
OKbtn.setText("OK");
OKbtn.setBounds(102, 217, 59, 23);
OKbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(Usernametxt.getText().equals("Admin")){} /*&&
(Passwordfld.getText().equals("Admin2"))*/
String cmd = evt.getActionCommand();
if (OKbtn.equals(cmd)) { //Process the password.
char[] input = Passwordfld.getPassword();
if (isPasswordCorrect(input)) {
System.out.println("Password Accepted");
} else {
System.out.println("Password Rejected");
}
//Zero out the possible password, for security.
Arrays.fill(input, '0');
Passwordfld.selectAll();
/*else{
System.out.println("permition Rejected");
}*/
//else{}
/* if (Passwordfld = Password)= true) {
System.out.println("permition granted");}*/
}
}
}
);
Cancelbtn = new JButton();
getContentPane().add(Cancelbtn);
Cancelbtn.setText("Exit");
Cancelbtn.setBounds(198, 217, 61, 23);
Cancelbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setDefaultCloseOperation(WindowConstants.setVisible(false);
//System.out.println("Cancelbtn.actionPerformed, event="+evt);
//TODO add your code for Cancelbtn.actionPerformed
}
});
Welco = new JLabel();
getContentPane().add(Welco);
Welco.setText("Welcome to Jstore please log in using your staff acount");
Welco.setBounds(51, 19, 291, 16);
JPasswordField Passwordfld = new JPasswordField();
//Passwordfld.setText("Secret");
getContentPane().add(Passwordfld);
Passwordfld.setBounds(198, 157, 79, 23);
Passwordfld.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//System.out.println("Passwordfld.actionPerformed, event="+evt);
//TODO add your code for Passwordfld.actionPerformed
}
});
pack();
setSize(400, 300);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
//static class AL implements ActionListener{
//JPasswordField input = new JPasswordField();
/* char [] passy = input.getPassword();
String p = new String (passy);{
if (p.equals (Password)){
JOptionPane.showMessageDialog(null, "Correct"); }
else
{ JOptionPane.showMessageDialog(null, "InCorrect");
}
*/
}
Alternatively you can use this....
package javaapplication7;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
/**
*
* #author akash
*/
public class detail extends javax.swing.JFrame implements ActionListener{
private final String username ="admin";
private final String password = "pass";
public detail() {
initComponents();
jButton1.addActionListener(this);
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Username");
jLabel2.setText("Password");
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jButton1.setText("Submit");
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()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(63, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(47, 47, 47)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14))
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(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(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(detail.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 detail().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()== jButton1)
{
if("admin".equals(jTextField1.getText()) && "pass".equals(jTextField2.getText()))
{
java.awt.EventQueue.invokeLater(() -> {
new LoggedIn().setVisible(true);
});
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use admin and pass");
}
}
}
}
The above one will be your first class and the next will be....
class LoggedIn extends javax.swing.JFrame {
/**
* Creates new form LoggedIn
*/
public LoggedIn() {
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() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Welcome 2 Store");
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(91, 91, 91)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(101, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(163, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #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(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Hoping it helped....
Your password field is not inited, it's still null when you try to take char[] from it. You can try with:
final JPasswordField Passwordfld = new JPasswordField();
// Passwordfld.setText("Secret");
getContentPane().add(Passwordfld);
Passwordfld.setBounds(198, 157, 79, 23);
Passwordfld.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// System.out.println("Passwordfld.actionPerformed, event="+evt);
// TODO add your code for Passwordfld.actionPerformed
}
});
OKbtn = new JButton();
getContentPane().add(OKbtn);
OKbtn.setText("OK");
OKbtn.setBounds(102, 217, 59, 23);
OKbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String passText = new String(Passwordfld.getPassword());
if (Usernametxt.getText().equals("Admin")) {
String cmd = evt.getActionCommand();
if (OKbtn.getActionCommand().equals(cmd)) { // Process the password.
if (isPasswordCorrect(passText.toCharArray())) {
System.out.println("Password Accepted");
} else {
System.out.println("Password Rejected: " + passText);
}
// Zero out the possible password, for security.
Arrays.fill(passText.toCharArray(), '0');
Passwordfld.selectAll();
/*
* else{ System.out.println("permition Rejected"); }
*/
// else{}
/*
* if (Passwordfld = Password)= true) {
* System.out.println("permition granted");}
*/
}
}
}
});
I have write a code to find a word in JTextPane. Problem here is when I enter a search word and click on search button it was highlight the all the occurrence of the given search word. I want to Highlight the first occurrence of the word then click on search button shows second occurrence of the way like that. Another one is it was not unHighlight the after search complete when click on text pane.
My code:
public class FindAWord extends javax.swing.JFrame {
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(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MarkAll.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 MarkAll().setVisible(true);
}
});
}
Highlighter.HighlightPainter myHighLightPainter = new FindAWord.MyHighightPainter(
Color.LIGHT_GRAY);
// Variables declaration - do not modify
private javax.swing.JScrollPane scrollPane;
private javax.swing.JTextField searchText;
private javax.swing.JTextPane textPane;
private javax.swing.JButton search;
public FindAWord() {
initComponents();
}
public void removeHighLights(JTextComponent component) {
Highlighter hilet = component.getHighlighter();
Highlighter.Highlight[] highLites = hilet.getHighlights();
for (int i = 0; i < highLites.length; i++) {
if (highLites[i].getPainter() instanceof MarkAll.MyHighightPainter) {
hilet.removeHighlight(highLites[i]);
}
}
}
public void highLight(JTextComponent component, String patteren) {
try {
removeHighLights(component);
Highlighter hLite = component.getHighlighter();
Document doc = component.getDocument();
String text = component.getText(0, doc.getLength());
int pos = 0;
while ((pos = text.toUpperCase().indexOf(patteren.toUpperCase(),
pos)) >= 0) {
hLite.addHighlight(pos, pos + patteren.length(),
myHighLightPainter);
pos += patteren.length();
}
} catch (Exception e) {
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
search = new javax.swing.JButton();
searchText = new javax.swing.JTextField();
scrollPane = new javax.swing.JScrollPane();
textPane = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
search.setText("Search");
search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchActionPerformed(evt);
}
});
scrollPane.setViewportView(textPane);
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(36, 36, 36)
.addComponent(search,
javax.swing.GroupLayout.PREFERRED_SIZE,
91,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(searchText,
javax.swing.GroupLayout.PREFERRED_SIZE,
120,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114, Short.MAX_VALUE))
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addComponent(scrollPane)
.addContainerGap()));
layout.setVerticalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(search)
.addComponent(
searchText,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPane,
javax.swing.GroupLayout.DEFAULT_SIZE,
235, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void searchActionPerformed(java.awt.event.ActionEvent evt) {
if (searchText.getText().length() == 0) {
removeHighLights(textPane);
} else
highLight(textPane, searchText.getText());
}
class MyHighightPainter extends DefaultHighlighter.DefaultHighlightPainter {
MyHighightPainter(Color color) {
super(color);
}
}
}
If you need just to highlight one word you don't need all the addHighlight() and removeHighlight() calls.
Just figure out the word's offset (and length) and use setSelectionStart()/setSelectionEnd() method of the JTextPane passing the word start and start + length
UPDATE as requested the working code
import javax.swing.text.*;
import java.awt.*;
public class FindAWord extends javax.swing.JFrame {
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 (Exception ex) {
ex.printStackTrace();
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new FindAWord().setVisible(true);
}
});
}
Highlighter.HighlightPainter myHighLightPainter=new FindAWord.MyHighightPainter(Color.LIGHT_GRAY);
// Variables declaration - do not modify
private javax.swing.JScrollPane scrollPane;
private javax.swing.JTextField searchText;
private javax.swing.JTextPane textPane;
private javax.swing.JButton search;
public FindAWord() {
initComponents();
}
public void highLight(JTextComponent component,String patteren){
try {
Document doc=component.getDocument();
String text=component.getText(0,doc.getLength());
int pos=component.getCaretPosition();
if (pos==doc.getLength()) {
pos=0;
}
int index=text.toUpperCase().indexOf(patteren.toUpperCase(),pos);
if (index>=0) {
component.setSelectionStart(index);
component.setSelectionEnd(index+patteren.length());
component.getCaret().setSelectionVisible(true);
}
}
catch(Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
search = new javax.swing.JButton();
searchText = new javax.swing.JTextField();
scrollPane = new javax.swing.JScrollPane();
textPane = new javax.swing.JTextPane();
searchText.setText("test");
textPane.setText("test qweqw test asdasdas test");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
search.setText("Search");
search.setFocusable(false);
search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchActionPerformed(evt);
}
});
scrollPane.setViewportView(textPane);
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(36, 36, 36)
.addComponent(search, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(scrollPane)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(search)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void searchActionPerformed(java.awt.event.ActionEvent evt) {
highLight(textPane, searchText.getText());
}
class MyHighightPainter extends DefaultHighlighter.DefaultHighlightPainter{
MyHighightPainter(Color color){
super(color);
}
}
}