Search Results

Search found 32 results on 2 pages for 'jmenubar'.

Page 1/2 | 1 2  | Next Page >

  • Button in a JMenuBar

    - by Kurru
    Hi I was trying to make a JMenu behave like a JButton but I'm having some problems and hopefully someone here can help! I've added a MenuListener to the JMenu item with this but I cant get the popup menu/focus to leave to enable me to properly click the JMenu repeated times to trigger this function and i was hoping someone could tell me what i'm doing wrong. Thanks. public void menuSelected(MenuEvent e) { ... // do stuff here code JMenu source = (JMenu)e.getSource(); source.setSelected(false); source.setPopupMenuVisible(false); }

    Read the article

  • JPanel Appears Behind JMenuBar

    - by Matt H
    import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; @SuppressWarnings("serial") public class Main extends JFrame { final int FRAME_HEIGHT = 400; final int FRAME_WIDTH = 400; public static void main(String args[]) { new Main(); } public Main() { super("Game"); GameCanvas canvas = new GameCanvas(); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem startMenuItem = new JMenuItem("Pause"); menuBar.add(fileMenu); fileMenu.add(startMenuItem); super.setVisible(true); super.setSize(FRAME_WIDTH, FRAME_WIDTH); super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); super.setJMenuBar(menuBar); } } import java.awt.Canvas; import java.awt.Graphics; import javax.swing.JPanel; @SuppressWarnings("serial") public class GameCanvas extends JPanel { public void paint(Graphics g) { g.drawString("hI", 0, 0); } } This code causes the string to appear behind the JMenuBar. To see the string, you must draw it at (0,10). I'm sure this must be something simple, so do you guys have any ideas?

    Read the article

  • Auto-hide JMenuBar

    - by PeterMmm
    When i run the code above the frame's menu bar come up when the mouse moves to the upper part of the window. The problem is when i open the menu but do not select any item and move out the mouse the menu bar get invisible but the items stay on screen. public class Test extends JFrame { public Test() { setLayout(new BorderLayout()); setSize(300, 300); JMenuBar mb = new JMenuBar(); setJMenuBar(mb); mb.setVisible(false); JMenu menu = new JMenu("File"); mb.add(menu); menu.add(new JMenuItem("Item-1")); menu.add(new JMenuItem("Item-2")); addMouseMotionListener(new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { getJMenuBar().setVisible(e.getY() < 50); } }); } public static void main(String args[]) { new Test().setVisible(true); } }

    Read the article

  • JMenuBar dropping down to a "custom" JPanel and "erased"

    - by Jani
    The JMenuItems of JMenuBar drops down to a JPanel added to the JFrame, but the JPanel erases the JMenuItems. Do I supposed to pause the re-drawing of the JPanel? I'm using getGraphics() on the JPanel for drawing an image, this method is called from a thread with (for example) 200 ms delay. edit: It's a (very simple) game inside the JPanel. (I've added a field "paused" to the JPanel and i've edited the paint method so it repaints the JPanel only if paused is false, however I don't know if this "solution" is good. (It's set to true when the user clicks on a menu and set to false when selects or cancels it.)

    Read the article

  • changing jtoolbar images when JMenuItem is clicked

    - by ammayi100
    Hi, I need to develop a swing application with a menubar. When a menu is clicked, I have to display the menu items as icons in one bar. Same like when another menu is selected, corresponding menu items should be displayed in the bar. How can I achieve this functionality using Swings? Any help would be appreciated. Thanks in Advance, Maruthi Prasanna.

    Read the article

  • Java JMenuItem Accelator Snow Leopard

    - by Jeremy McGee
    about = new JMenuItem("About"); about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A((Toolkit.getDefaultToolkit().getMenuShortcutMask())))); JMenu help = new JMenu("Help"); help.add(about); I was wondering why my aaccelerators were not working. I am running this in snow leopard with JavaSe-1.6 VM. They do work if I pull the menu down then try the key sequence. Thanks

    Read the article

  • Best way to implement game loop without freezing UI thread

    - by Matt H
    I'm trying to make a simple 2D game in Java. So far I have a JFrame, with a menubar, and a class which extends JPanel and overrides it's paint method. Now, I need to get a game loop going, where I will update the position of images and so on. However, I'm stuck at how best to achieve this. Should I use multi-threading, because surely, if you put an infinite loop on the main thread, the UI (and thus my menu bar) will freeze up? Here's my code so far: import java.awt.Color; import java.awt.Graphics; import javax.swing.JPanel; @SuppressWarnings("serial") public class GameCanvas extends JPanel { public void paint(Graphics g) { while (true) { g.setColor(Color.DARK_GRAY); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; @SuppressWarnings("serial") public class Main extends JFrame { GameCanvas canvas = new GameCanvas(); final int FRAME_HEIGHT = 400; final int FRAME_WIDTH = 400; public static void main(String args[]) { new Main(); } public Main() { super("Game"); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem startMenuItem = new JMenuItem("Pause"); menuBar.add(fileMenu); fileMenu.add(startMenuItem); super.add(canvas); super.setVisible(true); super.setSize(FRAME_WIDTH, FRAME_WIDTH); super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); super.setJMenuBar(menuBar); } } Any pointers/tips? Also, where should I put my loop? In my main class, or my GameCanvas class? Any help is appreciated, thanks.

    Read the article

  • How to add support for resizing when using an undecorated JFrame?

    - by Jonas
    I would like to customize my titlebar, minimize-, maximize- and the close-button. So I used setUndecorated(true); on my JFrame, but I still want to be able to resize the window. What is the best way to implement that? I have a border on the RootPane, and I could use MouseListeners on the Border or the RootPane. Any recommendations? import java.awt.Color; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.border.LineBorder; public class UndecoratedFrame extends JFrame { private LineBorder border = new LineBorder(Color.BLUE,2); private JMenuBar menuBar = new JMenuBar(); private JMenu menu = new JMenu("File"); private JMenuItem item = new JMenuItem("Nothing"); public UndecoratedFrame() { menu.add(item); menuBar.add(menu); this.setJMenuBar(menuBar); this.setUndecorated(true); this.getRootPane().setBorder(border); this.setSize(400,340); this.setVisible(true); } public static void main(String[] args) { new UndecoratedFrame(); } }

    Read the article

  • BorderLayout problem with JSplitPane after adding JToolbar (Java)

    - by Alex Cheng
    Hello all. Problem: My program layout is fine, as below before I add JToolbar to BorderLayout.PAGE_START Here's a screenshot before JToolbar is added: Here's how it looked like after adding JToolbar: May I know what did I do wrong? Here's the code I used: //Create the text pane and configure it. textPane = new JTextPane(); -snipped code- JScrollPane scrollPane = new JScrollPane(textPane); scrollPane.setPreferredSize(new Dimension(300, 300)); //Create the text area for the status log and configure it. changeLog = new JTextArea(5, 30); changeLog.setEditable(false); JScrollPane scrollPaneForLog = new JScrollPane(changeLog); //Create a split pane for the change log and the text area. JSplitPane splitPane = new JSplitPane( JSplitPane.VERTICAL_SPLIT, scrollPane, scrollPaneForLog); splitPane.setOneTouchExpandable(true); //Create the status area. JPanel statusPane = new JPanel(new GridLayout(1, 1)); CaretListenerLabel caretListenerLabel = new CaretListenerLabel("Caret Status"); statusPane.add(caretListenerLabel); //Create the toolbar JToolBar toolBar = new JToolBar(); -snipped code- //Add the components. getContentPane().add(toolBar, BorderLayout.PAGE_START); getContentPane().add(splitPane, BorderLayout.CENTER); getContentPane().add(statusPane, BorderLayout.PAGE_END); //Set up the menu bar. actions = createActionTable(textPane); JMenu editMenu = createEditMenu(); JMenu styleMenu = createStyleMenu(); JMenuBar mb = new JMenuBar(); mb.add(editMenu); mb.add(styleMenu); setJMenuBar(mb); Please help, I'm new to GUI Building, and I don't feel like using Netbeans to drag and drop the UI for me... Thank you in advance.

    Read the article

  • Swing Menu dimensions

    - by ikurtz
    Greetings. I am trying to learn Java and Swing (today is my first day). I have been able to set up a menu in my test application. but the items occupy very little space (they are narrow). How do I go about extendng the amount of space it uses? I am studying Teach Yourself Java 6 in 21 Days 5th Ed, Java Swing, 2nd Edition, 2002 and Teach Yourself Programming With Java In 24 Hours, 4th Edition (2005) but none of them shed any light on this issue. EDIT: Menu code: JMenu _Game = new JMenu("Game"); JMenuItem _New = new JMenuItem("New"); JMenuItem _Exit = new JMenuItem("Exit"); JMenu _Turn = new JMenu("Turn"); JMenuItem _Red = new JMenuItem("Red"); JMenuItem _Yellow = new JMenuItem("Yellow"); _Turn.add(_Red); _Turn.add(_Yellow); _Game.add(_New); _Game.addSeparator(); _Game.add(_Turn); _Game.addSeparator(); _Game.add(_Exit); JMenu _Help = new JMenu("Help"); JMenuItem _About = new JMenuItem("About"); _Help.add(_About); JMenuBar _MenuBar = new JMenuBar(); _MenuBar.add(_Game); _MenuBar.add(_Help); setJMenuBar(_MenuBar); EDIT: Solved! JMenuItem _New = new JMenuItem("New "); just add spaces as needed! simple.

    Read the article

  • Java Box Class: Unsolvable: aligning components to the left or right

    - by user323186
    I have been trying to left align buttons contained in a Box to the left, with no success. They align left alright, but for some reason dont shift all the way left as one would imagine. I attach the code below. Please try compiling it and see for yourself. Seems bizarre to me. Thanks, Eric import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class MainGUI extends Box implements ActionListener{ //Create GUI Components Box centerGUI=new Box(BoxLayout.X_AXIS); Box bottomGUI=new Box(BoxLayout.X_AXIS); //centerGUI subcomponents JTextArea left=new JTextArea(), right=new JTextArea(); JScrollPane leftScrollPane = new JScrollPane(left), rightScrollPane = new JScrollPane(right); //bottomGUI subcomponents JButton encrypt=new JButton("Encrypt"), decrypt=new JButton("Decrypt"), close=new JButton("Close"), info=new JButton("Info"); //Create Menubar components JMenuBar menubar=new JMenuBar(); JMenu fileMenu=new JMenu("File"); JMenuItem open=new JMenuItem("Open"), save=new JMenuItem("Save"), exit=new JMenuItem("Exit"); int returnVal =0; public MainGUI(){ super(BoxLayout.Y_AXIS); initCenterGUI(); initBottomGUI(); initFileMenu(); add(centerGUI); add(bottomGUI); addActionListeners(); } private void addActionListeners() { open.addActionListener(this); save.addActionListener(this); exit.addActionListener(this); encrypt.addActionListener(this); decrypt.addActionListener(this); close.addActionListener(this); info.addActionListener(this); } private void initFileMenu() { fileMenu.add(open); fileMenu.add(save); fileMenu.add(exit); menubar.add(fileMenu); } public void initCenterGUI(){ centerGUI.add(leftScrollPane); centerGUI.add(rightScrollPane); } public void initBottomGUI(){ bottomGUI.setAlignmentX(LEFT_ALIGNMENT); //setBorder(BorderFactory.createLineBorder(Color.BLACK)); bottomGUI.add(encrypt); bottomGUI.add(decrypt); bottomGUI.add(close); bottomGUI.add(info); } @Override public void actionPerformed(ActionEvent arg0) { // find source of the action Object source=arg0.getSource(); //if action is of such a type do the corresponding action if(source==close){ kill(); } else if(source==open){ //CHOOSE FILE File file1 =chooseFile(); String input1=readToString(file1); System.out.println(input1); left.setText(input1); } else if(source==decrypt){ //decrypt everything in Right Panel and output in left panel decrypt(); } else if(source==encrypt){ //encrypt everything in left panel and output in right panel encrypt(); } else if(source==info){ //show contents of info file in right panel doInfo(); } else { System.out.println("Error"); //throw new UnimplementedActionException(); } } private void doInfo() { // TODO Auto-generated method stub } private void encrypt() { // TODO Auto-generated method stub } private void decrypt() { // TODO Auto-generated method stub } private String readToString(File file) { FileReader fr = null; try { fr = new FileReader(file); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader br=new BufferedReader(fr); String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } String input=""; while(line!=null){ input=input+"\n"+line; try { line=br.readLine(); } catch (IOException e) { e.printStackTrace(); } } return input; } private File chooseFile() { //Create a file chooser final JFileChooser fc = new JFileChooser(); returnVal = fc.showOpenDialog(fc); return fc.getSelectedFile(); } private void kill() { System.exit(0); } public static void main(String[] args) { // TODO Auto-generated method stub MainGUI test=new MainGUI(); JFrame f=new JFrame("Tester"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setJMenuBar(test.menubar); f.setPreferredSize(new Dimension(600,400)); //f.setUndecorated(true); f.add(test); f.pack(); f.setVisible(true); } }

    Read the article

  • JToolbar is hidden by JMenu

    - by pierre
    I'm using Netbeans to add a JToolbar to my window which also has a JMenuBar. Here is the design-time look: .. but during run-time I get this: With the toolbar seemingly partially hidden under the menu names. This is on the Mac, btw. Is there something stupid I've forgotten to do or some layout trick I should be using? EDIT: I'll add that the area below the toolbar is a SplitContainer.

    Read the article

  • Cannot find Symbol = new

    - by Nick G.
    Java is complaining! cannot find symbol symbol : constructor Bar() location: class Bar JPanel panel = new Bar(); ^ QUESTION: Why am I getting this error?...everything seems to be correct. this is the coding: public class JFrameWithPanel { public static void main(String[] args) { JPanel panel = new Bar(); } } Bar( ) is public class Bar extends JPanel { public Bar(final JFrame frame) { super(new BorderLayout()); String[] tests = { "A+ Certification", "Network+ Certification", "Security+ Certification", "CIT Full Test Package" }; JComboBox comboBox = new JComboBox(tests); TextArea text = new TextArea(5, 10); add(new JLabel("Welcome to the CIT Test Program ")); add(new JLabel("Please select which Test Package from the list below.")); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenu editMenu = new JMenu("Edit"); JMenu helpMenu = new JMenu("Help"); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(helpMenu); JMenuItem newMenu = new JMenuItem("New (Ctrl+N)"); JMenuItem openMenu = new JMenuItem("Open (Ctrl+O)"); JMenuItem saveMenu = new JMenuItem("Save (Ctrl+S)"); JMenuItem exitMenu = new JMenuItem("Exit (Ctrl+W)"); JMenuItem cutMenu = new JMenuItem("Cut (Ctrl+X)"); JMenuItem copyMenu = new JMenuItem("Copy (Ctrl+C)"); JMenuItem pasteMenu = new JMenuItem("Paste (Ctrl+V)"); JMenuItem infoMenu = new JMenuItem("Help (Ctrl+H)"); fileMenu.add(newMenu); fileMenu.add(openMenu); fileMenu.add(saveMenu); fileMenu.add(exitMenu); editMenu.add(cutMenu); editMenu.add(copyMenu); editMenu.add(pasteMenu); helpMenu.add(infoMenu); this.add(comboBox, BorderLayout.NORTH); this.add(text, BorderLayout.SOUTH); frame.setJMenuBar(menuBar); add(new JButton("Select") { { addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); JOptionPane.showMessageDialog(frame, "IT WORKS!"); } }); } }); } }

    Read the article

  • JMenu issue with Gnome's native look and feel.

    - by gmunk
    I stumbled on a very odd problem while trying to set up a JMenuBar with the native look and feel of Gnome. Here is a screenshot: http://img23.imageshack.us/i/issuel.png/ It has to say File there but it gets cut out. http://pastebin.com/CjFhmxcf http://pastebin.com/gwB3vnC3 Any, help is appreciated!

    Read the article

  • How do I make my custom Swing component visible?

    - by Alex
    I have no idea why it won't show. First I create an instance of the component and then add it to a certain element in a two-dimensional JPanel array. Then I loop through that array and add each JPanel to another JPanel container which is to hold all the JPanels. I then add that final container to my JFrame window and set visibility to true, it should be visible? public class View extends JFrame { Board gameBoard; JFrame gameWindow = new JFrame("Chess"); JPanel gamePanel = new JPanel(); JPanel[][] squarePanel = new JPanel[8][8]; JMenuBar gameMenu = new JMenuBar(); JButton restartGame = new JButton("Restart"); JButton pauseGame = new JButton("Pause"); JButton log = new JButton("Log"); View(Board board){ gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE); gameWindow.setSize(400, 420); gameWindow.getContentPane().add(gamePanel, BorderLayout.CENTER); gameWindow.getContentPane().add(gameMenu, BorderLayout.NORTH); gameMenu.add(restartGame); gameMenu.add(pauseGame); gameMenu.add(log); gameBoard = board; drawBoard(gameBoard); gameWindow.setResizable(false); gameWindow.setVisible(true); } public void drawBoard(Board board){ for(int row = 0; row < 8; row++){ for(int col = 0; col < 8; col++){ Box box = new Box(board.getSquare(col, row).getColour(), col, row); squarePanel[col][row] = new JPanel(); squarePanel[col][row].add(box); } } for(JPanel[] col : squarePanel){ for(JPanel square : col){ gamePanel.add(square); } } } } @SuppressWarnings("serial") class Box extends JComponent{ Color boxColour; int col, row; public Box(Color boxColour, int col, int row){ this.boxColour = boxColour; this.col = col; this.row = row; repaint(); } protected void paintComponent(Graphics drawBox){ drawBox.setColor(boxColour); drawBox.drawRect(50*col, 50*row, 50, 50); drawBox.fillRect(50*col, 50*row, 50, 50); } } A final question as well. Notice how each Box component has a position, what happens to the position when I add the component to a JPanel and add the JPanel to my JFrame? Does it still have the same position in relation to the other Box components?

    Read the article

  • Why Look and feel is not getting updated properly?

    - by swift
    I’m developing a swing application in which I have an option to change the Look and feel of the application on click of a button. Now my problem is when I click the button to change the theme it’s not properly updating the L&F of my app, say my previous theme is “noire” and I choose “MCWin” after it, but the style of the noire theme is still there Here is sample working code: package whiteboard; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants; public class DiscussionBoard extends JFrame implements ComponentListener,ActionListener { // Variables declaration private JMenuItem audioMenuItem; private JMenuItem boardMenuItem; private JMenuItem exitMenuItem; private JMenuItem clientsMenuItem; private JMenuItem acryl; private JMenuItem hifi; private JMenuItem aero; private JMenuItem aluminium; private JMenuItem bernstein; private JMenuItem fast; private JMenuItem graphite; private JMenuItem luna; private JMenuItem mcwin; private JMenuItem noire; private JMenuItem smart; private JMenuBar boardMenuBar; private JMenuItem messengerMenuItem; private JMenu openMenu; private JMenu saveMenu; private JMenu themesMenu; private JMenuItem saveMessengerMenuItem; private JMenuItem saveWhiteboardMenuItem; private JMenu userMenu; JLayeredPane layerpane; /** Creates new form discussionBoard * @param connection */ public DiscussionBoard() { initComponents(); setLocationRelativeTo(null); addComponentListener(this); } private void initComponents() { boardMenuBar = new JMenuBar(); openMenu = new JMenu(); themesMenu = new JMenu(); messengerMenuItem = new JMenuItem(); boardMenuItem = new JMenuItem(); audioMenuItem = new JMenuItem(); saveMenu = new JMenu(); saveMessengerMenuItem = new JMenuItem(); saveWhiteboardMenuItem = new JMenuItem(); userMenu = new JMenu(); clientsMenuItem = new JMenuItem(); exitMenuItem = new JMenuItem(); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new GridBagLayout()); setResizable(false); setTitle("Discussion Board"); openMenu.setText("Open"); saveMenu.setText("Save"); themesMenu.setText("Themes"); acryl = new JMenuItem("Acryl"); hifi = new JMenuItem("HiFi"); aero = new JMenuItem("Aero"); aluminium = new JMenuItem("Aluminium"); bernstein = new JMenuItem("Bernstein"); fast = new JMenuItem("Fast"); graphite = new JMenuItem("Graphite"); luna = new JMenuItem("Luna"); mcwin = new JMenuItem("MCwin"); noire = new JMenuItem("Noire"); smart = new JMenuItem("Smart"); hifi.addActionListener(this); acryl.addActionListener(this); aero.addActionListener(this); aluminium.addActionListener(this); bernstein.addActionListener(this); fast.addActionListener(this); graphite.addActionListener(this); luna.addActionListener(this); mcwin.addActionListener(this); noire.addActionListener(this); smart.addActionListener(this); messengerMenuItem.setText("Messenger"); openMenu.add(messengerMenuItem); openMenu.add(boardMenuItem); audioMenuItem.setText("Audio Messenger"); openMenu.add(audioMenuItem); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); openMenu.add(exitMenuItem); boardMenuBar.add(openMenu); saveMessengerMenuItem.setText("Messenger"); saveMenu.add(saveMessengerMenuItem); saveWhiteboardMenuItem.setText("Whiteboard"); saveMenu.add(saveWhiteboardMenuItem); boardMenuBar.add(saveMenu); userMenu.setText("Users"); clientsMenuItem.setText("Current Session"); userMenu.add(clientsMenuItem); themesMenu.add(acryl); themesMenu.add(hifi); themesMenu.add(aero); themesMenu.add(aluminium); themesMenu.add(bernstein); themesMenu.add(fast); themesMenu.add(graphite); themesMenu.add(luna); themesMenu.add(mcwin); themesMenu.add(noire); themesMenu.add(smart); boardMenuBar.add(userMenu); boardMenuBar.add(themesMenu); saveMessengerMenuItem.setEnabled(false); saveWhiteboardMenuItem.setEnabled(false); setJMenuBar(boardMenuBar); setSize(1024, 740); setVisible(true); } protected void exitMenuItemActionPerformed(ActionEvent evt) { System.exit(0); } @Override public void componentHidden(ComponentEvent arg0) { } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentResized(ComponentEvent arg0) { } @Override public void componentShown(ComponentEvent arg0) { } @Override public void actionPerformed(ActionEvent e) { try { if(e.getSource()==hifi) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel"); enableTheme(); hifi.setEnabled(false); } else if(e.getSource()==acryl) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel"); enableTheme(); acryl.setEnabled(false); } else if(e.getSource()==aero) { UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel"); enableTheme(); aero.setEnabled(false); } else if(e.getSource()==aluminium) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel"); enableTheme(); aluminium.setEnabled(false); } else if(e.getSource()==bernstein) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.bernstein.BernsteinLookAndFeel"); enableTheme(); bernstein.setEnabled(false); } else if(e.getSource()==fast) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.fast.FastLookAndFeel"); enableTheme(); fast.setEnabled(false); } else if(e.getSource()==graphite) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel"); enableTheme(); graphite.setEnabled(false); } else if(e.getSource()==luna) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.luna.LunaLookAndFeel"); enableTheme(); luna.setEnabled(false); } else if(e.getSource()==mcwin) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel"); enableTheme(); mcwin.setEnabled(false); } else if(e.getSource()==noire) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel"); enableTheme(); noire.setEnabled(false); } else if(e.getSource()==smart) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.updateComponentTreeUI(getRootPane()); UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel"); enableTheme(); smart.setEnabled(false); } SwingUtilities.updateComponentTreeUI(getRootPane()); } catch (Exception ex) { ex.printStackTrace(); } } private void enableTheme() { acryl.setEnabled(true); hifi.setEnabled(true); aero.setEnabled(true); aluminium.setEnabled(true); bernstein.setEnabled(true); fast.setEnabled(true); graphite.setEnabled(true); luna.setEnabled(true); mcwin.setEnabled(true); noire.setEnabled(true); smart.setEnabled(true); } public static void main(String []ar) { try { UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } new DiscussionBoard(); } } What’s the problem here? why its not getting updated? There is a demo application here which is exactly doing what i want but i cant get a clear idea of it.

    Read the article

  • Fonts, goes back to default size

    - by Bladimir Ruiz
    Every time I change the font, it goes back to the default size, which is 12, even if I change it before with the "Tamano" menu, it only goes back to 12 every time, my guess would be the way I change the size with deriveFont(), but don't I now any other way to change it. public static class cambiar extends JFrame { public cambiar() { final Font aryal = new Font("Comic Sans MS", Font.PLAIN, 12); JFrame ventana = new JFrame("Cambios en el Texto!"); JPanel adentro = new JPanel(); final JLabel texto = new JLabel("Texto a Cambiar!"); texto.setFont(aryal); JMenuBar menu = new JMenuBar(); JMenu fuentes = new JMenu("Fuentes"); /* Elementos de Fuentes */ JMenuItem arial = new JMenuItem("Arial"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Font arrrial = new Font("Arial", Font.PLAIN, 12); float tam = (float) texto.getFont().getSize(); String hola = String.valueOf(tam); texto.setFont(arrrial); texto.setFont(texto.getFont().deriveFont(tam)); } }); fuentes.add(arial); /* FIN Fuentes */ JMenu tamano = new JMenu("Tamano"); /* Elementos de Tamano */ JMenuItem font13 = new JMenuItem("13"); font13.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(texto.getFont().deriveFont(23.0f)); } }); JMenuItem font14 = new JMenuItem("14"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font15 = new JMenuItem("15"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font16 = new JMenuItem("16"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font17 = new JMenuItem("17"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font18 = new JMenuItem("18"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font19 = new JMenuItem("19"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font20 = new JMenuItem("20"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); tamano.add(font13); /* FIN tanano */ JMenu tipo = new JMenu("Tipo"); /* Elementos de tipo */ /* FIN tipo */ /* Elementos del JMENU */ menu.add(fuentes); menu.add(tamano); menu.add(tipo); /* FIN JMENU */ /* Elementos del JPanel */ adentro.add(menu); adentro.add(texto); /* FIN JPanel */ /* Elementos del JFRAME */ ventana.add(adentro); ventana.setVisible(true); ventana.setSize(250, 250); /* FIN JFRAME */ } } Thanks in Advance!

    Read the article

  • JFrame not working correctly

    - by Nick Gibson
    This is making me very angry, I have worked on this for 2 days, have 2 books open and have looked through them, and STILL can't get this program to run the way I want it run. I'm getting to the point where if this doesn't help, I quit. I want a SIMPLE Frame application. It has a JComboBox centered at the top. Next to it is a text field big enough to show numeric digits such as "$49.99" Below it is a spot for a Text area showing terms of service Below that is the checkbox agreeing to the terms of service Below that is 2 buttons "Accept" and "Decline" I Have worked on this for 2 days, here is the coding: public class Bar extends JFrame implements ActionListener { public Bar(final JFrame frame) { String[] tests = { "A+ Certification", "Network+ Certification", "Security+ Certification", "CIT Full Test Package" }; JButton button = new JButton("Click Meh"); add(new JLabel("Welcome to the CIT Test Program ")); add(new JLabel("Please select which Test Package from the list below.")); frame.setVisible(true); frame.setSize(250,250); JPanel pane1 = new JPanel(new FlowLayout()); JPanel pane2 = new JPanel(new FlowLayout()); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenu editMenu = new JMenu("Edit"); JMenu helpMenu = new JMenu("Help"); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(helpMenu); JMenuItem newMenu = new JMenuItem("New (Ctrl+N)"); JMenuItem openMenu = new JMenuItem("Open (Ctrl+O)"); JMenuItem saveMenu = new JMenuItem("Save (Ctrl+S)"); saveMenu.addActionListener(this); JMenuItem exitMenu = new JMenuItem("Exit (Ctrl+W)"); JMenuItem cutMenu = new JMenuItem("Cut (Ctrl+X)"); JMenuItem copyMenu = new JMenuItem("Copy (Ctrl+C)"); JMenuItem pasteMenu = new JMenuItem("Paste (Ctrl+V)"); JMenuItem infoMenu = new JMenuItem("Help (Ctrl+H)"); fileMenu.add(newMenu); fileMenu.add(openMenu); fileMenu.add(saveMenu); fileMenu.add(exitMenu); editMenu.add(cutMenu); editMenu.add(copyMenu); editMenu.add(pasteMenu); helpMenu.add(infoMenu); frame.setJMenuBar(menuBar); JComboBox packageChoice = new JComboBox(tests); frame.add(packageChoice); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); { } } EDIT: Forgot to add the second program public class JFrameWithPanel { public static void main(String[] args) { JPanel panel = new Bar(new JFrame("CIT Test Program")); } } How do I get this to have everything where I want it and show up? I'm very confused because of this and now barely even get how Frames work.

    Read the article

  • Table header is not shown

    - by Vivien
    My error is that the table headers of my two tables are not shown. Right now I am setting the header with new JTable(data, columnNames). Here is an example which shows, my problem: public class Test extends JFrame { private static final long serialVersionUID = -4682396888922360841L; private JMenuBar menuBar; private JMenu mAbout; private JMenu mMain; private JTabbedPane tabbedPane; public SettingsTab settings = new SettingsTab(); private void addMenuBar() { menuBar = new JMenuBar(); mMain = new JMenu("Main"); mAbout = new JMenu("About"); menuBar.add(mMain); menuBar.add(mAbout); setJMenuBar(menuBar); } public void createTabBar() { tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.addTab("Settings", settings.createLayout()); add(tabbedPane); tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); } private void makeLayout() { setTitle("Test"); setLayout(new BorderLayout()); setPreferredSize(new Dimension(1000, 500)); addMenuBar(); createTabBar(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setVisible(true); } public void start() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { makeLayout(); } }); } public static void main(String[] args) { Test gui = new Test(); gui.start(); } public class SettingsTab extends JPanel { public JScrollPane createLayout() { JPanel panel = new JPanel(new MigLayout("")); JScrollPane sp = new JScrollPane(panel); sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); panel.add(table1(), "growx, wrap"); panel.add(Box.createRigidArea(new Dimension(0,10))); panel.add(table2()); // panel.add(Box.createRigidArea(new Dimension(0,10))); return sp; } public JPanel table1() { JPanel panel1 = new JPanel(); String[] columnNames = {"First Name", "Last Name"}; Object[][] data = { {"Kathy", "Smith"}, {"John", "Doe"}, {"Sue", "Black"}, {"Jane", "White"}, {"Joe", "Brown"}, {"John", "Doe"}, {"Sue", "Black"}, {"Jane", "White"}, {"Joe", "Brown"} }; final JTable table = new JTable(data, columnNames); tableProperties(table); panel1.add(table); panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS)); return panel1; } public JPanel table2() { JPanel panel1 = new JPanel(); String[] columnNames = {"First Name", "Last Name"}; Object[][] data = { {"Kathy", "Smith"}, {"John", "Doe"}, {"Sue", "Black"}, {"Jane", "White"}, {"Joe", "Brown"}, {"John", "Doe"}, {"Sue", "Black"}, {"Jane", "White"}, {"Joe", "Brown"} }; final JTable table = new JTable(data, columnNames); table.setPreferredScrollableViewportSize(new Dimension(500, 70)); table.setFillsViewportHeight(true); tableProperties(table); panel1.add(table); panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS)); return panel1; } public void tableProperties(JTable table) { table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); table.repaint(); table.revalidate(); } } } Any recommendations what I am doing wrong?

    Read the article

  • save as .txt format

    - by user1180492
    I made a NotePad program. The problem is it doesn't save in .txt format, It save as a file with no format. But it can open .txt files. How can i fix it? Here is my work. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Scanner; import java.io.*; public class NotePad extends JFrame { private JTextArea noteArea; public static void main(String[] args) { NotePad p = new NotePad(); p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); p.setSize(500,300); p.setVisible(true); } public NotePad() { super("Java Notepad"); setLayout(new BorderLayout()); noteArea = new JTextArea("",20,20); noteArea.setWrapStyleWord(true); noteArea.setLineWrap(true); Font font = new Font("sanserif", Font.BOLD,14); noteArea.setFont(font); JScrollPane scroller = new JScrollPane(noteArea); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); add(scroller,BorderLayout.CENTER); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem openMenu = new JMenuItem("Open"); openMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser openFile = new JFileChooser(); openFile.showOpenDialog(new NotePad()); loadFile(openFile.getSelectedFile()); } }); JMenuItem saveMenu = new JMenuItem("Save"); saveMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser saveFile = new JFileChooser(); saveFile.showSaveDialog(new NotePad()); fileSaved(saveFile.getSelectedFile()); } }); JMenuItem exitMenu = new JMenuItem("Close"); exitMenu.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae) { System.exit(0); } }); fileMenu.add(openMenu); fileMenu.add(saveMenu); fileMenu.add(exitMenu); menuBar.add(fileMenu); this.setJMenuBar(menuBar); } public void loadFile(File file) { noteArea.setText(""); try { BufferedReader read = new BufferedReader(new FileReader(file)); String line = null; while((line =read.readLine())!=null) { noteArea.append(line +"\n"); } read.close(); } catch (Exception e) { System.out.println("Error " + e.toString()); } } public void fileSaved(File file) { try { PrintWriter writer = new PrintWriter(file); String[] lines = noteArea.getText().split("\\n"); for (String ) { writer.println(words); } writer.close(); } catch (Exception e) { System.out.println("Error " + e.toString()); } } } btw I can't post my question because of not explaning the scenario according to the site. So there. Thanks for the help

    Read the article

  • actionlistener not responding in java calculator

    - by tokee
    hi, please see calculator interface code below, from my beginners point of view the "1" should display when it's pressed but evidently i'm doing something wrong. any suggestiosn please? import java.awt.*; import javax.swing.*; import javax.swing.border.*; import java.awt.event.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** *A Class that operates as the framework for a calculator. *No calculations are performed in this section */ public class CalcFrame extends JPanel { private CalcEngine calc; private JFrame frame; private JTextField display; private JLabel status; /** * Constructor for objects of class GridLayoutExample */ //public CalcFrame(CalcEngine engine) //{ //frame.setVisible(true); // calc = engine; // makeFrame(); //} public CalcFrame() { makeFrame(); calc = new CalcEngine(); } class ButtonListener implements ActionListener { ButtonListener() { } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("1")) { System.out.println("1"); } } } /** * This allows you to quit the calculator. */ // Alows the class to quit. private void quit() { System.exit(0); } // Calls the dialog frame with the information about the project. private void showAbout() { JOptionPane.showMessageDialog(frame, "Declan Hodge and Tony O'Keefe Group Project", "About Calculator Group Project", JOptionPane.INFORMATION_MESSAGE); } // ---- swing stuff to build the frame and all its components ---- /** * The following creates a layout of the calculator frame. */ private void makeFrame() { frame = new JFrame("Group Project Calculator"); makeMenuBar(frame); JPanel contentPane = (JPanel)frame.getContentPane(); contentPane.setLayout(new BorderLayout(8, 8)); contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10)); /** * Insert a text field */ display = new JTextField(8); contentPane.add(display, BorderLayout.NORTH); //Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(4, 5)); JPanel buttonPanel = new JPanel(new GridLayout(4, 4)); contentPane.add(new JButton("9")); contentPane.add(new JButton("8")); contentPane.add(new JButton("7")); contentPane.add(new JButton("6")); contentPane.add(new JButton("5")); contentPane.add(new JButton("4")); contentPane.add(new JButton("3")); contentPane.add(new JButton("2")); contentPane.add(new JButton("1")); contentPane.add(new JButton("0")); contentPane.add(new JButton("+")); contentPane.add(new JButton("-")); contentPane.add(new JButton("/")); contentPane.add(new JButton("*")); contentPane.add(new JButton("=")); contentPane.add(new JButton("C")); contentPane.add(new JButton("CE")); contentPane.add(new JButton("%")); contentPane.add(new JButton("#")); //contentPane.add(buttonPanel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } /** * Create the main frame's menu bar. * The frame that the menu bar should be added to. */ private void makeMenuBar(JFrame frame) { final int SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu menu; JMenuItem item; // create the File menu menu = new JMenu("File"); menubar.add(menu); // create the Quit menu with a shortcut "Q" key. item = new JMenuItem("Quit"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { quit(); } }); menu.add(item); // Adds an about menu. menu = new JMenu("About"); menubar.add(menu); // Displays item = new JMenuItem("Calculator Project"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAbout(); } }); menu.add(item); } }

    Read the article

  • Problem creating calculations 'engine' in two class java calculator

    - by tokee
    i have hit a brick wall whilst attempting to create a two class java calculator but have been unsuccessful so far in getting it working. i have the code for an interface which works and displays ok but creating a seperate class 'CalcEngine' to do the actual calculations has proven to be beyond me. I'd appreciate it if someone could kick start things for me and create a class calcEngine which works with the interface class and allows input when from single button i.e. if one is pressed on the calc then 1 displays onscreen. please note i'm not asking someone to do the whole thing for me as i want to learn and i'm confident i can do the rest including addition subtraction etc. once i get over the obstacle of getting the two classes to communicate. any and all assistance would be very much appreciated. Please see the calcInterface class code below - import java.awt.*; import javax.swing.*; import javax.swing.border.*; import java.awt.event.*; /** *A Class that operates as the framework for a calculator. *No calculations are performed in this section */ public class CalcFrame implements ActionListener { private CalcEngine calc; private JFrame frame; private JTextField display; private JLabel status; /** * Constructor for objects of class GridLayoutExample */ public CalcFrame() { makeFrame(); //calc = engine; } /** * This allows you to quit the calculator. */ // Alows the class to quit. private void quit() { System.exit(0); } // Calls the dialog frame with the information about the project. private void showAbout() { JOptionPane.showMessageDialog(frame, "Group Project", "About Calculator Group Project", JOptionPane.INFORMATION_MESSAGE); } private void makeFrame() { frame = new JFrame("Group Project Calculator"); makeMenuBar(frame); JPanel contentPane = (JPanel)frame.getContentPane(); contentPane.setLayout(new BorderLayout(8, 8)); contentPane.setBorder(new EmptyBorder( 10, 10, 10, 10)); /** * Insert a text field */ display = new JTextField(); contentPane.add(display, BorderLayout.NORTH); //Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(4, 4)); JPanel buttonPanel = new JPanel(new GridLayout(4, 4)); contentPane.add(new JButton("1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("3")); contentPane.add(new JButton("4")); contentPane.add(new JButton("5")); contentPane.add(new JButton("6")); contentPane.add(new JButton("7")); contentPane.add(new JButton("8")); contentPane.add(new JButton("9")); contentPane.add(new JButton("0")); contentPane.add(new JButton("+")); contentPane.add(new JButton("-")); contentPane.add(new JButton("/")); contentPane.add(new JButton("*")); contentPane.add(new JButton("=")); contentPane.add(new JButton("C")); contentPane.add(buttonPanel, BorderLayout.CENTER); //status = new JLabel(calc.getAuthor()); //contentPane.add(status, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } /** * Create the main frame's menu bar. * The frame that the menu bar should be added to. */ private void makeMenuBar(JFrame frame) { final int SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); JMenuBar menubar = new JMenuBar(); frame.setJMenuBar(menubar); JMenu menu; JMenuItem item; // create the File menu menu = new JMenu("File"); menubar.add(menu); // create the Quit menu with a shortcut "Q" key. item = new JMenuItem("Quit"); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, SHORTCUT_MASK)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { quit(); } }); menu.add(item); // Adds an about menu. menu = new JMenu("About"); menubar.add(menu); // Displays item = new JMenuItem("Calculator Project"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showAbout(); } }); menu.add(item); } /** * An interface action has been performed. * Find out what it was and handle it. * @param event The event that has occured. */ public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); if(command.equals("0") || command.equals("1") || command.equals("2") || command.equals("3") || command.equals("4") || command.equals("5") || command.equals("6") || command.equals("7") || command.equals("8") || command.equals("9")) { int number = Integer.parseInt(command); calc.numberPressed(number); } else if(command.equals("+")) { calc.plus(); } else if(command.equals("-")) { calc.minus(); } else if(command.equals("=")) { calc.equals(); } else if(command.equals("C")) { calc.clear(); } else if(command.equals("?")) { } // else unknown command. redisplay(); } /** * Update the interface display to show the current value of the * calculator. */ private void redisplay() { display.setText("" + calc.getDisplayValue()); } /** * Toggle the info display in the calculator's status area between the * author and version information. */ }

    Read the article

  • problem in login in yahoo massanger

    - by khoyendra
    package session; import java.io.FileWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.JOptionPane; import org.openymsg.network.FireEvent; import org.openymsg.network.Session; import org.openymsg.network.SessionState; import org.openymsg.network.event.SessionListener; public class BotGUI extends javax.swing.JFrame implements SessionListener{ /** Creates new form BotGUI */ FileWriter fw; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public BotGUI() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); uNameTextField = new javax.swing.JTextField(); uPassPasswordField = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel3.setBackground(new java.awt.Color(51, 51, 51)); jLabel1.setBackground(new java.awt.Color(0, 0, 255)); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Yahoo Login Panel"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(38, 38, 38) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(532, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE) ); jPanel2.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 710, 30)); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel2.setText("Username"); jPanel4.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 20, 60, 20)); jLabel3.setText("Password"); jPanel4.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 20, 60, 20)); jPanel4.add(uNameTextField, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 20, 140, 20)); jPanel4.add(uPassPasswordField, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 20, 140, -1)); jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setText("Login"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel4.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(490, 15, 90, -1)); jPanel2.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 30, 710, 60)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(293, Short.MAX_VALUE)) ); jMenu1.setText("Option"); jMenuItem1.setText("Logout"); jMenu1.add(jMenuItem1); jMenuItem2.setText("Load CSV"); jMenu1.add(jMenuItem2); jMenuItem3.setText("Exit"); jMenu1.add(jMenuItem3); jMenuBar1.add(jMenu1); jMenu2.setText("Help"); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold> public void handleConnectionClosed() { connectionClosed = true; loggedIn = false; } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { if(!uNameTextField.getText().equals("") && !uPassPasswordField.getText().equals("")){ Yahoo_login(uNameTextField.getText(),uPassPasswordField.getText()); }else{ JOptionPane.showMessageDialog(null, "Plese Enter User Id and Password"); } } Session yahooMessengerSession; MySessionListener mySessionListener; boolean loggedIn = false; boolean connectionClosed = false; public void Yahoo_login(String uName, String pass) { connectionClosed = false; if (loggedIn == false) { yahooMessengerSession = new Session(); mySessionListener = new MySessionListener(this); yahooMessengerSession.addSessionListener(mySessionListener); try { if ((uName.equals("")) || (pass.equals(""))) { System.out.println("User name/password is blank"); } else{ //initialized a file writer for log file System.out.println("Login start........"); yahooMessengerSession.login(uName, pass, true); //checks whether user was succesful in login in if (yahooMessengerSession!=null && yahooMessengerSession.getSessionStatus()== SessionState.LOGGED_ON) { //this loop is reached when the user has been successfully logined System.out.println("Login Success"); fw.write("User (" + uName + ") logged in at : " + dateFormat.format("09.05.10") + " \n"); fw.close(); } else { yahooMessengerSession.reset(); } } } catch(Exception e){ } } } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BotGUI().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JTextField uNameTextField; private javax.swing.JPasswordField uPassPasswordField; // End of variables declaration public void dispatch(FireEvent fe) { throw new UnsupportedOperationException("Not supported yet."); } } i have to find the error SEVERE: error during the dispatch of event: FireEvent [org.openymsg.network.event.SessionListEvent to:null from:null message:null timestamp:0 status:0 list type:Friends size:2 LIST] java.lang.UnsupportedOperationException: Not supported yet. at yahoomessangerbot.MySessionListener.dispatch(MySessionListener.java:131) at org.openymsg.network.EventDispatcher.runEventNOW(EventDispatcher.java:133) at org.openymsg.network.EventDispatcher.run(EventDispatcher.java:114)

    Read the article

  • Using getters/setters in Java

    - by Crystal
    I'm having some trouble with the idea of accessing variables from other classes. I had a post here: http://stackoverflow.com/questions/3011642/having-access-to-a-private-variable-from-other-classes-in-java where I got some useful information, and thought an example would be better show it, and ask a separate question as well. I have a form that I can input data to, and it has a List variable. I didn't make it static at first, but I thought if I needed to get the total size from another class, then I wouldn't create an instance of that class in order to use the function to getTotalContacts. I basically want to update my status bar with the total number of contacts that are in my list. One of the members said in the above post to use the original Foo member to get the contacts, but I'm not sure how that works in this case. Any thoughts would be appreciated. Thanks. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class AddressBook { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { AddressBookFrame frame = new AddressBookFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenuItem openItem = new JMenuItem("Open"); JMenuItem saveItem = new JMenuItem("Save"); JMenuItem saveAsItem = new JMenuItem("Save As"); JMenuItem printItem = new JMenuItem("Print"); JMenuItem exitItem = new JMenuItem("Exit"); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(saveAsItem); fileMenu.add(printItem); fileMenu.add(exitItem); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); JMenuItem newItem = new JMenuItem("New"); JMenuItem editItem = new JMenuItem("Edit"); JMenuItem deleteItem = new JMenuItem("Delete"); JMenuItem findItem = new JMenuItem("Find"); JMenuItem firstItem = new JMenuItem("First"); JMenuItem previousItem = new JMenuItem("Previous"); JMenuItem nextItem = new JMenuItem("Next"); JMenuItem lastItem = new JMenuItem("Last"); editMenu.add(newItem); editMenu.add(editItem); editMenu.add(deleteItem); editMenu.add(findItem); editMenu.add(firstItem); editMenu.add(previousItem); editMenu.add(nextItem); editMenu.add(lastItem); menuBar.add(editMenu); JMenu helpMenu = new JMenu("Help"); JMenuItem documentationItem = new JMenuItem("Documentation"); JMenuItem aboutItem = new JMenuItem("About"); helpMenu.add(documentationItem); helpMenu.add(aboutItem); menuBar.add(helpMenu); frame.setVisible(true); } }); } } class AddressBookFrame extends JFrame { public AddressBookFrame() { setLayout(new BorderLayout()); setTitle("Address Book"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); AddressBookToolBar toolBar = new AddressBookToolBar(); add(toolBar, BorderLayout.NORTH); AddressBookStatusBar aStatusBar = new AddressBookStatusBar(); add(aStatusBar, BorderLayout.SOUTH); AddressBookForm form = new AddressBookForm(); add(form, BorderLayout.CENTER); } public static final int DEFAULT_WIDTH = 500; public static final int DEFAULT_HEIGHT = 500; } /* Create toolbar buttons and add buttons to toolbar */ class AddressBookToolBar extends JPanel { public AddressBookToolBar() { setLayout(new FlowLayout(FlowLayout.LEFT)); JToolBar bar = new JToolBar(); JButton newButton = new JButton("New"); JButton editButton = new JButton("Edit"); JButton deleteButton = new JButton("Delete"); JButton findButton = new JButton("Find"); JButton firstButton = new JButton("First"); JButton previousButton = new JButton("Previous"); JButton nextButton = new JButton("Next"); JButton lastButton = new JButton("Last"); bar.add(newButton); bar.add(editButton); bar.add(deleteButton); bar.add(findButton); bar.add(firstButton); bar.add(previousButton); bar.add(nextButton); bar.add(lastButton); add(bar); } } /* Creates the status bar string */ class AddressBookStatusBar extends JPanel { public AddressBookStatusBar() { setLayout(new FlowLayout(FlowLayout.LEFT)); this.statusBarString = new JLabel("Total: " + AddressBookForm.getTotalContacts()); add(this.statusBarString); } public void updateLabel() { contactsLabel.setText(AddressBookForm.getTotalContacts().toString()); } private JLabel statusBarString; private JLabel contactsLabel; } class AddressBookForm extends JPanel { public AddressBookForm() { // create form panel this.setLayout(new GridLayout(2, 1)); JPanel formPanel = new JPanel(); formPanel.setLayout(new GridLayout(4, 2)); firstName = new JTextField(20); lastName = new JTextField(20); telephone = new JTextField(20); email = new JTextField(20); JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT); formPanel.add(firstNameLabel); formPanel.add(firstName); JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT); formPanel.add(lastNameLabel); formPanel.add(lastName); JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT); formPanel.add(telephoneLabel); formPanel.add(telephone); JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT); formPanel.add(emailLabel); formPanel.add(email); add(formPanel); // create button panel JPanel buttonPanel = new JPanel(); JButton insertButton = new JButton("Insert"); JButton displayButton = new JButton("Display"); ActionListener insertAction = new AddressBookListener(); ActionListener displayAction = new AddressBookListener(); insertButton.addActionListener(insertAction); displayButton.addActionListener(displayAction); buttonPanel.add(insertButton); buttonPanel.add(displayButton); add(buttonPanel); } public static int getTotalContacts() { return addressList.size(); } //void addContact(Person contact); private JTextField firstName; private JTextField lastName; private JTextField telephone; private JTextField email; private JLabel contacts; private static List<Person> addressList = new ArrayList<Person>(); private class AddressBookListener implements ActionListener { public void actionPerformed(ActionEvent e) { String buttonPressed = e.getActionCommand(); System.out.println(buttonPressed); if (buttonPressed == "Insert") { Person aPerson = new Person(firstName.getText(), lastName.getText(), telephone.getText(), email.getText()); addressList.add(aPerson); } else { for (Person p : addressList) { System.out.println(p); } } } } } My other question is why do I get the error, "int cannot be dereferenced contactsLabel.setText(AddressbookForm.getTotalContacts().toString()); Thanks!

    Read the article

  • Passing ActionListeners in Java, pack()

    - by Crystal
    Two questions. First question is I'm trying to create a simple form that when you press a button, it adds a Person object to the ArrayList. However, since I am not used to GUIs, I tried creating one and am first just trying to get the user input from the JTextField, create an ActionListener object of the appropriate type, so once that works, then I can pass in all the JTextField inputs to create my Person object. Unfortunately, I am not getting any data when I type in something to the firstName JTextField and was wondering if someone could look at my code below. import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.List; import java.util.ArrayList; public class AddressBook { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { AddressBookFrame frame = new AddressBookFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); JMenuItem openItem = new JMenuItem("Open"); JMenuItem saveItem = new JMenuItem("Save"); JMenuItem saveAsItem = new JMenuItem("Save As"); JMenuItem printItem = new JMenuItem("Print"); JMenuItem exitItem = new JMenuItem("Exit"); fileMenu.add(openItem); fileMenu.add(saveItem); fileMenu.add(saveAsItem); fileMenu.add(printItem); fileMenu.add(exitItem); menuBar.add(fileMenu); JMenu editMenu = new JMenu("Edit"); JMenuItem newItem = new JMenuItem("New"); JMenuItem editItem = new JMenuItem("Edit"); JMenuItem deleteItem = new JMenuItem("Delete"); JMenuItem findItem = new JMenuItem("Find"); JMenuItem firstItem = new JMenuItem("First"); JMenuItem previousItem = new JMenuItem("Previous"); JMenuItem nextItem = new JMenuItem("Next"); JMenuItem lastItem = new JMenuItem("Last"); editMenu.add(newItem); editMenu.add(editItem); editMenu.add(deleteItem); editMenu.add(findItem); editMenu.add(firstItem); editMenu.add(previousItem); editMenu.add(nextItem); editMenu.add(lastItem); menuBar.add(editMenu); JMenu helpMenu = new JMenu("Help"); JMenuItem documentationItem = new JMenuItem("Documentation"); JMenuItem aboutItem = new JMenuItem("About"); helpMenu.add(documentationItem); helpMenu.add(aboutItem); menuBar.add(helpMenu); frame.setVisible(true); } }); } } class AddressBookFrame extends JFrame { public AddressBookFrame() { setLayout(new BorderLayout()); setTitle("Address Book"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); AddressBookToolBar toolBar = new AddressBookToolBar(); add(toolBar, BorderLayout.NORTH); AddressBookStatusBar aStatusBar = new AddressBookStatusBar("5"); add(aStatusBar, BorderLayout.SOUTH); AddressBookForm form = new AddressBookForm(); add(form, BorderLayout.CENTER); } public static final int DEFAULT_WIDTH = 500; public static final int DEFAULT_HEIGHT = 500; } /* Create toolbar buttons and add buttons to toolbar */ class AddressBookToolBar extends JPanel { public AddressBookToolBar() { setLayout(new FlowLayout(FlowLayout.LEFT)); JToolBar bar = new JToolBar(); JButton newButton = new JButton("New"); JButton editButton = new JButton("Edit"); JButton deleteButton = new JButton("Delete"); JButton findButton = new JButton("Find"); JButton firstButton = new JButton("First"); JButton previousButton = new JButton("Previous"); JButton nextButton = new JButton("Next"); JButton lastButton = new JButton("Last"); bar.add(newButton); bar.add(editButton); bar.add(deleteButton); bar.add(findButton); bar.add(firstButton); bar.add(previousButton); bar.add(nextButton); bar.add(lastButton); add(bar); } } /* Creates the status bar string */ class AddressBookStatusBar extends JPanel { public AddressBookStatusBar(String statusBarString) { setLayout(new FlowLayout(FlowLayout.LEFT)); this.statusBarString = new JLabel("Total number of people: " + statusBarString); add(this.statusBarString); } private JLabel statusBarString; private int totalContacts; } class AddressBookForm extends JPanel { public AddressBookForm() { this.setLayout(new GridLayout(2, 1)); JPanel formPanel = new JPanel(); formPanel.setLayout(new GridLayout(4, 2)); JTextField firstName = new JTextField(20); JTextField lastName = new JTextField(20); JTextField telephone = new JTextField(20); JTextField email = new JTextField(20); JLabel firstNameLabel = new JLabel("First Name: ", JLabel.LEFT); formPanel.add(firstNameLabel); formPanel.add(firstName); JLabel lastNameLabel = new JLabel("Last Name: ", JLabel.LEFT); formPanel.add(lastNameLabel); formPanel.add(lastName); JLabel telephoneLabel = new JLabel("Telephone: ", JLabel.LEFT); formPanel.add(telephoneLabel); formPanel.add(telephone); JLabel emailLabel = new JLabel("Email: ", JLabel.LEFT); formPanel.add(emailLabel); formPanel.add(email); add(formPanel); JPanel buttonPanel = new JPanel(); JButton insertButton = new JButton("Insert"); JButton displayButton = new JButton("Display"); // create button actions AddressBookManager insertAction = new AddressBookManager(firstName.getText()); insertButton.addActionListener(insertAction); buttonPanel.add(insertButton); buttonPanel.add(displayButton); add(buttonPanel); } private List<Person> addressList = new ArrayList<Person>(); private class AddressBookManager implements ActionListener { public AddressBookManager(String text) { // addressList.add( setName(text); System.out.println("Test" + text); } public void actionPerformed(ActionEvent e) { System.out.println("Hello" + name); } public void setName(String name) { this.name = name; } private String name; } } Second question is, how do I make my form not take up the whole center space. I don't like the stretch look and was hoping the JTextFields could be just one line long, not a big box. Same thing with the buttons. Any thoughts? Thanks.

    Read the article

1 2  | Next Page >