Card Layout get the current card string [duplicate] - java

This question already has answers here:
CardLayout get the selected card's name
(2 answers)
Closed 6 years ago.
i'm using cardlayout in application and want to get the name of the current active card
i tried many methods but with no mean, for example this method seems to be no longer exists
panel.getLayout().getActiveItem()
also i tried this but it doesn't work too
Panel card = null;
for (Component comp : cardPanel.getComponents()) {
if (comp.isVisible()) {
System.out.println(card.getName());
}
}
for example: the following stamts adds several panels to a card layout, i want to return 1,2,3,4 or 5 of the currently active card:
cardPanel.add(firstP, "1");
cardPanel.add(secondP, "2");
cardPanel.add(thirdP, "3");
cardPanel.add(fourthP, "4");
cardPanel.add(fifthP, "5");
what's the possible ways to do that?

CardLayout does not expose its own mapping between of components and its keys (here 1, 2, 3, 4...), so using the layout itself will not reveal how the "cards" are hashed.
If you wish to use the getName method, remember that you must set this yourself first as the field is not set by default:
firstPanel.setName("1");
cardPanel.add(firstPanel, firstPanel.getName());
then, using your for loop, you will be able to get the current card String.

there are two ways
determine visible JComponent from current card
putClientProperty (setName, etc) add listeneing byAncestorListener or HierarchyListener
code
(Disclaimer, Notice this is only code example with Thread.sleep(int), and works only in this form, there is designedly locked Event Dispatch Thread)
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
public class CardlayoutTest extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel pnlA, pnlB, pnlC;
public CardLayout card = new CardLayout();
public CardlayoutTest() {
EventHandler eventHandle = new EventHandler();
pnlA = new JPanel(new BorderLayout());
pnlA.add(new JButton("A"), BorderLayout.CENTER);
pnlA.putClientProperty("JPanel", "JPanel_a");
pnlB = new JPanel(new BorderLayout());
pnlB.add(new JButton("B"), BorderLayout.CENTER);
pnlB.putClientProperty("JPanel", "JPanel_b");
pnlC = new JPanel(new BorderLayout());
pnlC.add(new JButton("C"), BorderLayout.CENTER);
pnlC.putClientProperty("JPanel", "JPanel_c");
pnlA.addAncestorListener(eventHandle);
pnlA.addHierarchyListener(eventHandle);
pnlB.addAncestorListener(eventHandle);
pnlB.addHierarchyListener(eventHandle);
pnlC.addAncestorListener(eventHandle);
pnlC.addHierarchyListener(eventHandle);
setLayout(card);
add(pnlA, "A");
add(pnlB, "B");//
add(pnlC, "C");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class EventHandler implements AncestorListener, HierarchyListener {
#Override
public void ancestorAdded(AncestorEvent event) {
JComponent comp2 = event.getComponent();
String str = (String) comp2.getClientProperty("JPanel");
System.out.println("ancestorAdded " + str);
}
#Override
public void ancestorMoved(AncestorEvent event) {
JComponent comp2 = event.getComponent();
String str = (String) comp2.getClientProperty("JPanel");
System.out.println("ancestorMoved " + str);
}
#Override
public void ancestorRemoved(AncestorEvent event) {
JComponent comp2 = event.getComponent();
String str = (String) comp2.getClientProperty("JPanel");
System.out.println("ancestorRemoved " + str);
}
#Override
public void hierarchyChanged(HierarchyEvent e) {
JComponent comp2 = (JComponent) e.getComponent();
String str = (String) comp2.getClientProperty("JPanel");
System.out.println("hierarchyChanged " + str);
}
}
public static void main(String[] args) {
CardlayoutTest t = new CardlayoutTest();
t.setSize(300, 200);
System.out.println("CardlayoutTest.main()------------------------ FIRST");
t.card.show(t.getContentPane(), "A");
t.setVisible(true);
System.out.print("\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("CardlayoutTest.main()------------------------ SECOND");
t.card.show(t.getContentPane(), "B");
System.out.print("\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("CardlayoutTest.main()------------------------ THIRD");
t.card.show(t.getContentPane(), "C");
System.out.print("\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("CardlayoutTest.main()------------------------ SECOND");
t.card.show(t.getContentPane(), "B");
System.out.print("\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("CardlayoutTest.main()------------------------ FIRST");
t.card.show(t.getContentPane(), "A");
System.out.print("\n");
}
}

Related

How to use a boolean outside the scope of a key listener

I created a shop cart login JFrame and I added a "shopkeeperToggle" so that when it's pressed the user logs in to the shopkeeper's JFrame and otherwise to a shopper's jframe. the problem is I don't know how to implement it, I tried to set a boolean "pressed" to false whenever the key is released in the "shopkeeperToggle" key listener, and apparently I'm unable to use the value of pressed inside the sign-in button.
Here's the code for the toggle:
shopkeeperToggle = new JToggleButton("Shopkeeper");
shopkeeperToggle.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
pressed = false;
}
});
and this is what I'm trying to do in the sign in button:
signinButton = new JButton("Sign in ");
signinButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3308/shoppingCart","root","");
// select the users that have the inputted credentials from the database
String sql = "SELECT * FROM users WHERE userUsername = ? AND userEmail =?AND userPassword = ? ";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,usernamelogin.getText());
ps.setString(2, emaillogin.getText());
ps.setString(3,passwordlogin.getText());
ResultSet rs = ps.executeQuery();
// if query executed and
if (rs.next()) {
// if login succ show window log succ, and go to home shopping page
JOptionPane.showMessageDialog(null,"Login successful! :)");
/////////////////this is where I fail////////////////////
if (pressed) {
OwnerHomePage ownerhome = new OwnerHomePage();
ownerhome.setVisible(true);
setVisible(false);
} else {
UserHomePage home = new UserHomePage();
home.setVisible(true);
setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null,"Wrong Username or Email or Password :(");
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null,e1);
}
}
}
This may offer some help in fixing your issue. It is a fully compilable demo. The following changes were made.
Used Actions in lieu of KeyListener. A little more involved to setup but they can be configured to monitor only certain keys.
Used a JButton in lieu of a JToggleButton. No specific reason and can be changed.
Created separate inner classes for the listeners. Tends to reduce clutter and is usually more readable.
Changed the name of the button depending on the mode.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class ActionMapAndButtons {
JFrame frame = new JFrame("Demo");
public static void main(String[] args) {
SwingUtilities
.invokeLater(() -> new ActionMapAndButtons().start());
}
public void start() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyClass cls = new MyClass();
frame.add(cls);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class MyClass extends JPanel {
JButton button = new JButton("Shopper Sign in");
boolean pause = false;
public MyClass() {
setPreferredSize(new Dimension(300, 300));
button.addActionListener(new ButtonListener());
add(button);
InputMap map = getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
for (int i = 0; i < 256; i++) {
map.put(KeyStroke.getKeyStroke((char)i), "anyKey");
}
getActionMap().put("anyKey", new MyAction());
setFocusable(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj instanceof JButton) {
JButton b = (JButton) obj;
pause = !pause;
if (pause) {
b.setText("Shopkeeper Sign in");
} else {
b.setText("Shopper Sign in");
}
}
}
}
private class MyAction extends AbstractAction {
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if (pause) {
System.out.println("Shopkeeper - " + cmd);
} else {
System.out.println("Shopper - " + cmd);
}
}
}
}
Inner (or nested) classes and action maps are covered in The Java Tutorials
You can define pressed as a static value;
class c {
static boolean pressed = true;
...
}
and you can access anywhere;
c.pressed; //will return true if you don't change

I am trying to create a Java program that will make the letters appear one at a time in a JLabel

I am trying to create a program in java that makes the letters of a string appear one at a time into a JLabel, but the text just appears all at once every time. The more the delay on the Thread.Sleep();, the longer it takes to appear. I think what is happening is that it is writing it all out and then printing it into the Label, but i still don't know what to do to fix it. The code is here:
package uiTesting;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class ScrollingText extends JFrame {
private JPanel contentPane;
//Variables and values
public static String ThingToBePrinted = "You look down the gigantic hallway, the cold breath of spirits breathing down your neck. "
+ "Its nothing you haven't felt before. The spirits of those long past were always closer here, where many of them met"
+ " their end. Maybe you would be one of them, someday. But not today. Today, there was still too much to be done to rest.";
public static String ThingPrinted = "";
public static int Mili = 100;
public String html1 = "<html><body style='width: ";
public String html2 = "px'>";
/**
* Launch the application.
*/
public static void main(String[] args) {
System.out.println(ThingToBePrinted.length());
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScrollingText frame = new ScrollingText();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ScrollingText() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 719, 504);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//The only Label
JLabel Scrolling_L1 = new JLabel("");
Scrolling_L1.setFont(new Font("Tahoma", Font.PLAIN, 15));
Scrolling_L1.setVerticalAlignment(SwingConstants.TOP);
Scrolling_L1.setBounds(10, 11, 693, 354);
contentPane.add(Scrolling_L1);
//The only Button
JButton Master_B1 = new JButton("Print Text");
Master_B1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
//scrolling function
for (int i = 0; i < ThingToBePrinted.length(); i++) {
String x = String.valueOf(ThingToBePrinted.charAt(i));
ThingPrinted = ThingPrinted + x;
Scrolling_L1.setText(html1 + "500" + html2 + ThingPrinted); //Html for wrapping text
Thread.sleep(Mili); //Delay between letters
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error");
}
}
});
Master_B1.setFont(new Font("Tahoma", Font.PLAIN, 25));
Master_B1.setBounds(164, 385, 375, 70);
contentPane.add(Master_B1);
}
}
I would really appreciate any solution at this point, I've been troubleshooting for hours
Your problem is related to how concurrency works in Swing. One (imperfect) solution is to use a SwingWorker. You could change your action listener to this:
Master_B1.addActionListener(event -> {
SwingWorker<Object, Void> worker = new SwingWorker<Object, Void>() {
#Override
protected String doInBackground() throws InterruptedException {
for (int i = 0; i < ThingToBePrinted.length(); i++) {
ThingPrinted += ThingToBePrinted.charAt(i);
Scrolling_L1.setText(html1 + "500" + html2 + ThingPrinted); // Html for wrapping text
Thread.sleep(Mili); //Delay between letters
}
return null;
}
};
worker.execute();
});
Read this tutorial: Lesson: Concurrency in Swing to get a better understanding of the topic. (You might want to read up on concurrency in Java in general also, see this tutorial for example).
It is because you are updating the JLabel in the UI thread itself from the event handler. Better way is to start a new thread in the event handler and then update the JLabel from this new thread. Following is the section you need to use in your code. I have tested it, it works.
Master_B1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try { // Start new thread here for updating JLabel.
new Thread() {
public void run() {
//scrolling function
for (int i = 0; i < ThingToBePrinted.length(); i++) {
String x = String.valueOf(ThingToBePrinted.charAt(i));
ThingPrinted = ThingPrinted + x;
Scrolling_L1.setText(html1 + "500" + html2 + ThingPrinted); //Html for wrapping text
try {
Thread.sleep(Mili); // Delay between letters
} catch (Exception e) {
}
}
}
}.start();
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error");
}
}
});

How to Remove Mask of JFormattedTextField?

I've a JFormattedTextField controlled by two RadioButton. In one of RadioButton I set the mask and the other I want to clear the mask and type normally. After set to type normally it doesn't return the value of getText(), the value only return if the mask is setted.
How could fix this problem ?
private void setMask() {
MaskFormatter formatter = null;
try {
txtPesquisar.setValue(null);
if (rbNome.isSelected()) {
//clear mask to type normally
formatter = new MaskFormatter("****************************************");
formatter.setPlaceholderCharacter(' ');
} else {
//set mask
formatter = new MaskFormatter("###.###.###-##");
formatter.setPlaceholderCharacter(' ');
}
txtPesquisar.setFormatterFactory(new DefaultFormatterFactory(formatter));
txtPesquisar.requestFocus();
txtPesquisar.selectAll();
} catch (ParseException ex) {
ex.printStackTrace();
}
}
Be sure to call commitEdit() on your JFormattedTextField before calling getValue(). As per the JFormattedTextField API section on getValue():
Returns the last valid value. Based on the editing policy of the AbstractFormatter this may not return the current value. The currently edited value can be obtained by invoking commitEdit followed by getValue.
Returns:
For example:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
#SuppressWarnings("serial")
public class TestFormattedField extends JPanel {
private JFormattedTextField txtPesquisar = new JFormattedTextField();
private JRadioButton rbNome = new JRadioButton("None");
private JRadioButton rbFormat = new JRadioButton("Format");
public TestFormattedField() {
txtPesquisar.setColumns(20);
ButtonGroup btnGroup = new ButtonGroup();
btnGroup.add(rbFormat);
btnGroup.add(rbNome);
rbNome.setSelected(true);
rbNome.setMnemonic(KeyEvent.VK_N);
rbFormat.setMnemonic(KeyEvent.VK_F);
add(txtPesquisar);
add(rbFormat);
add(rbNome);
setMask();
add(new JButton(new SetFormatAction()));
add(new JButton(new GetTextAction()));
}
private void setMask() {
MaskFormatter formatter = null;
try {
txtPesquisar.setValue(null);
if (rbNome.isSelected()) {
//clear mask to type normally
formatter = new MaskFormatter("****************************************");
formatter.setPlaceholderCharacter(' ');
} else {
//set mask
formatter = new MaskFormatter("###.###.###-##");
formatter.setPlaceholderCharacter(' ');
}
txtPesquisar.setFormatterFactory(new DefaultFormatterFactory(formatter));
txtPesquisar.requestFocus();
txtPesquisar.selectAll();
} catch (ParseException ex) {
ex.printStackTrace();
}
}
private class SetFormatAction extends AbstractAction {
public SetFormatAction() {
super("Set Format");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e) {
setMask();
}
}
private class GetTextAction extends AbstractAction {
public GetTextAction() {
super("Get Text");
putValue(MNEMONIC_KEY, KeyEvent.VK_G);
}
#Override
public void actionPerformed(ActionEvent e) {
final String text = txtPesquisar.getText();
try {
txtPesquisar.commitEdit();
} catch (ParseException e1) {
String title = "Incomplete Text Entry";
String msg = "Text -- " + text + " is not yet complete";
JOptionPane.showMessageDialog(TestFormattedField.this, msg, title, JOptionPane.ERROR_MESSAGE);
}
Object value = txtPesquisar.getValue();
System.out.println("text: " + text);
System.out.println("value: " + value);
}
}
private static void createAndShowGui() {
TestFormattedField mainPanel = new TestFormattedField();
JFrame frame = new JFrame("Test JFormattedField");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
In the future, please consider taking a little time to create and post a minimal example program or SSCCE since this would be the best and quickest way to get folks to fully understand your problem and then be able to help you. Please see my code as an example of this.
on form constructor after inintcomponets
public Form1() {
initComponents();
MaskFormatter dateMask;
try {
dateMask = new MaskFormatter("|#|#|#|#|#|#|#|#|#|#|");
dateMask.install(JTEXTFORMATEE);
} catch (ParseException ex) {
Logger.getLogger(Forma051.class.getName()).log(Level.SEVERE, null, ex);
}
}

Can't print to JTextArea from another class

I am attempting to print to my JTextArea from another class. I have the class ActivityLogger call method Alert inside of my main class Risk_Mgnt_Manager which is where the JTextArea is located. I am able to pass the string into this method and print to counsel but it won't append or setText to the JTextArea. What am I missing?
My goal is to have different classes send messages to the class ActivityLogger which in turn sends it to the JTextArea.
Any examples are appreciated and Thank you in advance.
Main class
package risk_mgnt_manager;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
public class Risk_Mgnt_Manager extends JFrame{
boolean begin = false;
String message = null;
JTextArea text = new JTextArea();
JButton Start = new JButton("Start");//exit program button
JButton End = new JButton("End");//Ok button executes message creation
JButton Exit = new JButton("Exit Program");
public void Alert(String a){
System.out.println(a); // This is printing correctly
text.append(a + "\n"); // why won't this display the string?
}
public Risk_Mgnt_Manager(){
text.setEditable(false);
text.setWrapStyleWord(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
setLayout(new GridLayout(2, 3, 5, 5)); //LayoutManager Setup
JPanel myPanel = new JPanel(new GridLayout(3,0));
//JPanel myPanel2 = new JPanel(new GridLayout(1, 1));
//JPanel myPanel3 = new JPanel(new GridLayout(1, 1));
JPanel myPanel4 = new JPanel(new GridLayout(1, 1));
myPanel.add(new JLabel("Start Automated Processes: "));
myPanel.add(Start);
myPanel.add(new JLabel("End Automated Processes: "));
myPanel.add(End);
myPanel.add(new JLabel(" "));
myPanel.add(Exit);
myPanel4.add(text);
Start.addActionListener(new startActions());//Listener for button 1
End.addActionListener(new stopActions());//Listener for button 2
Exit.addActionListener(new Quit());//Listener for button 2
add(myPanel);
//add(myPanel2);
//add(myPanel3);
add(myPanel4);
}
public void StartAutomation(boolean start) throws SAXException, ParserConfigurationException, IOException, SQLException{
//calls test class
Test t = new Test();
t.mainTest(begin);
//ignore these classes
// Step one import settlement data from FIX 1 settlement tables
ImportSettles tbl = new ImportSettles();
//tbl.DataTransfer(begin);
// Step two import Real-Time price data from t_span_price on FIX 1
ImportSpanPrice tbl2 = new ImportSpanPrice();
//tbl2.DataTransfer1(begin);
// Step three import from xml file
ImportTradeData tbl3 = new ImportTradeData();
//tbl3.parseXML(begin);
// Step four not used as of 11/26/2013
ImportFirmRpt tbl4 = new ImportFirmRpt();
// Step five import poew.csv file
ImportPOEW tbl5 = new ImportPOEW();
//tbl5.csvImportPOEW(begin);
// Step six import paycollect.csv file
ImportPaycollect tbl6 = new ImportPaycollect();
//tbl6.csvImportPaycollect(begin);
// Step seven import data from RISK 1
ImportSecDeposit tbl7 = new ImportSecDeposit();
//tbl7.DataTransfer2(begin);
// Step 8 import FCM financial info, WinJammer not used as of 11/26/2013
ImportFCM tbl8 = new ImportFCM();
// Step nine import CGM_post.csv file
ImportCGMPost tbl9 = new ImportCGMPost();
//tbl9.csvImportCGMPost(begin);
// Step ten import RM_Intraday_paycollect.csv
ImportIntraday tbl10 = new ImportIntraday();
//tbl10.csvImportIntra(begin);
}
private static void ProjectFrame(){
Risk_Mgnt_Manager projectFrame = new Risk_Mgnt_Manager();
projectFrame.setSize(500, 300); //JFrame size set
projectFrame.setLocationRelativeTo(null); //JFrame centered to center of screen
projectFrame.setTitle("Automation Control"); //JFrame Title
projectFrame.setVisible(true);//JFrame is visible upon start of program
projectFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
ProjectFrame();
}
static class Quit implements ActionListener {
public void actionPerformed (ActionEvent e) {
//Once Exit JButton is pressed the program exits
System.exit(0);
}
}
public class startActions implements ActionListener {
public void actionPerformed (ActionEvent e) {
//Once Exit JButton is pressed the program exits
begin = true;
try {
StartAutomation(begin);
} catch (SAXException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class stopActions implements ActionListener {
public void actionPerformed (ActionEvent e) {
//Once Exit JButton is pressed the program exits
begin = false;
try {
StartAutomation(begin);
} catch (SAXException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Test class
package risk_mgnt_manager;
import java.util.Date;
/**
*
* #author bgilbert
*/
public class Test {
public void mainTest(boolean a){
ActivityLogger act = new ActivityLogger();
act.logger("Testing message reporting " + new Date(), 1, true);
}
}
ActivityLogger class
package risk_mgnt_manager;
/**
*
* #author MLaMeyer
*/
public class ActivityLogger{
private String message;
// this will perform different purposes once I can print to JTextArea
public void logger(String log, int type, boolean execution){
if (execution == true) {
message = log;
}
if (execution == false) {
message = log;
}
print();
}
// calls method Alert in main class and passes the string correctly
public void print(){
Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
m.Alert(message);
}
}
Your program prints out to the other class, just not in the object displayed:
public void print(){
Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
m.Alert(message);
}
When you create a new Risk_Mgnt_Manager, you do just that, create a new completely unique Risk_Mgnt_Manager object, one that is not displayed. Printing to it will have no effect on the displayed one.
A the solution is to pass in a reference to your logger class to the actual displayed Risk_Mgnt_Manager object.
public class ActivityLogger{
private String message;
private Risk_Mgnt_Manager m; // ***** added
public ActivityLogger(Risk_Mgnt_Manager m) {
this.m = m; // ****** added
}
// this will perform different purposes once I can print to JTextArea
public void logger(String log, int type, boolean execution){
if (execution == true) {
message = log;
}
if (execution == false) {
message = log;
}
print();
}
// calls method Alert in main class and passes the string correctly
public void print(){
// Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
m.Alert(message);
}
});
}
}
Whatever you do, don't attempt to solve this my making anything static as that road will lead to misery.
You need to update the UI in separate Thread, I mean UI related operations should run on the Event dispatch thread. Add constructor in your ActivityLogger class like Hovercraft's solution then try,
SwingUtilities.invokeLater(new Runnable() {
public void run() {
text.append(a+"\n");
}
});
First of all make the frame visible in your constructor.
public Risk_Mgnt_Manager(){
setVisible(true);
}
Then as per solution by Hovercraft pass by reference.

Vertical scrollbar in jTable swing does not appear

I am a bit new to swings, And i was trying to cough up some code involving Jtable.
I find that even though i have added the scrollbar policy the vertical scrollbar does not seem to appear. THe code is pretty shabby.(warning u before hand). But could you please indicate where I need to put in the scrollbar policy. I have tried adding it at a lot of places and it just does not seem to appear.
the other question is how do i make an empty table. As in every time the process button is clicked, i would like to refresh the table. Could u point me in this direction as well.
The directions for usage: just enter a number in the regular nodes textfield like 5 or 10
and click on the process button.
My code :
package ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import utils.ThroughputUtility;
/**
* #author Nathan
*
*/
public class EntryPoint extends JPanel{
public boolean isProcesed =false;
static JFrame frame;
JTabbedPane jTabbedPane = new JTabbedPane();
private static final long serialVersionUID = -6490905886388876629L;
public String messageTobeSent = null;
public int regularNodeCount =0;
public static final String MESSAGE_TO_BE_SENT =" Please Enter the message to be sent. ";
protected static final String ONE = "1";
Map<String,Double> regNodeThroughputMap ;
static JTable tableOfValues;
Object columnNames[] = { "<html><b>Regular Node Name</b></htm>", "<html><b>Throughput Value Obtained</b></html>"};
Object rowData[][] = null;
public EntryPoint() {
jTabbedPane.setTabPlacement(JTabbedPane.NORTH);
Font font = new Font("Verdana", Font.BOLD, 12);
jTabbedPane.setFont(font);
//Server Side Panel.
JPanel serverPanel = getServerPanel();
jTabbedPane.addTab("Server", serverPanel);
//Client side Panel.
JPanel clientPanel = getClientPanel();
jTabbedPane.addTab("Client", clientPanel);
}
private JPanel getClientPanel() {
//Heading Label
JPanel clientPanel = new JPanel();
JLabel RegularNodeLabel = new JLabel("<html><u>Throughput Optimization For Mobile BackBone Networks</u></html>");
RegularNodeLabel.setFont(new Font("Algerian",Font.BOLD,20));
RegularNodeLabel.setForeground(new Color(176,23,31));
clientPanel.add(RegularNodeLabel);
return clientPanel;
}
/**Server Side Code
* #return
*/
private JPanel getServerPanel() {
//Heading Label
JPanel serverPanel = new JPanel(new FlowLayout());
final Box verticalBox1 = Box.createVerticalBox();
Box horozontalBox1 = Box.createHorizontalBox();
Box verticalBox2forsep = Box.createVerticalBox();
Box horozontalBox2 = Box.createHorizontalBox();
JPanel heading = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel backBoneNodeLabel = new JLabel("<html><u>Throughput Optimization For Mobile BackBone Networks</u></html>");
backBoneNodeLabel.setFont(new Font("Algerian",Font.BOLD,20));
backBoneNodeLabel.setForeground(new Color(176,23,31));
backBoneNodeLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//Indication of BackBone Node
JPanel body = new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel backBoneNodeID = new JLabel("Fixed BackBone Node");
backBoneNodeID.setFont(new Font("Algerian",Font.BOLD,16));
backBoneNodeID.setForeground(new Color(176,23,31));
backBoneNodeID.setAlignmentX(Component.CENTER_ALIGNMENT);
//Seperator
JLabel seperator = new JLabel(" ");
seperator.setFont(new Font("Algerian",Font.BOLD,20));
seperator.setForeground(new Color(176,23,31));
verticalBox2forsep.add(seperator);
//Message label
JLabel messageLabel = new JLabel("Please enter the Message to be sent: ");
messageLabel.setFont(new Font("Algerian",Font.BOLD,16));
messageLabel.setForeground(new Color(176,23,31));
messageLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
//Message Text
final JTextField messageText = new JTextField(MESSAGE_TO_BE_SENT,25);
messageText.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent arg0) {
if(messageText.getText().trim().equalsIgnoreCase(MESSAGE_TO_BE_SENT.trim())){
messageText.setText("");
}
}
});
horozontalBox1.add(messageLabel);
horozontalBox1.add(messageText);
//Regular node attached to backbone nodes.
JLabel regularNodelabel = new JLabel("Number of Regular nodes to be attached to the backbone node. ");
regularNodelabel.setFont(new Font("Algerian",Font.BOLD,16));
regularNodelabel.setForeground(new Color(176,23,31));
regularNodelabel.setAlignmentX(Component.LEFT_ALIGNMENT);
//Regular Node text
final JTextField regularNodeText = new JTextField(ONE,5);
regularNodeText.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
if(regularNodeText.getText().trim().equalsIgnoreCase(ONE.trim())){
regularNodeText.setText("");
tableOfValues = new JTable(0,0);
}
}
});
horozontalBox2.add(regularNodelabel);
horozontalBox2.add(regularNodeText);
//Button for Processing.
JButton processbutton = new JButton("Process");
processbutton.setFont(new Font("Algerian",Font.BOLD,16));
processbutton.setForeground(new Color(176,23,31));
processbutton.setAlignmentX(Component.CENTER_ALIGNMENT);
//Processing on clciking process button
processbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
isProcesed=false;
Runnable runThread = new Runnable() {
#Override
public void run() {
while(!isProcesed){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
verticalBox1.add(tableOfValues);
isProcesed =false;
}
};
Thread processThread= new Thread(runThread);
processThread.start();
regularNodeCount = Integer.parseInt(regularNodeText.getText().trim());
regNodeThroughputMap = getThroughPutValues(regularNodeText.getText().trim());
System.out.println("Map obtained = "+regNodeThroughputMap);
tableOfValues = populateTable(regNodeThroughputMap);
isProcesed=true;
JScrollPane scrollPane = new JScrollPane(tableOfValues);
scrollPane.add(tableOfValues);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
verticalBox1.add(scrollPane,BorderLayout.CENTER);
// verticalBox1.add(scrollPane);
}
});
verticalBox1.add(backBoneNodeID);
verticalBox1.add(verticalBox2forsep);
verticalBox1.add(horozontalBox1);
verticalBox1.add(verticalBox2forsep);
verticalBox1.add(horozontalBox2);
verticalBox1.add(verticalBox2forsep);
verticalBox1.add(processbutton);
heading.add(backBoneNodeLabel);
//body.add(backBoneNodeID);
body.add(verticalBox1);
serverPanel.add(heading);
serverPanel.add(body);
return serverPanel;
}
protected JTable populateTable(Map<String,Double> regNodeThroughputMap) {
/*{ { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
{ "Row2-Column1", "Row2-Column2", "Row2-Column3" } }*/
rowData = new Object[regularNodeCount+1][2];
Set<Map.Entry<String, Double>> set = regNodeThroughputMap.entrySet();
for (Map.Entry<String, Double> me : set) {
System.out.println("key ="+me.getKey());
System.out.println("Value ="+me.getValue());
}
String[] keys = new String[regularNodeCount+2];
String[] values = new String[regularNodeCount+2];
List<String> keyList = new LinkedList<String>();
List<String> valueList = new LinkedList<String>();
keyList.add("");
valueList.add("");
for(String key:regNodeThroughputMap.keySet()){
keyList.add(key);
}
for(double value:regNodeThroughputMap.values()){
System.out.println(value);
valueList.add(Double.toString(value));
}
keyList.toArray(keys);
valueList.toArray(values);
System.out.println(Arrays.asList(keys));
System.out.println(Arrays.asList(values));
rowData[0][0] =columnNames[0];
rowData[0][1] =columnNames[1];
for(int i=1;i<=regularNodeCount;i++){
for(int j=0;j<2;j++){
if(j==0)
rowData[i][j]=keys[i];
if(j==1)
rowData[i][j]=values[i];
}
}
return new JTable(rowData, columnNames);
//Printing the array
/* for (int i =0; i < regularNodeCount; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(" " + rowData[i][j]);
}
System.out.println("");
}
*/
}
protected Map<String, Double> getThroughPutValues(String regularNodeInput) {
return ThroughputUtility.generateMapofNodeAndThroughput(regularNodeInput);
}
protected static void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("Throughput Optimization for Mobile BackBone Networks");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EntryPoint splitPaneDemo = new EntryPoint();
frame.getContentPane().add(splitPaneDemo.jTabbedPane);
JScrollPane sp = new JScrollPane(tableOfValues);
sp.setBorder(BorderFactory.createEmptyBorder());
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp.setHorizontalScrollBarPolicy(JScrollPane .HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.setResizable(false);
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setSize(800,600);
}
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Adding ThroughputUtility.java
package utils;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* #author Nathan
*
*/
public class ThroughputUtility {
public static double MIN =5000;
public static double MAX =10000;
public static final double e =Math.E;
public static final double epsilon = 8.854187 *Math.pow(10,-12);
static int regularNodeCount;
static int counter ;
/**Generates the map of Node and ThroughPut values
* #param regularNodeInput
*/
public static Map<String,Double> generateMapofNodeAndThroughput(String regularNodeInput){
regularNodeCount = Integer.parseInt(regularNodeInput);
List<Double> randNodeDistances =getRandDistanceOfNodes(regularNodeCount);
Map<String,Double> nodeAndThroughputmap = getThroughputValuesForNodes(randNodeDistances);
System.out.println(nodeAndThroughputmap);
return nodeAndThroughputmap;
}
/** Obtains the throughput value based on the distances between
* the regular nodes and the backend Nodes.
* #param randNodeDistances
* #return
*/
private static Map<String, Double> getThroughputValuesForNodes(
List<Double> randNodeDistances) {
Map<String,Double> nodeAndThroughputmap = new LinkedHashMap<String, Double>();
for(double i : randNodeDistances){
double throughputValue = calculateThroughPut(i);
nodeAndThroughputmap.put("RegularNode :"+counter, throughputValue);
counter++;
}
return nodeAndThroughputmap;
}
private static double calculateThroughPut(double distanceij) {
double throughput = 1 /(e*regularNodeCount*distanceij*epsilon);
return throughput;
}
/**Generates the distance dij .
* #param regularNodeCount
* #return
*/
private static List<Double> getRandDistanceOfNodes(int regularNodeCount) {
List<Double> distnodeNumbers = new LinkedList<Double>();
for(int i=0;i<regularNodeCount;i++){
double randnodeNumber = MIN + (double)(Math.random() * ((MAX - MIN) + 1));
distnodeNumbers.add(randnodeNumber);
}
return distnodeNumbers;
}
public static void main(String[] args) {
ThroughputUtility.generateMapofNodeAndThroughput("5");
/*System.out.println(e);
System.out.println(epsilon);*/
}
}
The main problem why you can't see the scroll bar is that you add the table to multiple containers.
when clicking the button, you recreate a lot of swing objects (why?), then you start a thread to add the table to the box (why?? be careful with swing and multithreading if you don't know what you are doing). after that (or before, depending on how long the thread is running) you add the table to the scrollpane.
the scrollpane does not contain your table, because you can only use it once.
A quick fix would be something like this:
create all you GUI stuff once, leave it out of any action listeners and stuff. if you start the application, it should just show an empty table. don't add the same object into multiple containers! you can control the size of your table and scrollpane by using
table.setPreferredSize(new Dimension(width, height));
if you click the button (that is in your action listener), get all the new data and add it it to the table. e.g. by using something like this.
tableOfValues.getModel().setValueAt(value, row, column);
or create a new table model if you have to:
tableOfValues.setModel(new DefaultTableModel(rowData, columnNames));
That's all I can tell you for now by looking at the code...
edit:
in the method populateTable(...) don't create a new table! use the above code to set a new model instead if you have to, or use an existing one and modify its values.
You never at the scroll pane to the JFrame as far as I could tell on
a quick look
You change the data in the TableModel (or replace the TableModel of
the JTable)
See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
I had the same problem, just set JTable preferredsize to null and the scrollbar will show up.
Hope it helps

Categories