Scroll to a position in a text area when the button clicked. - java

It's easy to create HTML link locations like this sample, but now I'm talking about Java swing.
Lets assume I've created 5 JButtons: firstButton, secondButton, thirdButton, fourthButton and fifthButton.
Then I put all text information in a JTextArea txtInform.
When I click firstButton, information for firstButton will be displayed to the top of txtInform.
When I click secondButton, information for secondButton will be displayed to the top of txtInform.
And so forth for the next buttons. All buttons must work like this sample.
How can I do that?
Note: I know how to create components (like JButton, JTextArea, etc) in java swing. Please don't tell me only to read the tutorial of Swing Class API or other java docs. I have read the Swing Class API tutorial and java docs but I don't find any specific tutorial for this problem yet. If you ever read specific tutorial like what I'm asking here, please let me know.
Edit:
Updated: What I really need is to scroll to a position in a text area when the button clicked.
Below is the my code so far, I created it in netbeans. I use hightlight from here.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui_001;
import java.awt.Color;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
/**
*
* #author MyScript
*/
public class sampleFrame extends javax.swing.JFrame {
/**
* Creates new form sampleFrame
*/
public sampleFrame() {
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() {
firstButton = new javax.swing.JButton();
secondButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
txtInform = new javax.swing.JTextArea();
thirdButton = new javax.swing.JButton();
fourthButton = new javax.swing.JButton();
fifthButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
firstButton.setText("First Button");
firstButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
firstButtonActionPerformed(evt);
}
});
secondButton.setText("Second Button");
secondButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
secondButtonActionPerformed(evt);
}
});
txtInform.setText("*First*");
txtInform.append("\n");
txtInform.append("All first information are here..");
txtInform.append("\n\n\n\n");
txtInform.append("**Second**");
txtInform.append("\n");
txtInform.append("All second information are here..");
txtInform.append("\n\n\n\n");
txtInform.append("***Third***");
txtInform.append("\n");
txtInform.append("All third information are here..");
txtInform.append("\n\n\n\n");
txtInform.append("****Fourth****");
txtInform.append("\n");
txtInform.append("All fourth information are here..");
txtInform.append("\n\n\n\n");
txtInform.append("*****Fifth*****");
txtInform.append("\n");
txtInform.append("All fifth information are here..");
txtInform.setColumns(20);
txtInform.setLineWrap(true);
txtInform.setRows(5);
txtInform.setWrapStyleWord(true);
jScrollPane1.setViewportView(txtInform);
thirdButton.setText("Third Button");
thirdButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
thirdButtonActionPerformed(evt);
}
});
fourthButton.setText("Fourth Button");
fourthButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fourthButtonActionPerformed(evt);
}
});
fifthButton.setText("Fifth Button");
fifthButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fifthButtonActionPerformed(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(76, 76, 76)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(secondButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(firstButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(thirdButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(fourthButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(fifthButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(64, 64, 64)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(71, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(76, 76, 76)
.addComponent(firstButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(secondButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(thirdButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fourthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fifthButton, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(44, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(90, Short.MAX_VALUE))
);
setSize(new java.awt.Dimension(595, 477));
setLocationRelativeTo(null);
}// </editor-fold>
private void secondButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "**Second**";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
private void firstButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "*First*";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
private void fifthButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "*****Fifth*****";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
private void fourthButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "****Fourth****";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
private void thirdButtonActionPerformed(java.awt.event.ActionEvent evt) {
String text = txtInform.getText();
String second = "***Third***";
int i = text.indexOf(second);
int pos = txtInform.getCaretPosition();
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.BLUE );
int offset = text.indexOf(second);
int length = second.length();
while ( offset != -1)
{
try
{
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
offset = text.indexOf(second, offset+1);
}
catch(BadLocationException ble) { System.out.println(ble); }
}
}
/**
* #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(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(sampleFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(sampleFrame.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 sampleFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton fifthButton;
private javax.swing.JButton firstButton;
private javax.swing.JButton fourthButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton secondButton;
private javax.swing.JButton thirdButton;
private javax.swing.JTextArea txtInform;
// End of variables declaration
}

Here is your code with some changes. When pressing a button, the text area will be scrolled to the location of the text and only that text will be highlighted.
public class SampleFrame extends JFrame {
private static JTextArea txtInform = new JTextArea();
private static final String TEXT = "*First*\nAll first information are here..\n\n\n\n" +
"**Second**\nAll second information are here..\n\n\n\n" +
"***Third***\nAll third information are here..\n\n\n\n" +
"****Fourth****\nAll fourth information are here..\n\n\n\n" +
"*****Fifth*****\nAll fifth information are here..";
public SampleFrame() {
initComponents();
}
private void initComponents() {
JScrollPane jScrollPane1 = new JScrollPane(txtInform);
JButton firstButton = new JButton("First Button");
JButton secondButton = new JButton("Second Button");
JButton thirdButton = new JButton("Third Button");
JButton fourthButton = new JButton("Fourth Button");
JButton fifthButton = new JButton("Fifth Button");
firstButton.addActionListener(new MyActionListener("*First*"));
secondButton.addActionListener(new MyActionListener("**Second**"));
thirdButton.addActionListener(new MyActionListener("***Third***"));
fourthButton.addActionListener(new MyActionListener("****Fourth****"));
fifthButton.addActionListener(new MyActionListener("*****Fifth*****"));
txtInform.setText(TEXT);
txtInform.setColumns(20);
txtInform.setRows(5);
txtInform.setLineWrap(true);
txtInform.setWrapStyleWord(true);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(76, 76, 76)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(secondButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(firstButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(thirdButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(fourthButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(fifthButton, GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(64, 64, 64)
.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 265,
GroupLayout.PREFERRED_SIZE).addContainerGap(71, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(76, 76, 76)
.addComponent(firstButton, GroupLayout.PREFERRED_SIZE, 30,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(secondButton, GroupLayout.PREFERRED_SIZE, 31,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(thirdButton, GroupLayout.PREFERRED_SIZE, 31,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fourthButton, GroupLayout.PREFERRED_SIZE, 32,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(fifthButton, GroupLayout.PREFERRED_SIZE, 32,
GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(44, Short.MAX_VALUE)
.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 305,
GroupLayout.PREFERRED_SIZE).addContainerGap(90, Short.MAX_VALUE)));
setSize(new java.awt.Dimension(595, 477));
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
private class MyActionListener implements ActionListener {
private int offset, length;
private final Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.BLUE);
private MyActionListener(String chapter) {
offset = TEXT.indexOf(chapter);
length = chapter.length();
}
public void actionPerformed(ActionEvent e) {
txtInform.setCaretPosition(offset);
txtInform.getHighlighter().removeAllHighlights();
try {
txtInform.getHighlighter().addHighlight(offset, offset + length, painter);
} catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SampleFrame().setVisible(true);
}
});
}
}
Class names start with uppercase per Java naming conventions.
Make your code present a logical order of the lines. It's clearer to initialize all buttons one after the other and not shove in the middle a scroll pane initialization.
Don't create fields when you can create local variables (all your buttons and scroll pane).
Prepare a single string with the text that should be displayed instead of calling append for every line (if you are not doing that already).
Create 1 action listener for all the buttons since it has a similar function for all of them - reusable code.
You'll profit a lot if you write the GUI yourself and not with a builder.

Simple example
public class Main extends JPanel implements ActionListener{
JTextField textField = null;
public static void main(final String[] args) {
Main main = new Main();
main.textField= new JTextField("Sample");
JButton btn1 = new JButton("Button1");
btn1.addActionListener(main);
JButton btn2 = new JButton("Button2");
btn2.addActionListener(main);
main.add(main.textField);
main.add(btn1);
main.add(btn2);
JFrame frame = new JFrame();
frame.setTitle("Simple example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.add(main);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(e.getActionCommand());
repaint();
}
}

Related

Basically what i want is to display the usb directoires and a local drive directoires in two jscrollpane side by side

I have made two JScrollPane components. The left one shows the directories in USB and right shows the directories of a local drive. For I am able to display the complete file path as shown in first pic. But I want to display it with icons just like the way directories are displayed in any local drive on PC. This is my designed GUI, here is the example of what I want example
public class MainForm extends javax.swing.JFrame {
iRecordCopy obj = new iRecordCopy();
public MainForm() {
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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jScrollPane2 = new javax.swing.JScrollPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Main From");
setLocation(new java.awt.Point(0, 0));
setName("mainframe"); // NOI18N
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel1.setText("iRecordCopy");
jLabel2.setText("jLabel2");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(48, 48, 48)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(30, 30, 30))
);
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.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public 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(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.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 MainForm().setVisible(true);
}
});
}
public void showusb()
{
File[] usb;
int count = 0;
String str;
usb = obj.detectUSB();
if(usb == null)
{
//USB_window.setText("No USB attached\n");
return;
}
for (File filename : usb) {
str = filename.toString().substring(3);
str = str.substring(0, str.length() - 3);
System.out.println(str);
if(str.equalsIgnoreCase("vehicle"))
{
System.out.print(filename.toString());
//USB_window.append(filename.getPath()+"\n");
count++;
}
}
if(count == 0)
{
System.out.println("No recordings found in usb");
}
else
System.out.println("Number of directries :" + count);
//File currentDir = new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(obj.path.listFiles());
jScrollPane1 = new JScrollPane(jlist);
jScrollPane1.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane1);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
public void showPc(File f)
{
JList<File> jlist=new JList<File>(f.listFiles());
jScrollPane2 = new JScrollPane(jlist);
//jScrollPane2.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane2);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration
}
Here a short example to create a minimal JList with file icons, it displays the content of the user's home directory using the system file icons.
package test;
import java.awt.Component;
import java.awt.Dimension;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.filechooser.FileSystemView;
public class Test {
public static void main(String[] args) {
JFrame frame=new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File currentDir=new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(currentDir.listFiles());
JScrollPane scrollPane=new JScrollPane(jlist);
scrollPane.setPreferredSize(new Dimension(400, 800));
frame.setContentPane(scrollPane);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
frame.pack();
frame.setVisible(true);
}
}

How to get ALL values from a Jtable and graph them?

I have a jtable set up that I've populated with values from a .csv file. I need to retrieve all of the values from the jtable and graph them, but am having trouble figuring it out. I'm using JFreeChart and have set up the graph but am absolutely stuck on how to populate the line graph with values from the JTable.
Code that I've tried, but isn't working and simply halts the application when I hit the graph button:
//instantiate the data series and the chart
int row = tableRadio.getRowCount();
int column = tableRadio.getColumnCount();
for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
series.add(r, c);
}
}
Entire Code:
//data used by all methods
DefaultTableModel tableModel;
//Global variables
XYSeries series; //series of data that will be added to the graph
XYSeriesCollection dataSet; //a collection object holds the series
JFreeChart chart; //chart to be placed on the panel
public MainWindow() {
initComponents();
//instantiate the DefaultTableModel
tableModel = (DefaultTableModel) tableRadio.getModel();
//instantiate the data series and the chart
series = new XYSeries("Random Numbers");
dataSet = new XYSeriesCollection(series);
chart = ChartFactory.createXYLineChart("Radio Astronomy Graphing", "Time", "Sensor Value", dataSet);
//display the graphing chart on the panel
panelGraph.add(new ChartPanel(chart), BorderLayout.CENTER);
panelGraph.revalidate();
//center the applications window upon start
this.setLocationRelativeTo(null);
}
/**
* 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() {
buttonLoad = new javax.swing.JButton();
buttonGraph = new javax.swing.JButton();
buttonSave = new javax.swing.JButton();
buttonAdd = new javax.swing.JButton();
buttonEdit = new javax.swing.JButton();
buttonRemove = new javax.swing.JButton();
labelValue = new javax.swing.JLabel();
tfMonth = new javax.swing.JTextField();
tfValue = new javax.swing.JTextField();
tfDay = new javax.swing.JTextField();
labelHour = new javax.swing.JLabel();
labelMin = new javax.swing.JLabel();
labelYear = new javax.swing.JLabel();
labelDay = new javax.swing.JLabel();
labelMonth = new javax.swing.JLabel();
tfYear = new javax.swing.JTextField();
tfHour = new javax.swing.JTextField();
tfMin = new javax.swing.JTextField();
panelGraph = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tableRadio = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonLoad.setText("Load File");
buttonLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonLoadActionPerformed(evt);
}
});
buttonGraph.setText("Graph Data");
buttonGraph.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonGraphActionPerformed(evt);
}
});
buttonSave.setText("Save");
buttonSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonSaveActionPerformed(evt);
}
});
buttonAdd.setText("Add");
buttonAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonAddActionPerformed(evt);
}
});
buttonEdit.setText("Edit");
buttonEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonEditActionPerformed(evt);
}
});
buttonRemove.setText("Remove");
buttonRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonRemoveActionPerformed(evt);
}
});
labelValue.setText("Sensor Value:");
tfValue.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tfValueActionPerformed(evt);
}
});
labelHour.setText("Hour");
labelMin.setText("Minute");
labelYear.setText("Year");
labelDay.setText("Day");
labelMonth.setText("Month");
panelGraph.setLayout(new java.awt.BorderLayout());
tableRadio.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Date and Time", "Sensor Value"
}
) {
boolean[] canEdit = new boolean [] {
false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tableRadio);
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(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(buttonLoad, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonSave, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonGraph, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(buttonAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(84, 84, 84)
.addComponent(labelMonth)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfMonth, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(labelDay)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfDay, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(buttonEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(buttonRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(87, 87, 87)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelValue)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfValue, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(labelHour)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfHour, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(15, 15, 15)
.addComponent(labelMin)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfMin, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(labelYear)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfYear, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(panelGraph, javax.swing.GroupLayout.PREFERRED_SIZE, 382, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 17, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panelGraph, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonLoad)
.addComponent(buttonAdd)
.addComponent(labelMonth)
.addComponent(tfMonth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelDay)
.addComponent(tfDay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelYear)
.addComponent(tfYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonGraph)
.addComponent(buttonEdit)
.addComponent(tfHour, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(labelHour)
.addComponent(labelMin)
.addComponent(tfMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonSave)
.addComponent(buttonRemove)
.addComponent(labelValue)
.addComponent(tfValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(35, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void buttonLoadActionPerformed(java.awt.event.ActionEvent evt) {
//Load file into table
//create JFileChooser
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
//create myFile and define the path
File myFile = fileChooser.getSelectedFile();
try{
//instantiate Scanner
Scanner inputStream = new Scanner(myFile);
for(int i=0; i < 12; i++){
inputStream.nextLine();
}
//split values into 2 arrays and insert into table
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
tableModel.insertRow(tableModel.getRowCount(), values);
}//end of while block
}//end of try block
catch(FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "File Not Found");
}//end of catch block
}
private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {
//add info from text fields and combo boxes to table
try {
//create variables to hold the contents of what user has typed in
int Month = Integer.parseInt(tfMonth.getText());
int Day = Integer.parseInt(tfDay.getText());
int Year = Integer.parseInt(tfYear.getText());
int Hour = Integer.parseInt(tfHour.getText());
int Min = Integer.parseInt(tfMin.getText());
double Value = Double.parseDouble(tfValue.getText());
//add the info to the table
tableModel.insertRow(tableModel.getRowCount(), new Object[]{Month + "/" + Day + "/" + Year + " " + Hour + ":" + Min, Value });
//clear the controls on the interface
tfMonth.setText("");
tfDay.setText("");
tfYear.setText("");
tfHour.setText("");
tfMin.setText("");
tfValue.setText("");
}//end of try block
catch(NumberFormatException e) {
JOptionPane.showMessageDialog(this, "Please fill out all fields and enter only numbers");
}//end of catch block
}
private void buttonEditActionPerformed(java.awt.event.ActionEvent evt) {
//edit info based on row selected
//make sure a row is selected
if(tableRadio.getSelectedRow() >= 0){
//set the values in the table for all text fields
tableModel.setValueAt(tfMonth.getText() + "/" + tfDay.getText() + "/" + tfYear.getText() + " " + tfHour.getText() + ":" + tfMin.getText(), tableRadio.getSelectedRow(), 0);
tableModel.setValueAt(tfValue.getText(), tableRadio.getSelectedRow(), 1);
//clear the user interface controls after adding them to the table
tfMonth.setText("");
tfDay.setText("");
tfYear.setText("");
tfHour.setText("");
tfMin.setText("");
tfValue.setText("");
}//end of if block checking for selected row
else{
JOptionPane.showMessageDialog(this, "Please select a row.");
}//end of else block
}
private void buttonRemoveActionPerformed(java.awt.event.ActionEvent evt) {
//Delete the selected row
//Make sure a row is selected
if(tableRadio.getSelectedRow() >= 0){
//remove the row
tableModel.removeRow(tableRadio.getSelectedRow());
//clear the user interface controls after deleting a row
tfMonth.setText("");
tfDay.setText("");
tfYear.setText("");
tfHour.setText("");
tfMin.setText("");
tfValue.setText("");
}//end of if block
else{
JOptionPane.showMessageDialog(this, "Please select a row.");
}//end of else block
}
private void buttonGraphActionPerformed(java.awt.event.ActionEvent evt) {
//instantiate the data series and the chart
int row = tableRadio.getRowCount();
int column = tableRadio.getColumnCount();
for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
series.add(r, c);
}
}
}
private void tfValueActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {
try {
// capture the whole screen
BufferedImage radioGraph = new Robot().createScreenCapture(
new Rectangle( panelGraph.getX(), panelGraph.getY(), panelGraph.getWidth(), panelGraph.getHeight() ) );
//Save as PNG
File file = new File("radioGraph.png");
ImageIO.write(radioGraph, "png", file);
JOptionPane.showMessageDialog(this, "radioGraph.png added to project folder");
}
catch(AWTException e) {
JOptionPane.showMessageDialog(this, "Error");
}
catch(IOException e){
JOptionPane.showMessageDialog(this, "Error");
}
}
/**
* #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(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainWindow.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 MainWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonAdd;
private javax.swing.JButton buttonEdit;
private javax.swing.JButton buttonGraph;
private javax.swing.JButton buttonLoad;
private javax.swing.JButton buttonRemove;
private javax.swing.JButton buttonSave;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labelDay;
private javax.swing.JLabel labelHour;
private javax.swing.JLabel labelMin;
private javax.swing.JLabel labelMonth;
private javax.swing.JLabel labelValue;
private javax.swing.JLabel labelYear;
private javax.swing.JPanel panelGraph;
private javax.swing.JTable tableRadio;
private javax.swing.JTextField tfDay;
private javax.swing.JTextField tfHour;
private javax.swing.JTextField tfMin;
private javax.swing.JTextField tfMonth;
private javax.swing.JTextField tfValue;
private javax.swing.JTextField tfYear;
// End of variables declaration
Any Ideas on what might work for me? I've never had to get data from a table and graph it so this is all new to me. Please let me know if I've messed up somewhere.
series.add(r, c);
That won't do anything. You are just getting the indexes of your loop.
You want something like:
series.add( tableRadio.getValueAt(r, c) );
Of course the getValueAt(...) method just returns an Object so you will need to convert the Object to the data type needed for the series Object.
Also if you need two parameter for the series Object, then you will obviously need two getValueAt(...) statements. Maybe you only have two columns, so you only need a single loop on the rows and then you get the value from column 0 and column 1? Only you know the data you have in your table.

Repaint doesn't work and the value of my private fields won't change?

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 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 0).
Can somebody please help me, I've been working on this project for days.
My Gui-class:
import java.awt.Graphics;
public class Gui extends javax.swing.JFrame {
public Gui() {
initComponents();
panel = new javax.swing.JPanel();
}
/**
* 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) {
Grafiek graf = new Grafiek();
graf.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
}
And my "Grafiek"-class:
import java.awt.Graphics;
public class Grafiek extends javax.swing.JPanel {
private String[] punt;
private int[] punti;
private int afstandX, afstandY, puntX1=0, puntY1=0, puntX2=0, puntY2=0;
private int max=1;
/**
* Creates new form Grafiek
*/
public Grafiek() {
initComponents();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
try{
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;
puntY2 = 0;
}catch(java.lang.NullPointerException npe) {
super.paintComponent(g);
}
}
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>
}
The code does not work because you add your points to the wrong object.
First of all, your panel object is not of type Grafiek, second of all it is first initialized in the method initComponents() and then overwritten again in the constructor.
Second problem, in the method verversActionPerformed called by the action listener, you create a new instance of Grafiek that is obviously not the one you have created/added before.
Thus, to make it work alter the code as follows:
The constructor should look the following:
public Gui() {
initComponents();
//panel = new javax.swing.JPanel();
}
The method like this:
private void verversActionPerformed(java.awt.event.ActionEvent evt) {
Grafiek graf = (Grafiek)panel;
graf.verwerkData(punten.getText());
}
Thus, it works as you expected.
However, this is far away from good code. You should set the type of variable panel to the correct type Grafiek.

How do I change the colors of my flower using a ComboBox? (java)

I want only the petals of my flowers to change color. I've gotten it to work with a textfield but I've decided a combobox would be better(so my lecturer knows which colors he can choose).
I saw a few examples where they would make the selection in the combobox show up in a textfield but I'm not sure how to do that with my flowers.
So in short, how do I get the combobox to change the color of my flower petals and would an array be better(and why/not)?
Picture - http://s903.photobucket.com/user/Nicole_Pretorius/media/Flowers_zps936f6f40.jpg.html
Code for Frame:
package Versie4;
public class FrameFlowers extends javax.swing.JFrame {
public FrameFlowers() {
initComponents();
setSize(900, 600);
setContentPane(new PanelFlowers());
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, 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(FrameFlowers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrameFlowers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrameFlowers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrameFlowers.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 FrameFlowers().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}
Code for Panel:
package Versie4;
import java.awt.Color;
import java.awt.Graphics;
public class PanelFlowers extends javax.swing.JPanel {
private int amount;
private String color = "";
public PanelFlowers() {
initComponents();
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int teller;
g.setColor(Color.RED); //flowerpot
g.fillRect(300, 350, 500, 100);
int x = 1;
for (teller=1; teller <= amount ;teller++) {
//Flower 1
g.setColor(Color.GREEN); //stem
g.fillRect(320 + x, 250, 10, 100);
switch (color) { //Colours of petals
case "red":
g.setColor(Color.red);
break;
case "blue":
g.setColor(Color.blue);
break;
case "yellow":
g.setColor(Color.yellow);
break;
case "orange":
g.setColor(Color.orange);
break;
case "pink":
g.setColor(Color.PINK);
break;
case "purple":
g.setColor(new Color(102, 0, 204));
break;
}
g.fillOval(304 + x, 190, 40, 40); //petals
g.fillOval(330 + x, 210, 40, 40);
g.fillOval(320 + x, 240, 40, 40);
g.fillOval(290 + x, 240, 40, 40);
g.fillOval(280 + x, 210, 40, 40);
g.setColor(Color.YELLOW); //pistil
g.fillOval(312 + x, 225, 25, 25);
x = teller * 80;
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
lblamount = new javax.swing.JLabel();
txtamount = new javax.swing.JTextField();
lblcolor = new javax.swing.JLabel();
txtcolor = new javax.swing.JTextField();
btngrow = new javax.swing.JButton();
btnreset = new javax.swing.JButton();
colorCombo = new javax.swing.JComboBox();
lblamount.setText("Amount: ");
txtamount.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtamountActionPerformed(evt);
}
});
lblcolor.setText("Color: ");
txtcolor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtcolorActionPerformed(evt);
}
});
btngrow.setText("Grow!");
btnreset.setText("Reset Size");
colorCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "red", "blue", "yellow", "orange", "pink", "purple" }));
colorCombo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
colorComboActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblamount)
.addGap(18, 18, 18)
.addComponent(txtamount, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41)
.addComponent(lblcolor)
.addGap(18, 18, 18)
.addComponent(txtcolor, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(60, 60, 60)
.addComponent(btngrow)
.addGap(18, 18, 18)
.addComponent(btnreset))
.addGroup(layout.createSequentialGroup()
.addGap(211, 211, 211)
.addComponent(colorCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(230, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblamount)
.addComponent(txtamount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblcolor)
.addComponent(txtcolor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btngrow)
.addComponent(btnreset))
.addGap(42, 42, 42)
.addComponent(colorCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(350, Short.MAX_VALUE))
);
}// </editor-fold>
private void txtamountActionPerformed(java.awt.event.ActionEvent evt) {
amount = Integer.parseInt(txtamount.getText());
color = this.txtcolor.getText();
repaint();
}
private void txtcolorActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void colorComboActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
// Variables declaration - do not modify
private javax.swing.JButton btngrow;
private javax.swing.JButton btnreset;
private javax.swing.JComboBox colorCombo;
private javax.swing.JLabel lblamount;
private javax.swing.JLabel lblcolor;
private javax.swing.JTextField txtamount;
private javax.swing.JTextField txtcolor;
// End of variables declaration
}
So in short, how do I get the combobox to change the color of my
flower petals and would an array be better(and why/not)?
Yes, obviously. JComboBox is a user input controlling component. It lets user to select item among various other items with same type but different taste. Array is not a component. It is just a inner data structure which we can use to maintain(add, save, remove) the item, nothing more. Well JComboBox has model known as DefaultComboBoxModel which internally contain such data structure and contain elements and manage them for us.
However, the way you are using JComboBox will get you into trouble, because if you select an item from the set of items, you will need to use if-else or switch-case check for finding the specific element. Apparently which is what you are doing now. As a solution which is simple(but rather junky):
public class PanelFlowers extends javax.swing.JPanel {
private int amount;
// private String color = "";
Color chosenColor;
public PanelFlowers() {
initComponents();
// repaint(); // <--- no need to call repaint in constructor
}
private void initComponents() {
// your other code------------
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.addElement(new Color(152, 52, 152));
model.addElement(new Color(152, 12, 52));
model.addElement(new Color(152, 142, 120));
colorCombo.setModel(model);
colorCombo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
JComboBox comb = (JComboBox)e.getSource();
chosenColor = (Color) comb.getSelectedItem();
repaint();
}
});
I have called the above solution junky. If you run the program by adopting the above approach you can actually directly use chosenColor instance to draw inside paintComponent function. Whenever you choose a Color from colorCombo you will see that now the program responds with the selected color item. But the item will appear in comboBox as: java.awt.Color[r=xxx,g=xxx,b=xxx] which is what probably you won't like.
How about learning about Color Chooser and make use of it.

action when component state changed

I have a series of radio buttons generated as an array and displayed in a jPanel.
I want a series of checkboxes in a second panel to be enbled when the radio buttons are in output state but not in the input (input or output are the radio choices).
I want to call the checking state method whenever any of the radiobuttons states change but don't know how to do this as they are created in an array.
Currently the method is called only when the radio button panel is actually clicked.
package my.ArduinoGUI;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
public class ArduinoGUI extends javax.swing.JFrame {
public ArduinoGUI() {
initCustomComponents();
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() {
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
digitalPinPanel = new javax.swing.JPanel(new GridLayout(0, 3));
jPanel3 = new javax.swing.JPanel(new GridLayout(0, 1));
jPanel2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Outputs"));
jPanel1.setName("Outputs"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 209, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 106, Short.MAX_VALUE)
);
digitalPinPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Digital Pin State"));
digitalPinPanel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseReleased(java.awt.event.MouseEvent evt) {
digitalPinPanelMouseReleased(evt);
}
});
digitalPinLabelArray = new javax.swing.JLabel[digitalPinTotal];
digitalPinRadioButtonArray = new javax.swing.JRadioButton[digitalPinTotal][2];
digitalPinGroupArray = new javax.swing.ButtonGroup[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinGroupArray[x] = new javax.swing.ButtonGroup(); // populate button group
digitalPinLabelArray[x] = new javax.swing.JLabel(); // populate label array
digitalPinLabelArray[x].setText("Pin " + (x +2));
digitalPinPanel.add(digitalPinLabelArray[x]); // add label to panel
for(int y = 0; y < 2; y++){
digitalPinRadioButtonArray[x][y] = new javax.swing.JRadioButton(); // populate radio button array
if (y == 0) {digitalPinRadioButtonArray[x][y].setText("Input");}
if (y == 1) {digitalPinRadioButtonArray[x][y].setText("Output"); digitalPinRadioButtonArray[x][y].setSelected(true);
}
digitalPinGroupArray[x].add(digitalPinRadioButtonArray[x][y]); // assign radio buttons to group
digitalPinPanel.add(digitalPinRadioButtonArray[x][y]); // add buttons to panel
}
}
jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Generated Boxes"));
digitalPinOutputArray = new javax.swing.JCheckBox[digitalPinTotal];
for(int x = 0; x < digitalPinTotal ; x++) {
digitalPinOutputArray[x] = new javax.swing.JCheckBox();
digitalPinOutputArray[x].setText("Output Pin " + (x+2));
jPanel3.add(digitalPinOutputArray[x]);
}
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Analog Pin State"));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 126, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, 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(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(digitalPinPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
);
digitalPinPanel.getAccessibleContext().setAccessibleName("DigitalPins");
pack();
}// </editor-fold>
private void digitalPinPanelMouseReleased(java.awt.event.MouseEvent evt) {
// if output selected enable checkbox otherwise disable it
for (int x = 0; x < digitalPinTotal; x++) {
if (digitalPinRadioButtonArray[x][0].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(false);
}
if (digitalPinRadioButtonArray[x][1].isSelected() == true) {
digitalPinOutputArray[x].setEnabled(true);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ArduinoGUI.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 ArduinoGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel digitalPinPanel;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
// End of variables declaration
private int digitalPinTotal = 12;
private int analogPinTotal = 8;
private javax.swing.JCheckBox[] digitalPinOutputArray;
private javax.swing.JRadioButton[][] digitalPinRadioButtonArray;
private javax.swing.ButtonGroup[] digitalPinGroupArray;
private javax.swing.JLabel[] digitalPinLabelArray;
private void initCustomComponents() {
//throw new UnsupportedOperationException("Not yet implemented");
// create checkbox array
}
}
digitalPinRadioButtonArray[x][y].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("Output"))
{
digitalPinOutputArray[2].setSelected(true);
}
}
});
try this

Categories

Resources