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.
Related
I have created a Java application that goes through hundreds of documents after user clicks "Run" button. Is there a way to terminate the program and leave the GUI running? All I want to be able to stop is the process of reading the documents.
System.exit(0) is not the solution I am looking for as my whole app closes.
It's difficult to say something without to see your application. But probably this piece of code will help you to understand how to implement what you want:
import java.awt.BorderLayout;
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.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
public class SwingWorkerTest implements Runnable {
private JButton cancelButton = new JButton("Cancel");
private JButton runButton = new JButton("Run");
private JLabel label = new JLabel("Press 'Run' to start");
private LongWorker longWorker;
#Override
public void run() {
JFrame frm = new JFrame("Long task test");
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
longWorker.terminate();
}
});
runButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
longWorker = new LongWorker();
runButton.setEnabled(false);
cancelButton.setEnabled(true);
label.setText("Task in progress. Press 'Cancel' to terminate.");
longWorker.execute();
}
});
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
bottomPanel.add(runButton);
bottomPanel.add(cancelButton);
frm.add(label);
frm.add(bottomPanel, BorderLayout.SOUTH);
frm.setSize(400, 200);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new SwingWorkerTest());
}
private class LongWorker extends SwingWorker<Void, Void> {
private volatile boolean terminated;
#Override
protected Void doInBackground() throws Exception {
// check special variable tov determine whether this task still active
for (int i = 0; i < 1000 && !terminated; i++) {
readFile();
}
return null;
}
#Override
protected void done() {
if (terminated) {
label.setText("Process terminated. Press 'Run' to restart.");
} else {
label.setText("Process done. Press 'Run' to restart.");
}
cancelButton.setEnabled(false);
runButton.setEnabled(true);
}
// dummy method - make 10 milliseconds sleep
private void readFile() {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
// Nothing here
}
}
public void terminate() {
terminated = true;
}
}
}
I am trying to make a function that allows you to navigate to a webpage. I can how to run the function, I just don't know how to write the part of the program that accesses the webpage. Here is the code that I am using to access the function via a JButton. I would like the program to work on multiple platforms. All of the solutions I have found to this, I either don't understand well enough to modify to my needs, or it isn't multi-platform.
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton google = new JButton("Google");
linux.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openURL("http://www.google.com/");
}
} );
JButton stackoverflow = new JButton("Stackoverflow");
JButton blah = new JButton("blah");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.add(linux);
panel.add(osx);
panel.add(windows);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
Yes I am aware the last two buttons do nothing.
Here is what I have tried so far:
public static void openURL(String url) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
else {
String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape", "chrome" };
String browser = null;
for (int count = 0; count < browsers.length && browser == null; count++)
if (Runtime.getRuntime().exec(new String[] {"which", browsers[count]}).waitFor() == 0)
browser = browsers[count];
Runtime.getRuntime().exec(new String[] {browser, url});
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error in opening browser" + ":\n" + e.getLocalizedMessage());
}
}
Unfortunately, I don't understand what this does, or how to change it to my needs.
If possible could you explain your solution so that I can understand how it works? Thanks.
You can use Desktop class which allows Java applications to interact with default applications associated with specific file types on the host platform. Here you have a tutorial on How to integrate with the Desktop class.
Remember:
Use the isDesktopSupported() method to determine whether the Desktop
API is available
I made a quick example.
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class DesktopTest {
private JPanel panel;
public DesktopTest() {
panel = new JPanel();
ActionListener listener = new OpenUrLAction();
JButton googleButton = new JButton("google");
googleButton.setActionCommand("http://www.google.com");
googleButton.addActionListener(listener);
JButton stackOverButton = new JButton("stackOverflow");
stackOverButton.setActionCommand("http://www.stackoverflow.com");
stackOverButton.addActionListener(listener);
panel.add(googleButton);
panel.add(stackOverButton);
}
public JPanel getPanel() {
return panel;
}
private class OpenUrLAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
try {
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(e.getActionCommand()));
} catch (IOException | URISyntaxException e1) {
JOptionPane.showMessageDialog(null,
"An error happen " + e1.getMessage());
}
}
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("DesktopExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(Boolean.TRUE);
frame.add(new DesktopTest().getPanel());
// Display the window.
frame.pack();
frame.setVisible(Boolean.TRUE);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If you don't find this useful , you can find some workaround in this answer
A friend recently asked me to make a simple Buzzer program and has found a strange "bug" in what I wrote for him.
If a key is pushed and the buzzer is reset rapidly over the course of a few seconds he observes a 2 to 3 second freeze of the program that occurs between the the first key press after the reset and the "buzz" indication. He has the following Java installation:
build 1.7.0_25-b16
However, I do not experience this problem on my computer, with the following Java installation:
$ java -version
java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-457-10M4509)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-457, mixed mode)
Upon unfreeze, the program returns the appropriate key (that is, not the last key pressed, but the first one pushed after the reset and before the freeze). This suggests that the problem is not with the listener but with the reaction to the listener.
Any thoughts on what might be causing this phenomenon? Thanks in advance for your help.
Source code:
/**
* Buzzer.java
*
* Buzzer
*/
package org.lexingtonma.lhs.nhb;
import java.awt.Color;
import java.awt.DefaultKeyboardFocusManager;
import java.awt.Font;
import java.awt.KeyEventDispatcher;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* #author Arman D. Bilge
*
*/
public class Buzzer extends JFrame implements KeyListener {
private static final long serialVersionUID = 7492374642744742658L;
private static final String BUZZ_A = "BuzzA.wav";
private static final String BUZZ_B = "BuzzB.wav";
private Clip buzz = null;
private boolean listening = true;
private final JTextField display = new JTextField(3);
private final JButton reset = new JButton("Reset");
{
DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
keyTyped(e);
return false;
}
});
setTitle("Buzzer");
final JPanel panel = new JPanel();
setSize(256, 162);
setDefaultCloseOperation(EXIT_ON_CLOSE);
display.setFont(new Font("Helvetica", Font.BOLD, 64));
display.setForeground(Color.WHITE);
display.setVisible(true);
display.setEditable(false);
display.setHorizontalAlignment(JTextField.CENTER);
panel.add(display);
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
display.setText("");
display.setBackground(Color.WHITE);
listening = true;
reset.setEnabled(false);
}
});
reset.setEnabled(false);
panel.add(reset);
add(panel);
try {
buzz = AudioSystem.getClip();
} catch (LineUnavailableException e) {
JOptionPane.showMessageDialog(this, e.getLocalizedMessage(), "FATAL ERROR", JOptionPane.ERROR_MESSAGE);
}
}
public static final void main(String args[]) {
Buzzer b = new Buzzer();
b.setVisible(true);
}
public void keyPressed(KeyEvent e) {
// Do nothing
}
public void keyReleased(KeyEvent e) {
// Do nothing
}
public void keyTyped(KeyEvent e) {
final char c = e.getKeyChar();
if (listening && Character.isLetterOrDigit(c)) {
buzz.close();
listening = false;
if (Character.isDigit(c)) {
display.setBackground(Color.RED);
try {
buzz.open(AudioSystem.getAudioInputStream(getClass().getResource(BUZZ_A)));
buzz.start();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getLocalizedMessage(), "FATAL ERROR", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
} else {
display.setBackground(Color.BLUE);
try {
buzz.open(AudioSystem.getAudioInputStream(getClass().getResource(BUZZ_B)));
buzz.start();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getLocalizedMessage(), "FATAL ERROR", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
display.setText("" + c);
reset.setEnabled(true);
}
}
}
Jar: https://www.dropbox.com/s/62fl2i97m9hrx9m/Buzzer.jar
It's safer to create a new Clip object every time and discard the old one. Try this method
public static void play(String name) {
try{
AudioInputStream sounds = AudioSystem.getAudioInputStream(Buzzer.class.getResource(name));
final Clip clip = AudioSystem.getClip();
clip.addLineListener(new LineListener() {
public void update(LineEvent e) {
LineEvent.Type type = e.getType();
if(type == type.STOP) clip.close();
}
});
clip.open(sounds);
clip.start();
} catch(Exception e){
e.printStackTrace();
}
}
As was suggested, you could give keybinding a try to see if it helps. This just shows how to do it with the Enter key.
public class Buzzer extends JFrame {
private static final String enter = "ENTER";
public Buzzer() {
// Key bound AbstractAction item
enterAction = new EnterAction();
// Gets the JFrame InputMap and pairs the key to the action
this.getInputMap().put(KeyStroke.getKeyStroke(enter), "doEnterAction");
// This line pairs the AbstractAction enterAction to the action "doEnterAction"
this.getActionMap().put("doEnterAction", enterAction);
}
private class EnterAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Enter was pressed.");
}
}
}
Actually I can't remember if this will work when applied to a JFrame, you might need to make a JPanel first to apply these to. Just replace 'this' with the panel name.
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");
}
}
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