A Swing GUI problem.

There are a JTextfield for entering an integer, a JButton that can be used to square the integer, and another Textfield to show the result. Two questions:
1) After typing the integer, I want to enter Enter-key to get the result, instead of pressing the JButton. How to code it in this case?
2) I want using mouse keys to select, copy and paste the contents in JTextfield. What should I do in my code?

Assuming your Textfield is called JTextField input = new JTextField(10);
JTextField output = new JTextField(10);
private class InputListener implements ActionListener
public void actionPerformed(ActionEvent evt)
String text = input.getText();
int x = Integer.parseInt(text) * Integer.parseInt(text);
output.setText(" " +x);
this should work I would imagine. when you press enter it will take whatever is in the input field, square it and put it in the output field.

Similar Messages

  • In this case, can I modify swing GUI out of swing thread?

    I know the Swing single thread rule and design (Swing is not thread safe).
    For time-consuming task, we are using other thread to do the task and
    we use SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater (or SwingWorker) to update Swing GUI.
    My problem is, my time-consuming task is related to Swing GUI stuff
    (like set expanded state of a huge tree, walk through entire tree... etc), not the classic DB task.
    So my time-consuming Swing task must executed on Swing thread, but it will block the GUI responsivity.
    I solve this problem by show up a modal waiting dialog to ask user to wait and
    also allow user to cancel the task.
    Then I create an other thread (no event-dispatch thread) to do my Swing time-consuming tasks.
    Since the modal dialog (do nothing just allow user to cancel) is a thread spawn by
    Swing event-dispatch thread and block the Swing dispatch-thread until dialog close.
    So my thread can modify Swing GUI stuff safely since there are no any concurrent access problem.
    In this case, I broke the Swing's suggestion, modify Swing stuff out of Swing event-dispatch thread.
    But as I said, there are no concurrent access, so I am safe.
    Am I right? Are you agree? Do you have other better idea?
    Thanks for your help.

    If you drag your modal dialog around in front of the background UI, then there is concurrent access: paint requests in your main window as the foreground window moves around.

  • Spreadsheets and SWING GUI's

    I have to embed a spreadsheet facility in a SWING GUI, what is the best and easiest way to do this ??

    I am not quite sure what your problem is.
    The way I see it, your question is one of the following:
    1. How do I (generally) make a user interface on top of my dos-based program?
    2. How do I make user interfaces in swing?
    If your question is the first, I'm afraid I can't tell you either. Would seem pretty obvious to me, make a simple dialog based app, using menu's or actions to trigger tha actions that were formerly triggered by numbers, etc...
    In the other case, I recommend the java swing tutorial at http://java.sun.com/docs/books/tutorial/uiswing/
    Greetings,
    Gert

  • JLabel + GUI problem

    Hello
    I have a JLabel2 which shows the spanish map. The thing is I do wanna draw lines on my spanish map and save it to as an image file in my desktop . I'm able to draw lines and save my JLabel2(spanish map) as an image in my Desktop. The problem is I'm not able to see any lines that I draw before in my image file. I can see those lines when I do click draw button but I can not see them when I save my file as an image to my desktop.Please help me.This problem killed me for two days..you can see how i converted to icon and how i save it as an image file below.Thank you for your helps from now.
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    File file3;
    int returnVal = fc.showSaveDialog(routemap.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    try {
    File f3 = fc.getSelectedFile();
    ImageIcon icon = (ImageIcon) jLabel2.getIcon();
    System.out.println(icon.getIconHeight());
    BufferedImage buf = new BufferedImage(icon.getImage().getWidth(
    null), icon.getImage().getHeight(null),
    BufferedImage.TYPE_INT_RGB);
    buf.getGraphics().drawImage(icon.getImage(), 0, 0,
    icon.getIconWidth(), icon.getIconHeight(), null);
    ImageIO.write(buf, "jpg", new File(f3.getAbsolutePath()
    + ".jpg"));
    System.out.println(f3.getAbsolutePath());
    } catch (IOException e) {
    I have drawn lines by using draw function as you see below and I can not see those lines without any problem..Lines disapper in the image file when I do save it..Here is the draw button..
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
    boolean go = true;
    if (OneClicked == false && go == true) {
    jLabel3.setText(jComboBox1.getSelectedItem() + " to ");
    view = jComboBox1.getSelectedItem().toString() + " to ";
    String m = jComboBox1.getSelectedItem().toString();
    int size1 = City.size();
    for (int i = 0; i < size1; i++) {
    if (City.get(i).equals(m)) {
    Index.add(i);
    OneClicked = true;
    go = false;
    if (OneClicked == true && go == true) {
    jLabel3.setText(view + jComboBox1.getSelectedItem());
    view = "";
    String m = jComboBox1.getSelectedItem().toString();
    int size1 = City.size();
    for (int i = 0; i < size1; i++) {
    if (City.get(i).equals(m)) {
    Index.add(i);
    Graphics g = jLabel2.getGraphics();
    g.setColor(Color.BLUE.darker());
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(new BasicStroke(3));
    System.out.println(Index.size());
    System.out.println(Index.size() - 2);
    int m1 = Integer.parseInt(XCoordinate.get(Index
    .get(Index.size() - 2)));
    int n1 = Integer.parseInt(YCoordinate.get(Index
    .get(Index.size() - 2)));
    int m2 = Integer.parseInt(XCoordinate.get(Index
    .get(Index.size() - 1)));
    int n2 = Integer.parseInt(YCoordinate.get(Index
    .get(Index.size() - 1)));
    System.out.println(m1 + " " + n1 + " " + m2 + " " + n2);
    g2.drawLine(m1, n1, m2, n2);
    OneClicked = false;
    System.out.println("index im" + Index);
    }

    Cross-post: [java-forums: jlabel-gui-problem|http://www.java-forums.org/java-applets/15472-jlabel-gui-problem.html]
    To the original poster, cross-posting can frustrate anyone who tries to help you only to find out later that the same answer was given hours ago in a cross-posted thread. No one likes wasting their time, especially a volunteer. The polite thing to do would be to not do this, but if you feel that you absolutely must, to at least provide links in both cross-posts to each other.
    edit: all over the dang place: [javaranch: JLabel-GUI|http://www.coderanch.com/t/428887/Swing-AWT-SWT-JFace/java/JLabel-GUI]
    Now this could get folks wanting to not help you ever. Please take care here.
    Edited by: Encephalopathic on Jan 31, 2009 6:34 AM

  • Need help with threading in Swing GUI !!!

    I've written an app that parses and writes
    files. I'm using a Swing GUI. The app
    could potenially be used to parse hundreds or even
    thousands of files. I've included a JProgressBar
    to monitor progress. The problem is when I parse
    a large number of files the GUI freezes and only
    updates the values of the progress bar when the
    parsing and writing process is finished.
    I assume I need to start the process in a seperate thread. But, I'm new to threads and I'm not sure
    whether to start the Progressbar code in a seperate
    thread or the parsing code. As a matter of fact I really
    don't have any idea how to go about this.
    I read that Swing requires repaints be done in the
    event dispatch thread. If I start the parsing in a seperate
    thread how do I update the progressbar from the other
    thread? I'm a thread neophyte.
    I need a cigarette.

    In other words do this:
    Inside event Thread:
    handle button action
    start thread
    return from action listener
    Inside worker Thread:
    lock interface
    loop
    perform action
    update progress bar
    unlock interface
    return from worker ThreadDoesn't updating the progress bar (and locking/unlocking the interface components) from within the worker thread violate the rule that you shouldn't mess with Swing components outside the event thread? (Do I have that rule right?)
    In any case, is there any way to just post some kind of event to the progress bar to update it from within the worker thread, thereby insuring that the GUI progress bar update is being invoked from the event thread? This would also obviate the need to use a timer to poll for an update, which I think is a waste especially when the monitored progress is at a variable rate, (or for number crunching, is executing on different speed machines).
    Also, doesn't using invokeLater() or invokeAndWait() still block the event dispatching thread? I don't understand how having a chunk of code started in the event thread doesn't block the event thread unless the code's executed in a "sub-thread", which would then make it not in the event thread.
    I'm also looking to have a progress bar updated to monitor a worker thread, but also want to include a "Stop" button, etc. and need the event queue not to be blocked.
    The last thing I can think of is to implement some kind of original event-listener class that listens to events that I define, then register it with the system event queue somehow, then have the worker thread post events to this listener which then calls setValue() in the progress bar to insure that the bar is updated from the event queue and when I want it to be updated. I don't know yet if it's possible to create and register these kinds of classes (I'm guessing it is).
    Thanks,
    Derek

  • Java Swing GUI Button Image

    Hi, I really need help with this one, I have tried many things and looked at many pages for this but to no avail as of yet.
    I have a Swing GUI in which I want to display an image. The way I am displaying it at the moment is as a button icon as I do not need to be able to alter the images. I can also use the button functionality as displaying something when the image is clicked. So I have an array of image paths which are accesed to load an image into the button and a "Next" button to change the image as required.
    My problem is that when I load an image into the button it moves from it's original location. When there is no image displayed the button is where I want it to be, but when I load an image it moves, this cannot happen. Any ideas.
    Also, when I am trying to click thru the array of images, it starts at the 1st image in the array but then skips to the last image in the array. Here is the code for that.
    // Handle events that arise from the "Next" button being clicked
    private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {
    if (jComboBox1.getSelectedIndex() == 1)
         for (int i = 1; i < juniorImageIndex.length; i++)
         jButton8.setIcon(new javax.swing.ImageIcon(juniorImageIndex));
    else if (jComboBox1.getSelectedIndex() == 2)
         for (int i = 1; i < seniorImageIndex.length; i++)
         jButton8.setIcon(new javax.swing.ImageIcon(seniorImageIndex[i]));
    juniorImageIndex and seniorImageIndex are obviuosly the arrrays with the file paths for the images. The reason I start at index 1 is that I use the 0 index image as the starting image for each part.
    Any help gratefully appreciated, I really hope someone can help, Thanks.

    // Handle events that arise from the "Next" button
    being clicked
    private void
    jButton5MouseClicked(java.awt.event.MouseEvent evt) {
      myImageIndex =(myImageIndex + 1) % imageArray.size();
      resetButtonImage();
    private void resetButtonImage() {
    if (jComboBox1.getSelectedIndex() == 1)
    {//take this out
    //> for (int i = 1; i < juniorImageIndex.length; i++)
    //> {
    jButton8.setIcon(new//> javax.swing.ImageIcon(array[myImageIndex]));
    //> }
    else if (jComboBox1.getSelectedIndex() == 2)
    {//this too
    //> for (int i = 1; i < seniorImageIndex.length; i++)
    //> {
    jButton8.setIcon(new
    javax.swing.ImageIcon(array2[myImageIndex]));//> }

  • Launching Swing GUI from Oracle Forms Web Based

    Hi there,
    I have oracle forms which call a shell script which initiates the java swing gui. I am using host command to run this script. When I am doing it on unix server everything works fine. Now we want same application on web now i am getting problem. The host command is not working in this case. It can not launch the java gui. Can anybody tell me what will be the nice approach to do it.
    Thanks
    Ranjan

    Hi,
    you'll have to create a Java Bean in Forms that calls the runtime. You can also use webutil, available on otn to call a client side host command.
    Frank

  • Freezing Swing GUI...

    Hi!
    I am having problems with my swing GUI. It's freezing when I'm trying to disable a JButton in it. Could anybody tell me y it happens and what can be done to remedy it?
    My piece of code:
    stopButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // stop!
    simulator.blinker = null;
    label.setText("Stopped!");
    playPauseButton.setEnabled(false);
    stepButton.setEnabled(false);
    showNamesButton.setEnabled(false);
    speedUpButton.setEnabled(false);
    speedDownButton.setEnabled(false);
    stopButton.setEnabled(false);
    When I press the stopButton, my GUI freezes. Same happens with this piece of code when simSpeed = 50:
    speedUpButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (simulator.simSpeed > 300 && simulator.simSpeed <= 500){
    simulator.simSpeed -= 100;
    System.out.println("sim speed = " + simulator.simSpeed);
    else if (simulator.simSpeed > 50 && simulator.simSpeed <= 300){
    simulator.simSpeed -= 50;
    System.out.println("sim speed = " + simulator.simSpeed);
    else {//if (simulator.simSpeed == 50){
    System.out.println("caution: sim speed = " + simulator.simSpeed);
    speedUpButton.setEnabled(false);
    Strangely, this one does not make the GUI freeze when simSpeed = 1500:
    speedDownButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if (simulator.simSpeed < 1500){
    simulator.simSpeed += 100;
    System.out.println("sim speed = " + simulator.simSpeed);
    else if (simulator.simSpeed == 1500)
    speedDownButton.setEnabled(false);
    I'd greatly apreciate any help!
    Thx in advance!
    Owrwe

    I have gone thru some experimentations and come to this conclusion:
    when i try to disable buttons at the extremity of a row of buttons, the GUI freezes!
    for example:
    buttonPanel.add(speedUpButton);
    buttonPanel.add(speedDownButton);
    buttonPanel.add(playPauseButton);
    buttonPanel.add(stepButton);
    buttonPanel.add(showNamesButton);
    buttonPanel.add(stopButton);
    this is the order of buttons in a layout (flow layout by default, isn't it?). The GUI freezes when I try to disable: speedUpButton and stopButton (from inside their ActionListener method).
    Changing the layout to:
    buttonPanel.add(speedDownButton);
    buttonPanel.add(speedUpButton);
    buttonPanel.add(playPauseButton);
    buttonPanel.add(stepButton);
    buttonPanel.add(showNamesButton);
    buttonPanel.add(stopButton);
    The GUI freezes when I try to disable: speedDownButton (as compared to speedUpButton from above) and stopButton (from inside their ActionListener method).
    Changing the layout to:
    buttonPanel.add(playPauseButton);
    buttonPanel.add(speedDownButton);
    buttonPanel.add(speedUpButton);
    buttonPanel.add(stepButton);
    buttonPanel.add(stopButton);
    buttonPanel.add(showNamesButton);
    The GUI freezes when I try to disable: all of them (from inside the stopButton ActionListener). The speedUpButton and speedDownButton are properly disabled when the limits are reached without freezing the GUI. If I disable all buttons (thru the stopButton when it's not at the extremity of the row) except one of them, the GUI doesn't freeze!
    any suggestions?

  • Multi-Client TCP Server /w Swing GUI

    Hi everybody,
    i have to develop a Multi-Client TCP Server with a Swing GUI. The GUI mainly consists of a JTable which shows various trace messages from processes running on other computers. As the data needs to be filtered i�m using a custom TableModel derived from AbstractTableModel. I�m creating a new thread for every client that connects as shown in http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/socket.html
    Now every client thread reads data from its TCP connection and puts it into the JTable by calling the method addRow of the model. But i�m getting strange NullPointerExceptions and IndexOutOfBoundExceptions when data arrives (i�m using ArrayList in the model). These exceptions never show in a single-threaded Swing app (i�ve tested this already, so i don�t think it�s a bug in my model), so i think this is a problem with Swing�s thread unsafety? Do you have any hints on how to get away with it? Also general design tips for a Multi-Client TCP Server /w Swing GUI are greatly appreciated.
    Thanks in advance!
    Best regards,
    Disposable_Hero

    Of course, but i don�t think it is the model (as said before it works fine in a single thread swing app)
    Here�s the code:
    public class LogTableModel extends AbstractTableModel{
    private Vector dataVector;
    private Vector filterVector;
    private String[] columnIdentifiers;
    private Vector filteredbyProcess;
    private Vector filteredbyLoglevel;
    private boolean bEnableRefresh;
    /** Creates a new instance of LogTableModel */
    public LogTableModel() {
    dataVector=new Vector(0);
    columnIdentifiers=new String[]{"LogTime","HostName","IP","ProcessName","LogLevel","Handle","PID","TID","LogData"};
    filteredbyProcess=new Vector(0);
    filteredbyLoglevel=new Vector(0);
    filterVector=new Vector(0);
    bEnableRefresh=true;
    public synchronized void enableRefresh(boolean bEnableRefresh){
    this.bEnableRefresh=bEnableRefresh;
    if(bEnableRefresh){
    this.buildIndexListBasedOnFilter();
    public synchronized void addRow(LogLine row){
    dataVector.add(row);
    if(bEnableRefresh)
    this.buildIndexListBasedOnFilter();
    public synchronized void addFilter(Filter filter){
    filterVector.add(filter);
    if(filter.isActive())
    this.buildIndexListBasedOnFilter();
    public synchronized void setFilterActive(String name,boolean active){
    int i;
    for(i=0;i<filterVector.size();i++)
    if(((Filter)filterVector.elementAt(i)).getName().equals(name))
    break;
    Filter tmp=(Filter)filterVector.elementAt(i);
    tmp.setActive(active);
    if(active)
    this.buildIndexListBasedOnFilter();
    public synchronized void setFilterLoglevel(String name,int Loglevel){
    int i;
    for(i=0;i<filterVector.size();i++)
    if(((Filter)filterVector.elementAt(i)).getName().equals(name))
    break;
    Filter tmp=(Filter)filterVector.elementAt(i);
    tmp.setLoglevel(Loglevel);
    if(tmp.isActive()==false)
    this.buildIndexListBasedOnFilter();
    private void buildIndexListBasedOnFilter(){
    filteredbyProcess.clear();
    filteredbyLoglevel.clear();
    applyProcessFilter();
    applyLoglevelFilter();
    if(bEnableRefresh)
    this.fireTableDataChanged();
    private void applyProcessFilter(){
    LogLine line=null;
    Filter filter=null;
    for(int i=0;i<dataVector.size();i++){
    for(int j=0;j<filterVector.size();j++){
    filter=(Filter)filterVector.elementAt(j);
    line=(LogLine)dataVector.elementAt(i);
    if(filter.isActive()&&(filter.getName().equals(line.getProcessName()))){
    line.setHidden(true);
    break;
    else{
    line.setHidden(false);
    if(line.getHidden()!=true)
    filteredbyProcess.add(new Integer(i));
    private void applyLoglevelFilter(){
    for(int i=0;i<filteredbyProcess.size();i++){
    int index=((Integer)filteredbyProcess.get(i)).intValue();
    LogLine line=(LogLine)dataVector.elementAt(index);
    for(int j=0;j<filterVector.size();j++){
    if(((Filter)filterVector.elementAt(j)).getName().equals(line.getProcessName())){
    Filter filter=(Filter)filterVector.elementAt(j);
    if((filter.getLoglevel()&line.getLogLevelAsInt())!=line.getLogLevelAsInt())
    line.setHidden(true);
    else
    filteredbyLoglevel.add(new Integer(index));
    break;
    public synchronized String getColumnName(int columnIndex){
    return columnIdentifiers[columnIndex];
    public synchronized void clearData(){
    dataVector.clear();
    filteredbyProcess.clear();
    filteredbyLoglevel.clear();
    public synchronized int getColumnCount() {
    return columnIdentifiers.length;
    public synchronized int getRowCount() {
    return filteredbyLoglevel.size();
    public synchronized Object getValueAt(int rowIndex, int columnIndex) {
    int iIndex=((Integer)filteredbyLoglevel.get(rowIndex)).intValue();// hier krachts warum???
    LogLine tmp=(LogLine)dataVector.elementAt(iIndex);
    switch(columnIndex){
    case 0:
    return tmp.getLogTime();
    case 1:
    return tmp.getHostName();
    case 2:
    return tmp.getIP();
    case 3:
    return tmp.getProcessName();
    case 4:
    return tmp.getLogLevel();
    case 5:
    return tmp.getHandle();
    case 6:
    return tmp.getProcessID();
    case 7:
    return tmp.getThreadID();
    case 8:
    return tmp.getLogData();
    default:
    return null;

  • Designing a smart Swing GUI with design patterns

    Hi !
    I have to build a quite big Swing GUI from
    scratch. I would like to use smart design patterns to :
    * ensure reusability of some components
    * offer a framework-like set of solid classes
    to deal with generic problems
    * try to respect MVC pattern as close as possible
    from the real MVC spirit (not the half MVC
    pattern Swing is build upon)
    Could somebody give me any link towards ressources/docs/articles dealing with how
    to build such a smart Swing GUI ?
    Thanx a lot !

    Hi !
    I have to build a quite big Swing GUI from
    scratch. I would like to use smart design patterns to :
    * ensure reusability of some components
    * offer a framework-like set of solid classes
    to deal with generic problems
    * try to respect MVC pattern as close as possible
    from the real MVC spirit (not the half MVC
    pattern Swing is build upon)
    Could somebody give me any link towards ressources/docs/articles dealing with how
    to build such a smart Swing GUI ?
    Thanx a lot !

  • Swing/GUI Strategy

    My Swing GUI has a JMenuBar with several items. The main panel has a "controls" pane and an "results" pane. The results must be displayed when selecting options/actions on the "controls" pane.
    However, I want the contents of the "controls" pane to depend on the menu item selected.
    What should be my strategy to achieve this?
    My best guess would be to create all of the "controls" panes and only show one of them when using the menu. But I need a litlle bit more help on this.
    Thanks,
    joozju

    CardLayout seems helpful. Although I seem to have some problem with the cl.show() method. The other cards are not drawn when I select a menuitem:
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.KeyStroke;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test implements ActionListener {
    JPanel controlCardsPanel;
    JPanel ccDef, ccOne, ccTwo;
    public static void main(String[] args) {
    try{
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } 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();
    private static void createAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Test - Under Construction");
    Test t = new Test();
    frame.setJMenuBar(t.createMenuBar());
    frame.setContentPane(t.createContentPane());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    public JPanel createContentPane() {
    JPanel jp = new JPanel(new BorderLayout(5,5)); //BorderLayout must be defined here
    jp.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
    jp.setPreferredSize(new Dimension(640, 480));
    jp.setBackground(Color.LIGHT_GRAY);
    ccDef = new JPanel();
    ccDef.add(new JLabel("Use the Menu"));
    ccOne = new JPanel();
    ccOne.add(new JLabel("Press One"));
    ccOne.add(new JButton("One"));
    ccTwo = new JPanel();
    ccTwo.add(new JLabel("Select Two"));
    ccTwo.add(new JCheckBox("High"));
    ccTwo.add(new JCheckBox("Low"));
    CardLayout cl = new CardLayout();
    controlCardsPanel = new JPanel();
    controlCardsPanel.setLayout(cl);
    controlCardsPanel.add(ccDef, "I am ccDefault");
    controlCardsPanel.add(ccOne, "I am ccOne");
    controlCardsPanel.add(ccTwo, "I am ccTwo");
    jp.add(controlCardsPanel, BorderLayout.LINE_START);
    jp.setOpaque(true);
    return jp;
    public JMenuBar createMenuBar() {
    //Create menu bar
    JMenuBar jmb = new JMenuBar();
    //Build File menu
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    //Add Control One MenuItem
    JMenuItem fileMenuControlOne = new JMenuItem("Card One");
    fileMenuControlOne.setActionCommand("ccOne");
    fileMenuControlOne.addActionListener(this);
    fileMenu.add(fileMenuControlOne);
    //Add Control Two MenuItem
    JMenuItem fileMenuControlTwo = new JMenuItem("Card Two");
    fileMenuControlTwo.setActionCommand("ccTwo");
    fileMenuControlTwo.addActionListener(this);
    fileMenu.add(fileMenuControlTwo);
    //Add Quit MenuItem
    JMenuItem fileMenuQuit = new JMenuItem("Quit");
    fileMenuQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
    fileMenuQuit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    System.exit(0);
    fileMenu.add(fileMenuQuit);
    jmb.add(fileMenu);
    return jmb;
    public void actionPerformed(ActionEvent ae) {
    CardLayout cl = (CardLayout)(controlCardsPanel.getLayout());
    cl.show(controlCardsPanel, (String)ae.getActionCommand());
    }I expect the othe cards to appear when I select "Card One" from the File menu. But they don't. I use the Ctrl-F11 key in eclipse when I test my app.
    Thanks,
    Joost

  • Loading large files in Java Swing GUI

    Hello Everyone!
    I am trying to load large files(more then 70 MB of xml text) in a Java Swing GUI. I tried several approaches,
    1)Byte based loading whith a loop similar to
    pane.setText("");
                 InputStream file_reader = new BufferedInputStream(new FileInputStream
                           (file));
                 int BUFFER_SIZE = 4096;
                 byte[] buffer = new byte[BUFFER_SIZE];
                 int bytesRead;
                 String line;
                 while ((bytesRead = file_reader.read(buffer, 0, BUFFER_SIZE)) != -1)
                      line = new String(buffer, 0, bytesRead);
                      pane.append(line);
                 }But this is gives me unacceptable response times for large files and runs out of Java Heap memory.
    2) I read in several places that I could load only small chunks of the file at a time and when the user scrolls upwards or downwards the next/previous chunk is loaded , to achieve this I am guessing extensive manipulation for the ScrollBar in the JScrollPane will be needed or adding an external JScrollBar perhaps? Can anyone provide sample code for that approach? (Putting in mind that I am writting code for an editor so I will be needing to interact via clicks and mouse wheel roatation and keyboard buttons and so on...)
    If anyone can help me, post sample code or point me to useful links that deal with this issue or with writting code for editors in general I would be very grateful.
    Thank you in advance.

    Hi,
    I'm replying to your question from another thread.
    To handle large files I used the new IO libary. I'm trying to remember off the top of my head but the classes involved were the RandomAccessFile, FileChannel and MappedByteBuffer. The MappedByteBuffer was the best way for me to read and write to the file.
    When opening the file I had to scan through the contents of the file using a swing worker thread and progress monitor. Whilst doing this I indexed the file into managable chunks. I also created a cache to further optimise file access.
    In all it worked really well and I was suprised by the performance of the new IO libraries. I remember loading 1GB files and whilst having to wait a few seconds to perform the indexing you wouldn't know that the data for the JList was being retrieved from a file whilst the application was running.
    Good Luck,
    Martin.

  • Running a Java application from a Swing GUI

    Hi,
    I was wondering if there is a simple way to run a Java application from a GUI built with Swing. I would presume there would be, because the Swing GUI is a Java application itself, technically.
    So, I want a user to click a button on my GUI, and then have another Java application, which is in the same package with the same classpaths and stuff, run.
    Is there a simple way to do this? Do any tutorials exist on this? If someone could give me any advice, or even a simple "yes this is possible, and it is simple" or "this is possible, but difficult" or "no this is not possible" answer, I would appreciate it. If anyone needs more information, I'll be happy to provide it.
    Thanks,
    Dan

    I don't know if it is possible to run the main method from another Java app by simply calling it...
    But you could just copy and paste the stuff from your main method into a new static method called something like runDBQuery and have all the execution run from there.
    How does that sound? Is it possible?
    What I'm suggeting is:
    Original
    public class DBQuery{
    public static void methodA(){
    public static void doQuery(){
    methodA();
    public static void main(String[] args){
    // Your method calls
    //Your initializing
    doQuery();
    }Revised:
    public class DBQuery{
    public static void methodA(){
    public static void doQuery(){
    methodA();
    public static void doMyQuery(){
    // Your method calls
    //Your initializing
    doQuery();
    // No main needed!!
    //public static void main(String[] args){
    // Your method calls
    //doQuery();
    //}

  • (Youtube-) Video in a Swing GUI

    Hey everyone,
    I'm currently trying to play a video in my Swing GUI with JMF but I really can't get it to work.
    With the help of google I got this far:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.media.CannotRealizeException;
    import javax.media.Manager;
    import javax.media.NoPlayerException;
    import javax.media.Player;
    import javax.swing.JFrame;
    public class MediaPanel extends JFrame {
        public MediaPanel() {
            setLayout(new BorderLayout()); // use a BorderLayout
            // Use lightweight components for Swing compatibility
            Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, true);
            URL mediaURL = null;
            try {
                mediaURL = new URL("http://www.youtube.com/watch?v=Q7_Z_mQUBa8");
            } catch (MalformedURLException ex) {
                System.err.println(ex);
            try {
                // create a player to play the media specified in the URL
                Player mediaPlayer = Manager.createRealizedPlayer(mediaURL);
                // get the components for the video and the playback controls
                Component video = mediaPlayer.getVisualComponent();
                Component controls = mediaPlayer.getControlPanelComponent();
                if (video != null) {
                    add(video, BorderLayout.CENTER); // add video component
                if (controls != null) {
                    add(controls, BorderLayout.SOUTH); // add controls
                mediaPlayer.start(); // start playing the media clip
            } // end try
            catch (NoPlayerException noPlayerException) {
                System.err.println("No media player found");
            } // end catch
            catch (CannotRealizeException cannotRealizeException) {
                System.err.println("Could not realize media player");
            } // end catch
            catch (IOException iOException) {
                System.err.println("Error reading from the source");
            } // end catch
        } // end MediaPanel constructor
    }But all I get is errors:
    Warning: The URL may not exist. Please check URL
    No media player found
    Can you please please help me get this working? I would really appreciate a little walkthrough
    Best regards,
    Patrick
    Edited by: 954807 on Aug 24, 2012 6:52 AM

    Just use \ tags. People don't like to go to external sites.
    I really advise you to consider using JavaFX 2 here. Swing is old and not really supported anymore, JMF is also old and absolutely not supported anymore.                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Help on right mouse click in swing GUI.

    I am working on a swing GUI interface which has Panels. One Panel contains two sub panels. I want to add the Right Mouse click feature to the panels. How should i go about achieving this? Please provide sample example if any.
    Thanks in advance.

    anyPanel.addMouseListener(new MouseAdapter(){
       public void mouseReleased(MouseEvent e){
          if(e.isPopupTrigger()){
              // right clicked
    });

Maybe you are looking for