Problems using my JPanel - java

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

Related

When I input a number into jTextField1, the case does not get acted upon

eg. I input 1 into combobox and 50 into jTextField1 and the correct answer won't come out. It is going to be code that runs an application to convert chosen temperature ie. celcius, fairenheit or kelvin into the desired choice. For now I'm just trying out with this format of the choices between 1 and 4. I will change it later. Jbutton1 is the button to convert and when clicked should enact all the code within it. but for some reason it does not want to enact on the case that I defined earlier on. It should take the inputted temperature and add 273 to it.
public class Conversion extends javax.swing.JFrame {
int calculation = 0;
String temphold;
double input_temp;
/**
* Creates new form Conversion
*/
public Conversion() {
initComponents();
}
public void cases() {
switch (calculation) {
case 1:
input_temp = input_temp + 273.5;
break;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jComboBox1 = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("jTextField1");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4" }));
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(jComboBox1, 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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(207, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(113, 113, 113))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(67, 67, 67))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(58, 58, 58)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(50, 50, 50))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
temphold = (String) jComboBox1.getSelectedItem();
String hold = jTextField1.getText();
input_temp = Double.parseDouble(hold);
if (temphold == "1") {
calculation = 1;
System.out.println("monkey");
System.out.println(input_temp);
}
}
/**
* #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(Conversion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Conversion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Conversion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Conversion.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 Conversion().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}

Why this java key bind doesn't work?

I have a JFrame that simulates a simple celsius to fahrenheit converter.
What I'm trying to do is call the "convert" button action whenever the ENTER key es pressed.
I've tried defining the default button (but it doesn't work).
My code now looks like this:
public class TemperatureConverterGUI extends javax.swing.JFrame {
/**
* Creates new form TemperatureConverterGUI
*/
public TemperatureConverterGUI() {
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() {
button_convert = new javax.swing.JButton();
edittext = new javax.swing.JFormattedTextField();
label = new javax.swing.JLabel();
label_resultat = new javax.swing.JLabel();
resultat = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
button_convert.setText("Converteix");
button_convert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button_convertActionPerformed(evt);
}
});
edittext.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
edittext.setHorizontalAlignment(javax.swing.JTextField.CENTER);
edittext.setToolTipText("Introdueix un número en Fahrenheit");
label.setText("Introdueix un número en Fahrenheit:");
label_resultat.setText("Resultat: ");
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(49, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(label_resultat)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(resultat))
.addComponent(button_convert)
.addComponent(label)
.addComponent(edittext, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(90, 90, 90))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(65, Short.MAX_VALUE)
.addComponent(label)
.addGap(12, 12, 12)
.addComponent(edittext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addComponent(button_convert)
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(label_resultat)
.addComponent(resultat))
.addGap(70, 70, 70))
);
pack();
}// </editor-fold>
private void button_convertActionPerformed(java.awt.event.ActionEvent evt) {
int f = Integer.valueOf(edittext.getText());
int c = VisualTemperatureConverter.FahrenheitToCelsius(f);
resultat.setText(String.valueOf(c));
}
/**
* #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(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
**TemperatureConverterGUI frame = new TemperatureConverterGUI();
frame.button_convert.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "enter");
frame.button_convert.getActionMap().put("enter", frame.button_convert.getAction());**
frame.setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton button_convert;
private javax.swing.JFormattedTextField edittext;
private javax.swing.JLabel label;
private javax.swing.JLabel label_resultat;
private javax.swing.JLabel resultat;
// End of variables declaration
}
Nothing fancy needed, just add this to your edittext setup.
edittext.addActionListener((ae)-> button_convertActionPerformed(null));

How do I get data from a table and display it in another table in Java?

How do I get data from a table and display it in another table in Java?
I select a row from a table and get its values but I don't know how to display it another table.
Netbean Project that copies data from one table to another
Hope this helps.
import javax.swing.table.DefaultTableModel;
/*
* 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 razak
*/
public class CopyDataFromTableToAnotherTable extends javax.swing.JFrame {
/**
* Creates new form CopyDataFromTableToAnotherTable
*/
public CopyDataFromTableToAnotherTable() {
initComponents();
populateTableToCopyFrom();
}
/**
* This populates tableToCopyDataFrom with test data
*/
private void populateTableToCopyFrom() {
String [] columnName = {"Name","Age"};
DefaultTableModel tableModel = new DefaultTableModel(columnName,0);
for (int i = 0; i < 5; i++){
String temp[] = {"Student " + i, (i+ 1)* 10+ ""};
tableModel.addRow(temp);
}
tableToCopyDataFrom.setModel(tableModel);
}
/**
* This methods copies values from tableToCopyDataFrom to tableToCopyDataTo
*/
private void copyDataToTableFromTable(){
DefaultTableModel tableModel = (DefaultTableModel)tableToCopyDataFrom.getModel();
tableToCopyDataTo.setModel(tableModel);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
tableToCopyDataFrom = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
tableToCopyDataTo = new javax.swing.JTable();
copyToTableButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tableToCopyDataFrom.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane1.setViewportView(tableToCopyDataFrom);
tableToCopyDataTo.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane2.setViewportView(tableToCopyDataTo);
copyToTableButton.setText("Copy To Table below");
copyToTableButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
copyToTableButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addContainerGap(19, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(copyToTableButton)
.addGap(50, 50, 50))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(copyToTableButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51))
);
pack();
}// </editor-fold>
/**
* Button click that copies data to the second table
* #param evt event listener
*/
private void copyToTableButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
copyDataToTableFromTable();
}
/**
* #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(CopyDataFromTableToAnotherTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CopyDataFromTableToAnotherTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CopyDataFromTableToAnotherTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CopyDataFromTableToAnotherTable.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 CopyDataFromTableToAnotherTable().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton copyToTableButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable tableToCopyDataFrom;
private javax.swing.JTable tableToCopyDataTo;
// End of variables declaration
}

How to Unhighlight the text in JTextPane

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

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