get usergroup of user in vbulletin using java and htmlunit - java

I am working on a login system that checks if the user is in a spesific usergroup.
If the user is in the usergroup "Access" then i want to show them the next form. If they are in the usergroup "registered user" it will display "Sorry, you dont have access"
This is my code so far: This will log in with 2 textboxes shown on a form.
I know i should not call "gettext();" on password field but i dont know how to code it so the htmlunit understands the characters and not puts in chars of array if i write "getpassword()"
/*
* 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 testmysql.gui;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
/**
*
* #author Kjetil
*/
public class Login extends javax.swing.JFrame {
public String setuser;
public String setpass;
public char[] input;
/**
* Creates new form Login
*/
public Login() {
initComponents();
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() {
jButton1 = new javax.swing.JButton();
txtboxPass = new javax.swing.JPasswordField();
txtboxUser = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1));
txtboxPass.setText("jPasswordField1");
getContentPane().add(txtboxPass, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, -1));
txtboxUser.setText("jTextField1");
getContentPane().add(txtboxUser, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 110, -1));
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
setuser = txtboxUser.getText();
setpass = txtboxPass.getText();
Login();
}
/**
* #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(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.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 Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPasswordField txtboxPass;
private javax.swing.JTextField txtboxUser;
// End of variables declaration
private void Login()
{
try {
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setCssEnabled(false); // I think this speeds the thing up
webClient.getOptions().setRedirectEnabled(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getCookieManager().setCookiesEnabled(true);
String url = "http://svergja.com/forum";
String name = setuser;
String pass = setpass;
HtmlPage page = webClient.getPage(url);
System.out.println(
"1st page : " + page.asText());
HtmlForm form = (HtmlForm) page.getElementById("navbar_loginform");
HtmlInput uName = (HtmlInput) form.getByXPath("//*[#id=\"navbar_username\"]").get(0);
uName.setValueAttribute(name);
HtmlPasswordInput password = (HtmlPasswordInput) form.getByXPath("//*[#id=\"navbar_password\"]").get(0);
password.setValueAttribute(setpass);
HtmlSubmitInput button = form.getInputByValue("Log in");
//(HtmlSubmitInput) form.getByXPath("//*[#id=\"loginbutton\"]").get(0);
WebWindow window = page.getEnclosingWindow();
button.click();
while (window.getEnclosedPage() == page) {
// The page hasn't changed.
Thread.sleep(500);
}
// This loop above will wait until the page changes.
page = (HtmlPage) window.getEnclosedPage();
System.out.println(
"2nd Page : " + page.asText());
webClient.closeAllWindows();
} catch (Exception ex) {
}
}
}
If the login is successful i want to start checking for the usergroup ID of the user. If i log in, my usergroup is Administrator. I will add a test user so you can log in and see for yourself.
(log in with this "you will be in the usergroup ("Registered Users")")
Forum url: http://svergja.com/forum
Username: stackoverflow
Password: stackit123
(test user information)

After the successfull login, use anchor to click profile link and then use span to get the usergroup.
The change in code will be:
private void Login() throws FailingHttpStatusCodeException, MalformedURLException, IOException
{
WebClient client = new WebClient();
client.setJavaScriptEnabled(false);
HtmlPage page = client.getPage("http://svergja.com/forum/");
HtmlForm form = (HtmlForm) page.getElementById("navbar_loginform");
HtmlTextInput username = (HtmlTextInput) page.getElementById("navbar_username");
username.setValueAttribute("stackoverflow");
HtmlPasswordInput password = (HtmlPasswordInput) page.getElementById("navbar_password");
password.setValueAttribute("stackit123");
HtmlSubmitInput button = form.getInputByValue("Log in");
page = button.click();
List<HtmlAnchor> anchorList = page.getAnchors();
for (HtmlAnchor htmlAnchor : anchorList) {
if(htmlAnchor.getAttribute("href").contains("member.php?"))
{
page = htmlAnchor.click();
}
}
HtmlSpan span = (HtmlSpan) page.getElementById("userinfo");
DomNodeList<DomNode> nodeList = span.getChildNodes();
for (DomNode domNode : nodeList) {
NamedNodeMap map = domNode.getAttributes();
Node node = map.getNamedItem("class");
if(node != null && node.getNodeValue() != null && node.getNodeValue().equals("usertitle"))
{
System.out.println("The usergroup is "+domNode.getTextContent());
}
}
}

Related

Why this actionEvent on a Java Swing menu item does not work?

I have created a basic JFrame using NetBeans form designer. I have reduced it to just a couple of menu items.
I intend to do something when user clicks on "Open", my understanding is that I have to add an "actionPerformed" through a listener, which can be done using NetBeans Designer.
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("ACTION PERFORMED");
}
But when I click on "Open" nothing happens I can not see the output message.
This is my main routine:
package test.dbviewer;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SealionDBViewer {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel ("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
JFrame databaseViewer = new DatabaseViewer();
databaseViewer.setVisible(true);
}
}
This is the reproducible code that NetBeans generate:
package test.dbviewer;
public class DatabaseViewer extends javax.swing.JFrame {
/**
* Creates new form DatabaseViewer
*/
public DatabaseViewer() {
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() {
jSplitPane1 = new javax.swing.JSplitPane();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuBar2 = new javax.swing.JMenuBar();
jMenu3 = new javax.swing.JMenu();
jMenu4 = new javax.swing.JMenu();
jMenuItem1.setText("jMenuItem1");
jMenuItem2.setText("jMenuItem2");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu3.setText("Open");
jMenu3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu3ActionPerformed(evt);
}
});
jMenuBar2.add(jMenu3);
jMenu4.setText("Exit");
jMenuBar2.add(jMenu4);
setJMenuBar(jMenuBar2);
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, 267, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jMenu3ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("ACTION PERFORMED");
}
/**
* #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(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DatabaseViewer.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 DatabaseViewer().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenuBar jMenuBar2;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JSplitPane jSplitPane1;
// End of variables declaration
}

Using a Timer in Swing to display a picture for 5 seconds

I am trying to make a login picture for my application using Timer. The idea is, when the user opens the application, he will see a picture for 5 seconds, then the application will start.
I tried, as you can see in the method shoutoff():
/*
* 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 login;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
/**
*
* #author isslam
*/
public class login extends javax.swing.JFrame {
Timer time;
/**
* Creates new form login
*/
public login() {
initComponents();
setLocation(350, 200);
time = new Timer(5000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
time.setRepeats(false);
}
public void shoutoff(){
if (!time.isRunning()) {
time.start();
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setLocationByPlatform(true);
setUndecorated(true);
setResizable(false);
jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\isslam\\Desktop\\one_piece_marble_play_by_iviarker-d511vb0.jpg")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
);
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(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(login.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 login().setVisible(true);
new login().shoutoff();
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Start by creating the Timer once in the constructor. The Timer should, also, only make the CURRENT instance of login close
public login() {
//...
time = new Timer(5000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
timer.setRepeats(false);
}
In the shoutoff method, you start timer...
public void shoutoff(){
if (!time.isRunning()) {
timer.start();
}
}
Take a closer look at How to use Swing Timers for more details.
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
The idea is, when the user opens the application, he will see a picture for 5 seconds, then the application will start.
You should use a Splash Screen. The advantage of the splash screen is the image is displayed immediately as the whole Swing app doesn't need to be loaded.
Check out the section from the Swing tutorial on How to Create a Splash Screen for more information and a working example.

Setting input box next to text (Java)

So I am trying to get my text input box for my fish sandwich next to the text for it. It keeps pushing down next to the hamburger input box. I cannot seem to get it next to it. Here is the code.
here is a screenshot
/*
* 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 foodproject2;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
/**
*
* #author Travis
*/
public class Menu1 extends javax.swing.JFrame {
private Container contents;
private JLabel name, courseNum, welcome, prompt, chickP, fishP, burgerP;
private JLabel chargeSand, chargeService, totalBill;
private JTextField numChick, numFish, numBurger;
private JButton compute;
public Menu1()
{
super("Travis' Menu");
contents = getContentPane();
contents.setLayout(new FlowLayout());
name=new JLabel("Programmer: Travis Easton");
courseNum=new JLabel("ITSD424");
welcome=new JLabel("Welcome To Travis' Sandwich Shop");
prompt=new JLabel("Enter number of Sandwiches for each; 0 if none");
chickP=new JLabel("Chicken Sandwiches # $4.99 each");
chickP.setForeground(Color.BLACK);
numChick=new JTextField(3);
fishP=new JLabel("Salmon Sandwiches # $4.99 each ");
fishP.setForeground(Color.BLACK);
numFish=new JTextField(3);
burgerP=new JLabel("Hamburger # $4.99 each");
burgerP.setForeground(Color.BLACK);
numBurger=new JTextField(3);
chargeSand = new JLabel("Charge for Sandwiches = $");
chargeService = new JLabel("Charge for Service = $");
totalBill= new JLabel("Total Bill = $");
chargeSand = new JLabel("Sandwich cost");
chargeService = new JLabel("Tax");
totalBill = new JLabel("Total");
compute = new JButton("Bill Total");
contents.add(name);
contents.add(courseNum);
contents.add(welcome);
contents.add(prompt);
contents.add(chickP);
contents.add(numChick);
contents.add(fishP);
contents.add(burgerP);
contents.add(numFish);
contents.add(numBurger);
contents.add(chargeSand);
contents.add(chargeService);
contents.add(totalBill);
contents.add(chargeSand);
contents.add(chargeService);
contents.add(totalBill);
contents.add(compute);
ButtonHandler bh = new ButtonHandler();
compute.addActionListener(bh);
setSize(400,400);
setVisible(true);
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e) {
try
{
double one = Double.parseDouble(numChick.getText());
double two = Double.parseDouble(numFish.getText());
double three = Double.parseDouble(numBurger.getText());
// Calculations for determining total price of bill
double orderAmount = (one*4.99)+(two*4.99)+(three*4.99);
double serviceAmount = (orderAmount)*.15;
double totalAmount = (orderAmount+serviceAmount);
// Now to display the charges
chargeSand.setText(new Double(orderAmount).toString());
chargeService.setText(new Double(serviceAmount).toString());
totalBill.setText(new Double(totalAmount).toString());
}
catch(NumberFormatException ex)
{
numChick.setText("0");
numFish.setText("0");
numBurger.setText("0");
totalBill.setText("0");
}
}
}
/**
* Creates new form Menu
*/
{
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">//GEN-BEGIN:initComponents
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>//GEN-END:initComponents
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Menu1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu1.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 Menu1().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
In you code, the string that you have passed into the fishP JLabel contains spaces at the end.
I think it should be:
fishP=new JLabel("Salmon Sandwiches # $4.99 each");
One more change:
contents.add(chickP);
contents.add(numChick);
contents.add(fishP);
contents.add(numFish);
contents.add(burgerP);
contents.add(numBurger);
When you add the content you are doing it in the wrong order:
contents.add(chickP);
contents.add(numChick);
contents.add(fishP);
contents.add(burgerP);
contents.add(numFish);
contents.add(numBurger);
Move numFish up.

Open a console alongside a Swing GUI in java

I am building an application with a Swing GUI. If you would would open this program from the command line, Some text will print (info and error messages). The program is just a normal executable jar file, but for the people who want to see a console I want an option to open a console from the Swing GUI, which displays all these messages, outputted by System.out.print(). I have seen several applications which have such a function, but I don't know how to do this.
The basics are explained at https://blogs.oracle.com/nickstephen/entry/java_redirecting_system_out_and. That example uses logging to redirect stdout and stderr. A simple approach could be to first define an OutputStream that writes to the "console":
package outerr;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JTextArea;
public class PrintOutErrStream extends ByteArrayOutputStream {
final int maxTextAreaSize = 1000;
private JTextArea textArea;
public PrintOutErrStream(JTextArea textArea) {
this.textArea = textArea;
}
public void flush() throws IOException {
synchronized(this) {
super.flush();
String outputStr = this.toString();
super.reset();
if(textArea.getText().length() > maxTextAreaSize) {
textArea.replaceRange("", 0, 100);
}
textArea.append(outputStr);
}
}
}
Then this is the remaining part of a demo program:
package outerr;
import java.io.PrintStream;
public class StdOutErr extends javax.swing.JFrame {
/** Creates new form StdOutErr */
public StdOutErr() {
initComponents();
PrintOutErrStream poes = new PrintOutErrStream(this.jTextAreaOutErrLog);
System.setErr(new PrintStream(poes, true));
System.setOut(new PrintStream(poes, true));
}
/** 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() {
java.awt.GridBagConstraints gridBagConstraints;
jButtonStdout = new javax.swing.JButton();
jButtonStderr = new javax.swing.JButton();
jPanelOutErrLog = new javax.swing.JPanel();
jScrollPaneOutErrLog = new javax.swing.JScrollPane();
jTextAreaOutErrLog = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new java.awt.FlowLayout());
jButtonStdout.setText("stdout");
jButtonStdout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonStdoutActionPerformed(evt);
}
});
getContentPane().add(jButtonStdout);
jButtonStderr.setText("stderr");
jButtonStderr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonStderrActionPerformed(evt);
}
});
getContentPane().add(jButtonStderr);
jTextAreaOutErrLog.setColumns(20);
jTextAreaOutErrLog.setRows(5);
jScrollPaneOutErrLog.setViewportView(jTextAreaOutErrLog);
javax.swing.GroupLayout jPanelOutErrLogLayout = new javax.swing.GroupLayout(jPanelOutErrLog);
jPanelOutErrLog.setLayout(jPanelOutErrLogLayout);
jPanelOutErrLogLayout.setHorizontalGroup(
jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 835, Short.MAX_VALUE)
.addGroup(jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneOutErrLog, javax.swing.GroupLayout.DEFAULT_SIZE, 835, Short.MAX_VALUE))
);
jPanelOutErrLogLayout.setVerticalGroup(
jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 378, Short.MAX_VALUE)
.addGroup(jPanelOutErrLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPaneOutErrLog, javax.swing.GroupLayout.DEFAULT_SIZE, 378, Short.MAX_VALUE))
);
getContentPane().add(jPanelOutErrLog);
pack();
}// </editor-fold>
private void jButtonStdoutActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("message via stdout");
}
private void jButtonStderrActionPerformed(java.awt.event.ActionEvent evt) {
System.err.println("message via stderr");
}
/**
* #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(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StdOutErr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StdOutErr.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 StdOutErr().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonStderr;
private javax.swing.JButton jButtonStdout;
private javax.swing.JPanel jPanelOutErrLog;
private javax.swing.JScrollPane jScrollPaneOutErrLog;
private javax.swing.JTextArea jTextAreaOutErrLog;
// End of variables declaration
}

How do I pass data between cards in Java CardLayout

I am new to working with Java GUI, I know this may sound ridiculous but I have been trying for days to pass data between cards on the CardLayout layout. I am using netbeans, the first card displays a list clients. When a client is selected, the choice selection is passed to a variable on that card. The next card queries the database to show more details about the client selected. I can handle the switching between cards but my problem is I can't pass the data stored in the variable on card 1 to card 2.
I have visited several forums and read through similar questions asked but I just cannot get any of the proposed solutions to work. Please help, I'm new at this so please go easy on me, thanks.
Here is the class that holds the panels
public class mainframe extends javax.swing.JFrame {
public mainframe() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
displayScrollPane = new javax.swing.JScrollPane();
displaypanel = new javax.swing.JPanel();
viewclientspanel1 = new viewclientspanel();
addclientpanel1 = new addclientpanel();
clientdetails1 = new clientdetails();
mainmenu = new javax.swing.JMenuBar();
clients = new javax.swing.JMenu();
viewclients = new javax.swing.JMenuItem();
addclient = new javax.swing.JMenuItem();
transactions = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
displaypanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
displaypanel.setLayout(new java.awt.CardLayout());
viewclientspanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
viewclientspanel1MouseClicked(evt);
}
});
displaypanel.add(viewclientspanel1, "viewclientscard");
displaypanel.add(addclientpanel1, "addclientcard");
displaypanel.add(clientdetails1, "clientdetailscard");
displayScrollPane.setViewportView(displaypanel);
clients.setText("Clients");
viewclients.setText("View Clients");
viewclients.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewclientsActionPerformed(evt);
}
});
clients.add(viewclients);
viewclients.getAccessibleContext().setAccessibleParent(mainmenu);
addclient.setText("Add Client");
addclient.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addclientActionPerformed(evt);
}
});
clients.add(addclient);
mainmenu.add(clients);
transactions.setText("Transactions");
mainmenu.add(transactions);
setJMenuBar(mainmenu);
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()
.addComponent(displayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 1059, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(99, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(66, Short.MAX_VALUE)
.addComponent(displayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 570, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33))
);
pack();
}// </editor-fold>
private void addclientActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) displaypanel.getLayout();
card.show(displaypanel, "addclientcard");
}
private void viewclientsActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) displaypanel.getLayout();
card.show(displaypanel, "viewclientscard");
}
private void viewclientspanel1MouseClicked(java.awt.event.MouseEvent evt) {
//viewclientspanel1.getComponentListeners();
}
/**
* #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(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(mainframe.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 mainframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem addclient;
private addclientpanel addclientpanel1;
private clientdetails clientdetails1;
private javax.swing.JMenu clients;
private javax.swing.JScrollPane displayScrollPane;
private javax.swing.JPanel displaypanel;
private javax.swing.JMenuBar mainmenu;
private javax.swing.JMenu transactions;
private javax.swing.JMenuItem viewclients;
private viewclientspanel viewclientspanel1;
// End of variables declaration
}
The class of the card that displays a list of the clients to choose from has a mouse event listener which gets the value of the client selected and switches the the next card
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
CardLayout card = (CardLayout) jPanel1.getParent().getParent().getParent().getParent().getLayout();
card.show(jPanel1.getParent().getParent().getParent().getParent(), "clientdetailscard");
}
Lastly the class that I need to transfer the client selected information to which dsiplays the more details.
public class clientdetails extends javax.swing.JPanel {
public clientdetails() {
initComponents();
}
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(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
JFrame f = new JFrame("Window");
f.add(new clientdetails());
f.setSize(500, 700);
f.setVisible(true);
}
private javax.swing.JPanel jPanel1;
}
You could pass the client information from one pane to the other using setters/getters...
clientDetailsPane.setClient(clientListPanel.getClient());
// Switch panels...
I was also thinking that you could use some kind of model or Map, but that is probably overkill for what you want to achieve...
Thanks a lot guys, I ended up using a class container to hold the variables I need transferred.
public class varcontainer {
public String variablename;
private static varcontainer instance = null;
public static varcontainer getInstance(){
if(instance == null){
instance = new varcontainer();
}
return instance;
}
}
I then call the getInstance from another class to get the current instance of the container and access the variables
varcontainer.getInstance().variablename
Thanks again for the feedback, I appreciate it.

Categories