How to Unhighlight the text in JTextPane - java

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);
}
}
}

Related

Adding ItemListener in dynamically generated checkboxes

I am developing a restaurant management system in Java Swing. I have displayed a list of checkboxes dynamically from databases which contains the names of mainstock (table names which contains mainstock items).I have added an ItemListener on each checkbox during the loop.
When I click each checkbox, it popups two JFrame. Why? How could I popup only one JFrame and insert required information?
package test;
public class test extends javax.swing.JFrame {
public static ArrayList<mdetails> list = new ArrayList<mdetails>();
public test() {
initComponents();
Connection con = (Connection) dbconnection.makeconnection();
String sql="select * from mainstock";
try{
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
String s2=rs.getString("stock_name");
JCheckBox cb = new JCheckBox("New CheckBox");
cb.setText(s2);
cb.setVisible(true);
cb.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
String name = cb.getActionCommand();
System.out.println(name);
JFrame frame = new JFrame(name);
int stock_id= rmsdao.givestockid(name);
System.out.println(stock_id);
String estimatedplate = JOptionPane.showInputDialog(frame, "Enter the estimated plate of 1 kg"+name);
if(estimatedplate!=null){
list.add(new mdetails(stock_id,estimatedplate));
}
else{
cb.setSelected(false);
}
}
});
jPanel1.add(cb);
jPanel1.validate();
}
con.close();
}
catch(Exception e){
System.out.println("not retrieving"+e);
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(65, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(23, 23, 23))
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(37, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addComponent(jButton1)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
for (int a = 0; a < list.size(); a++) {
mdetails item = list.get(a);
System.out.println(item.getId());
// rmsdao.insert_menu_details(item.getId(),getitemid,item.getEstimate_plate());
}
}
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(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(test.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 test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}

How to fix java.lang.StackoverflowError

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...

change the backgroundColor of progress bar in Java Netbeans

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
}

Problems using my JPanel

I am making a graphical interface in Netbeans where you can put a series of numbers (example: 7 8 5 4 10 13) in the textfield "punten" and when you press the button "ververs" a graphical linechart of all the numbers should appear (in my panel). I made a class "Gui" that extends JFrame with the Textfield, the button and a panel in it. I also made a class "Grafiek" that extends JPanel and that is linked with the panel in my "Gui". The chart would be on the JPanel that is displayed in my JFrame.
The problems that I experience are: the repaint(); command won't go to the paintComponent(Graphics g)-method and my private variables won't change (the length of punt and punti stays 1 no matter what variables I put in my Textbox).
Can somebody please help me, I've been working on this project for days.
My Gui-class:
package grafiek;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Gui extends javax.swing.JFrame {
private Grafiek newJPanel;
/**
* Creates new form Gui
*/
public Gui() {
initComponents();
newJPanel = new Grafiek();
}
/**
* 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() {
punten = new javax.swing.JTextField();
fout = new javax.swing.JLabel();
javax.swing.JButton ververs = new javax.swing.JButton();
panel = new Grafiek();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
fout.setText("j");
ververs.setText("Ververs");
ververs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
verversActionPerformed(evt);
}
});
panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 195, Short.MAX_VALUE)
);
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)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(punten, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(ververs)
.addGap(6, 6, 6)
.addComponent(fout)
.addGap(0, 302, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(punten, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(fout)
.addComponent(ververs))
.addContainerGap())
);
pack();
}// </editor-fold>
private void verversActionPerformed(java.awt.event.ActionEvent evt) {
newJPanel.verwerkData(punten.getText());
}
/**
* #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(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Gui.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 Gui().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel fout;
private javax.swing.JPanel panel;
private javax.swing.JTextField punten;
// End of variables declaration
}
My Grafiek-class:
package grafiek;
import java.awt.Graphics;
public class Grafiek extends javax.swing.JPanel {
private String[] punt;
private int[] punti;
private int afstandX, afstandY, puntX1, puntY1, puntX2, puntY2;
private int max;
/**
* Creates new form Grafiek
*/
public Grafiek() {
initComponents();
punt = new String[1];
punti = new int[1];
afstandX = 0;
afstandY = 0;
puntX1 = 0;
puntY1 = 0;
puntX2 = 0;
puntY2 = 0;
max = 1;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i=0; i<punti.length; i++) {
if(max <= punti[i]) {
max = punti[i];
}
}
afstandX = getWidth()/punt.length;
afstandY = getHeight()/max;
for(int i=0; i<punti.length; i++) {
puntX1 = puntX2;
if(i == 0) {
puntY1 = getHeight();
}
else puntY1 = puntY2;
puntX2 += afstandX;
puntY2 = getHeight() - punti[i]*afstandY;
g.drawLine(puntX1, puntY1, puntX2, puntY2);
}
puntX2 = 0;
}
public void verwerkData(String s) {
punt = s.split(" ");
punti = new int[punt.length];
for(int i=0; i<punt.length; i++) {
punti[i] = Integer.parseInt(punt[i]);
}
repaint();
}
/**
* 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() {
setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
}
One problem I see is that you have declare an instantiated
newJPanel = new Grafiek();
which is the object that you call in the action method
private void verversActionPerformed(java.awt.event.ActionEvent evt) {
newJPanel.verwerkData(punten.getText());
}
But the newJPanel is never added to the frame. The object that looks like it is being added to the frame is
panel = new Grafiek();
which is in the initComponents(). Try changing
newJPanel.verwerkData(punten.getText());
to
panel.verwerkData(punten.getText());
And get rid of the newJpanel because you never use it

How do I Calculate the Average using the CalculateButton with following code for a KDRCalculator Program

In the following code I don't know how to find the average using the Calculate Button. I have managed to read the text in through Text fields for the values but i don't know how to make the program calculate the average and print it in the textfield once the Calculate Button has been clicked.
import java.util.Scanner;
public class KdrCalGui extends javax.swing.JFrame {
/**
* Creates new form KdrCalGui
*/
public KdrCalGui() {
initComponents();
double kills;
double deaths;
double subtotal;
double roundnumber;
}
/**
* 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() {
KillsValue = new javax.swing.JTextField();
KillsLabel = new javax.swing.JLabel();
DeathsValue = new javax.swing.JLabel();
DeathsLabel = new javax.swing.JTextField();
CalculateButton = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
Display = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
KillsValue.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
KillsValueActionPerformed(evt);
}
});
KillsLabel.setText("Kills");
DeathsValue.setText("Deaths");
DeathsLabel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DeathsLabelActionPerformed(evt);
}
});
CalculateButton.setText("Calculate");
CalculateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CalculateButtonActionPerformed(evt);
}
});
jLabel3.setText("Your KDR");
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(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(CalculateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DeathsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DeathsValue)
.addComponent(KillsValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KillsLabel))
.addGap(113, 113, 113)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(Display, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addContainerGap(31, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {DeathsLabel, KillsValue});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(KillsLabel)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(KillsValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(DeathsValue)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(DeathsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Display)))
.addGap(36, 36, 36)
.addComponent(CalculateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(50, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void DeathsLabelActionPerformed(java.awt.event.ActionEvent evt) {
DeathsLabel.setText(DeathsLabel.getText());
double deaths;
Scanner sc= new Scanner(System.in);
deaths=sc.nextInt();
}
private void KillsValueActionPerformed(java.awt.event.ActionEvent evt) {
KillsLabel.setText(KillsLabel.getText());
double kills;
Scanner sc=new Scanner(System.in);
kills=sc.nextInt();
}
THIS IS THE CALCULATE BUTTON.
private void CalculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #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(KdrCalGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(KdrCalGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(KdrCalGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(KdrCalGui.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 KdrCalGui().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton CalculateButton;
private javax.swing.JTextField DeathsLabel;
private javax.swing.JLabel DeathsValue;
private javax.swing.JTextField Display;
private javax.swing.JLabel KillsLabel;
private javax.swing.JTextField KillsValue;
private javax.swing.JLabel jLabel3;
// End of variables declaration
}
CalculateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == CalculateButton) {
// not sure what exactly you're trying to average
// but if it's the kills and deaths value, then...
int k = Integer.parseInt(KillsValue.getText());
int d = Integer.parseInt(DeathsValue.getText());
Display.setText((k+d)/2);
// think about adding exception handling in case they enter a noninteger
// also you switched the names of the TextField and Label in the initComponents()
}
}
});

Categories