Making a JButton react like a JMenu

Hi everybody,
I'm really not sure if this is possible; if it isn't, feel free to tell me. Anyway, I have a JMenuBar with multiple JMenus, interspersed with JButtons. The JButtons replace JMenus with no JMenuItems, so you can just click on them and have something come up. I've figured out how to make a JButton look like a JMenu, but the problem is that when scrolling over the JButton, it doesn't get the selected look of a JMenu (with the highlighting). I know this would be done by using mouseEntered and mouseExited in a MouseListener, so I don't need help there, but I'm getting tripped up on how to change the look of the button properly. I'd like it to change to the default of whatever system it's running on (Windows, Mac, Linux), so I can't use UIManager, I don't think.
I don't need help making a program work (because my buttons are already fine in the JMenuBar, even though they don't do what I want), just some advice, so if anyone would be willing, I'd appreciate it.
Thanks,
Jezzica85

Here's my test code:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class MenuTest {
     public MenuTest() {
          try {
               JFrame frame = new JFrame();
               frame.setSize( 200, 200 );
               frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
               JMenuBar bar = new JMenuBar();
               JMenu menu1 = new JMenu( "one" );
               JMenuItem item = new JMenuItem( "Blah" );
               JMenuItem item2 = new JMenuItem( "Blah2" );
               menu1.add( item );
               menu1.add( item2 );
               bar.add( menu1 );
               JMenuItem button = new JMenuItem( "button" );
               bar.add( button );
               JMenu menu2 = new JMenu( "two" );
               JMenuItem itemA = new JMenuItem( "Blah" );
               JMenuItem item2A = new JMenuItem( "Blah2" );
               menu2.add( itemA );
               menu2.add( item2A );
               bar.add( menu2 );
               frame.add( bar, BorderLayout.NORTH );
               frame.setVisible( true );
          } catch( Exception e ) {
               e.printStackTrace();
               System.exit( -1 );
     public static void main(String[] args) { new MenuTest(); }
}What happens to me in this is that the two JMenus are sized fine, but the JMenuItem extends as far as it can, so the second JMenu is against the far side of the JMenuBar.
Thanks,
Jezzica85

Similar Messages

  • My mac pro keeps making a chirping cricket-like sound

    My Mac Pro keeps making a chirping cricket-like sound, more and more frequently. Has anyone else had this problem? Is this telling me one of my HD is going bad?

    K_Bar wrote:
    ...I had them so close together that it sounded like the MacPro. Once I pulled them apart however, it was clear where the sound was coming from. Thank you all for the help!
    Been there, done that. And the instructions, once I found them, seemed to list every possible communication except the chirps; I had to call tech support, which was actually a pleasant experience after dealing with Verizon.
    The frequency of chirping as well as how long each chirp sequence lasts seems to be related to the line voltage. It's as if the UPS begins to worry as the line voltage goes down that it might have to actually do something with its battery.

  • Tm2t. When using High GPU and in secondary landscape, pen and touch react like in landscape

    So I just my tm2t and found this odd problem. When Im using the tablet with the High performance GPU and go to secondary landscape the pen and touch react like the screen is in normal landscape. I switch to Low power GPU and the touch and pen is OK. Im so confused and angry!!! 
    Denis

    We uninstalled all the ATI software and disabled the driver/card last year because no matter what we did, this problem could not be resolved.  We are mostly mobile and do not need high end graphics.  The ATI card gets totally in the way of doing anything mobile and wanting us to exit our apps to switch on/off the GPU - are they crazy?

  • My 5 is making a feed back like noise when I make calls and the person I'm calling can hear the noise.

    My 5 is making a feed back like noise when I make calls and the person I'm calling can hear the noise.

    will someone from HP revert? need urgent solution please!!

  • Need advice on making a JButton

    hey guys, ive created a couple of gui's before using JButtons and using actionlistener to see which button was pressed based on the name of the button. this time im making buttons using a image and the button contains properties were as my previous buttons were just to sort, very easy compared to this time. basically my JButton is going to have 2 or more properties such as name, location etc.. . so if the user picked image 1, i can call getName or get Location based on the button they pressed and print it out on my text area. from what i was told i can make a class to extend JButton and have my Place object in that class. is this the easiest way to have 5 or more JButtons each with the same properties but different info, or is there an easier way?
    btw with having Strings as a button i can do
    command.equals("Sort") to have it sort
    but since its an image does it work the same way if i put in the image name command.equals("image.gif")?
    thanks in advance!

    Ok, if i got your problem right i think i've got the solution for you. What you are trying to do is to identify from which button the action came from, right? And you used to use strings to identify them, but now you've only got a picture on some.
    You need to think a little bit different.
    Something like this:
    JButton b1 = new JButton("Hi!");
    JButton b2 = new JButton("How are you?");
    JButton b3 = new JButton(new ImageIcon("image.gif"));
    public void actionPerformed(ActionEvent e) {
    if(e.getSource() == b1) {
            //Do something
    if (e.getSource() == b2) {
      //Do something else
    if (e.getSource() == b3) {
      //Do a third thing
    }As you can see, i only used the JButton variables (b1,b2 & b3) to identify the buttons. In this way, you never need to worry about the content of the different buttons! This is much better, just think what else to do if you have two buttons with the same text on them!

  • Making a picture look like a canvas print

    Hi
    I run an online canvas print company and sometimes for new images we have available I want to create a photoshopped example of how it would look as a canvas print, rather than getting it actually printed and photographing it. I can do this manually but it takes ages so I wondered if there is an easier way, perhaps an action or some kind of plugin that can do it a lot quicker?
    This page shows some examples of what I have done in photoshop http://www.fotoviva.co.uk/photos-on-canvas.asp
    The best one is the Gallery Wrapped Canvas at the bottom, which shows the image wrapping around the frame - it looks quite real. Ideally it would be useful to be able to create them with and without the wrap to show customers the options they can have.
    I tried to create a Photoshop action but the trouble is not all of the images we sell are the same size ratio ie. some are rectangular, some square and some panoramic in shape.
    So is there an easy way to create these in Photoshop? I guess it's like making a 2D image into a 3D box in effect.
    Thanks

    The major 3D packages are overkill for this (in expense, and time to setup/render).
    There is alot of software for this on the pc
    This one actually has a mac version
    http://www.boxshot3d.com/
    In your search I would look for one that lets you wrap 1 bitmap image against the front and 4 sides of an extruded rectangle, to save you the time of making separate images for side panels(and you likely  have slightly rounded edges on your canvas). I would try the boxshot3d as they appear to have a free trial.

  • Making an image look like its on a canvas?

    Hi guys,
    I am using Photoshop CS5, I generally find it very good and love the features it gives me, i however am having trouble trying to achieve something but i dont know if it can be done,
    I am going to be selling Canvas Prints and i dont know if theres anyway i can make a jpg image look like its on a canvas or even turn the image to a canvas design, this includes making it look 3d. The reason for doing this is it will save me having to manufacture every single image i have onto a canvas for a photo.
    I hope somebody can help me
    Regards
    Lee

    'Transform' can skew rectangular shapes to have perspective. Here's a loosely related tutorial or two...
    http://www.tutorial9.net/tutorials/photoshop-tutorials/designing-a-software-box/
    http://psd.tutsplus.com/tutorials/tools-tips/create-a-3d-software-box-in-photoshop-using-a ctions/

  • Make a JButton look like it is pressed

    I am setting up a JButton so that it operates like normal when you left click but if you right click it should act like it is being pressed until the next time you right click it.
    My problem is that when it is right click activated I want it to paint as if it were armed. When I setArmed and setPressed to true, it will look good so long as the mouse is over the button but not when the mouse leaves the area of the button.
    I've made a little hack that changes the background color to the color that is used when armed and it looks OK, but the border isn't drawn right. I am looking for a way to make the button look exactly like it does when held normally. Thanks in advance.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PolledButton extends JButton implements MouseListener
       protected boolean state;
       protected boolean rightClicked;
       protected Color enabledColor = new Color(153, 153, 153);
       public PolledButton()
          super();
          state = false;
          rightClicked = false;
          addMouseListener(this);
       public boolean getState()
          if(rightClicked) return true;
          boolean temp = state;
          state = false;
          return temp;
       public void mouseClicked(MouseEvent e)
          if(e.getButton() != MouseEvent.BUTTON3)
             System.out.println("Not a right click!");
             if(!rightClicked) state = true;
          else
             System.out.println("Right click!");
             if(rightClicked)
                System.out.println("Exiting hold");
                rightClicked = false;
                state = false;
                super.model.setArmed(false);
                super.model.setPressed(false);
                setBackground(Color.lightGray);
             else
                System.out.println("Entering hold");
                rightClicked = true;
                state = true;
                super.model.setArmed(true);
                super.model.setPressed(true);
                setBackground(enabledColor);
       public void mouseEntered(MouseEvent e)
       public void mouseExited(MouseEvent e)
       public void mousePressed(MouseEvent e)
       public void mouseReleased(MouseEvent e)
    }

    I believe using color is not the right approach
    try this out
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PolledButton extends JButton implements MouseListener
    protected boolean state;
    protected boolean rightClicked;
    public PolledButton()
         super();
         state = false;
         rightClicked = false;
         addMouseListener(this);
    public boolean getState()
         if(rightClicked) return true;
         boolean temp = state;
         state = false;
         return temp;
    public void mouseClicked(MouseEvent e)
         if(e.getButton() != MouseEvent.BUTTON3)
              System.out.println("Not a right click!");
              if(!rightClicked) state = true;
         else
              System.out.println("Right click!");
              if(rightClicked)
                   System.out.println("Exiting hold");
                   rightClicked = false;
                   state = false;
                   super.model.setArmed(false);
                   super.model.setPressed(false);
              else
                   System.out.println("Entering hold");
                   rightClicked = true;
                   state = true;
                   super.model.setArmed(true);
                   super.model.setPressed(true);
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e)
         if(rightClicked)
              super.model.setArmed(true);
              super.model.setPressed(true);
    public void mousePressed(MouseEvent e)
    public void mouseReleased(MouseEvent e)

  • JButton used like a JTextArea

    I have a code snippet which allows the user to click on a JTable cell, and edit the text using a pop-up window.
    I want to add a context menu to this, but it doesn't seem to work with a JButton. Here is the code:
         public TablePopupEditor(String strHeading)
              super(new JTextField());
              setClickCountToStart(1);
              //  Use a JButton as the editor component
              editorComponent = new JButton();
              editorComponent.setBackground(Color.white);
              editorComponent.setBorderPainted(false);
              editorComponent.setContentAreaFilled( false );
              // editorComponent.addActionListener( this );
              //  Set up the dialog where we do the actual editing
              popup = new PopupDialog(strHeading);
              createPopupMenu();
         }I was very surprised to see this code uses a JButton (!?) like a JTextArea. It has multiple rows, you type in text, etc. Why a JButton?
    Anyhow, I need to either use something else, or I need to figure out how to get a MouseListener on a JButton. The latter doesn't work right now.
    The context menu code works fine in a demo program -- but it is using a JTextArea:
        public Container createContentPane() {
            //Create the content-pane-to-be.
            JPanel contentPane = new JPanel(new BorderLayout());
            contentPane.setOpaque(true);
            //Create a scrolled text area.
            output = new JTextArea(5, 30);
            output.setEditable(true);
            scrollPane = new JScrollPane(output);
            //Add the text area to the content pane.
            contentPane.add(scrollPane, BorderLayout.CENTER);
            return contentPane;
        }Any help would be much appreciated.
    Thank you,
    Matthew

    Here is an SSCCE which might be of help:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.TableModelListener;
    import javax.swing.text.DefaultEditorKit;
    import java.util.*;
    import java.io.*;
    import java.util.List;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    public class Demo extends JPanel
                   implements KeyListener, ActionListener, ItemListener {
         public final int NUM_RECS = 4;
         MyTableModel mainTable;
         TableSorter sorter;
         JTable table;
         JPanel mainPanel, top;
         static JFrame frame;
        private MouseListener mouseListener;
        public Demo() {
              top = new JPanel();
            sorter = new TableSorter(new MyTableModel());
            table = new JTable(sorter);
            sorter.setTableHeader(table.getTableHeader());
              // We want a horizontal scroller, not auto-resize as we shrink/grow the table
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
              scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            //Add the scroll pane to this panel.
            top.add(scrollPane);
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            //Add all panels to the main panel.
            add(top);
             vLoadTableData();
        public void actionPerformed(ActionEvent e) {
             String strCommand = e.getActionCommand();
        public void itemStateChanged(ItemEvent e) {
            JMenuItem source = (JMenuItem)(e.getSource());
        public void keyTyped(KeyEvent e) {}
        public void keyPressed(KeyEvent e) {}
        public void keyReleased(KeyEvent e) {}
        protected void displayInfo(KeyEvent e, String s){}
         public void vLoadTableData() {
              TableColumn column = null;
             column = table.getColumnModel().getColumn(0);
                column.setPreferredWidth(50);
             column = table.getColumnModel().getColumn(1);
                column.setPreferredWidth(40);
             column = table.getColumnModel().getColumn(2);
              column.setCellEditor(new TablePopupEditor("Edit Description text"));
                column.setPreferredWidth(350);
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"Publish", "ID", "Description"};
              private Object[][] data;
              MyTableModel() {
                   data = new Object[NUM_RECS][3];
                   // Sample data               
                   data[0][0] = false;
                   data[0][1] = (int)101;
                   data[0][2] = "This is a book that is being sold at the present time. Buy yours today!";
                   data[1][0] = true;
                   data[1][1] = (int)102;
                   data[1][2] = "Gripping, thrilling, exciting. Tells how to grow tomatoes in your own backyard!";
                   data[2][0] = true;
                   data[2][1] = (int)103;
                   data[2][2] = "A story about a dog that attacks Kansas City.";
                   data[3][0] = false;
                   data[3][1] = (int)104;
                   data[3][2] = "Learn how to write an SSCCE that your Java forum will love.";
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                 return true;
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
        private static void createAndShowGUI() {
              JFrame.setDefaultLookAndFeelDecorated(false);
            frame = new JFrame("Test of Product database");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            Demo newContentPane = new Demo();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    class TableSorter extends AbstractTableModel {
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter() {
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel) {
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState() {
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel() {
            return tableModel;
        public void setTableModel(TableModel tableModel) {
            if (this.tableModel != null) {
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null) {
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader() {
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader) {
            if (this.tableHeader != null) {
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer) {
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null) {
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer(
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
        public boolean isSorting() {
            return sortingColumns.size() != 0;
        private Directive getDirective(int column) {
            for (int i = 0; i < sortingColumns.size(); i++) {
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column) {
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column) {
            return getDirective(column).direction;
        private void sortingStatusChanged() {
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null) {
                tableHeader.repaint();
        public void setSortingStatus(int column, int status) {
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE) {
                sortingColumns.remove(directive);
            if (status != NOT_SORTED) {
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size) {
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE) {
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting() {
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator) {
            if (comparator == null) {
                columnComparators.remove(type);
            } else {
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column) {
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null) {
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType)) {
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel() {
            if (viewToModel == null) {
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++) {
                    viewToModel[row] = new Row(row);
                if (isSorting()) {
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex) {
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView() {
            if (modelToView == null) {
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++) {
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount() {
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount() {
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column) {
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column) {
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column) {
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column) {
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column) {
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable {
            private int modelIndex;
            public Row(int index) {
                this.modelIndex = index;
            public int compareTo(Object o) {
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null) {
                        comparison = 0;
                    } else if (o1 == null) {
                        comparison = -1;
                    } else if (o2 == null) {
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0) {
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener {
            public void tableChanged(TableModelEvent e) {
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting()) {
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null) {
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1) {
                    int status = getSortingStatus(column);
                    if (!e.isControlDown()) {
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon {
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority) {
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y) {
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth() {
                return size;
            public int getIconHeight() {
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer {
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column) {
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive {
            private int column;
            private int direction;
            public Directive(int column, int direction) {
                this.column = column;
                this.direction = direction;
    class TablePopupEditor extends DefaultCellEditor     
              implements TableCellEditor, ActionListener {
         private PopupDialog popup;
         private String currentText = "";
         private JButton editorComponent;
        String newline = "\n";
        JTextArea output;
        JScrollPane scrollPane;
         JPanel contentPane;
         public TablePopupEditor(String strHeading)
              super(new JTextField());
              setClickCountToStart(1);
              //  Use a JButton as the editor component
              editorComponent = new JButton();
              editorComponent.setBackground(Color.white);
              editorComponent.setBorderPainted(false);
              editorComponent.setContentAreaFilled( false );
              // editorComponent.addActionListener( this );
              //  Set up the dialog where we do the actual editing
              popup = new PopupDialog(strHeading);
              createPopupMenu();
        public void createPopupMenu() {
            JMenuItem menuItem;
            //Create the popup menu.
            JPopupMenu contextMenu = new JPopupMenu();
            menuItem = new JMenuItem(new DefaultEditorKit.CopyAction());
            menuItem.setText("Copy");
              menuItem.setMnemonic(KeyEvent.VK_C);
            menuItem.addActionListener(this);
            contextMenu.add(menuItem);
            menuItem = new JMenuItem(new DefaultEditorKit.CutAction());
            menuItem.setText("Cut");
              menuItem.setMnemonic(KeyEvent.VK_T);
            menuItem.addActionListener(this);
            contextMenu.add(menuItem);
            menuItem = new JMenuItem(new DefaultEditorKit.PasteAction());
            menuItem.setText("Paste");
              menuItem.setMnemonic(KeyEvent.VK_P);
            menuItem.addActionListener(this);
            contextMenu.add(menuItem);
            //Add listener to the text area so the popup menu can come up.
            MouseListener popupListener = new PopupListener(contextMenu);
            editorComponent.addMouseListener(popupListener);
            popup.addMouseListener(popupListener);
         public Object getCellEditorValue()
              return currentText;
         public Component getTableCellEditorComponent(
              JTable table, Object value, boolean isSelected, int row, int column)
              SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        popup.setText( currentText );
                        popup.setLocationRelativeTo( editorComponent );
                        popup.show();
                        fireEditingStopped();
              currentText = value.toString();
                 editorComponent.setText( currentText );
              return editorComponent;
         *   When the editor button is clicked display the editing dialog
         public void actionPerformed(ActionEvent e)
              popup.setText( currentText );
              popup.setLocationRelativeTo( editorComponent );
              popup.show();
              //  Since dialog is modal editing will only stop when the
              //  dialog is closed
              fireEditingStopped();
        // Returns just the class name -- no package info.
        protected String getClassName(Object o) {
            String classString = o.getClass().getName();
            int dotIndex = classString.lastIndexOf(".");
            return classString.substring(dotIndex+1);
         *   Simple dialog containing the actual editing component
         class PopupDialog extends JDialog implements ActionListener
              private JTextArea textArea;
              public PopupDialog(String strHeading)
                   super((Frame)null, strHeading, true);
                   setDefaultLookAndFeelDecorated(false);
                   textArea = new JTextArea(7, 30);
                   textArea.setLineWrap( true );
                   textArea.setWrapStyleWord( true );
                   KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
                   textArea.getInputMap().put(keyStroke, "none");
                   JScrollPane scrollPane = new JScrollPane( textArea );
                   getContentPane().add( scrollPane );
                   JButton cancel = new JButton("Cancel");
                   cancel.addActionListener( this );
                   JButton ok = new JButton("Ok");
                   ok.setPreferredSize( cancel.getPreferredSize() );
                   ok.addActionListener( this );
                   JPanel buttons = new JPanel();
                   buttons.add( ok );
                   buttons.add( cancel );
                   getContentPane().add(buttons, BorderLayout.SOUTH);
                   pack();
                   getRootPane().setDefaultButton( ok );
              public void setText(String text) {
                   textArea.setText( text );
              *   Save the changed text before hiding the popup
              public void actionPerformed(ActionEvent e)
                   if ("Ok".equals( e.getActionCommand() ) )
                        currentText = textArea.getText();
                   textArea.requestFocusInWindow();
                   setVisible( false );
        class PopupListener extends MouseAdapter {
            JPopupMenu popup;
            PopupListener(JPopupMenu popupMenu) {
                popup = popupMenu;
            public void mousePressed(MouseEvent e) {
                maybeShowPopup(e);
            public void mouseReleased(MouseEvent e) {
                maybeShowPopup(e);
            private void maybeShowPopup(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    popup.show(e.getComponent(),
                               e.getX(), e.getY());
        }

  • I want to put Newstand in my REFFERENCE folder!! WHY HAS APPLE STARTED making choices for me like Microsoft do??, I want to put Newstand in my REFFERENCE folder!! WHY HAS APPLE STARTED making choices for me like Microsoft do??

    I want to put Newsstand in my "Refference" folder!! Why has Apple started making decisions for me? Thats what Microsoft do!! Please dont start doing things like that - PLEASE HEAR MY CRY!!

    You cannot put folders inside folders. Newstand is technically a folder. Don't panic.

  • Windows 8 (Stream 7) reacts like power button is being held down

    So I just got home from work and sat down to browse some web sites and eat. When I was done I hit the sleep button but shortly after the screen went out, windows came back with the slide down to shut down slider.
    It just sat there waiting for input, I would slide it up (no) and then hit the sleep button again only for it to wake up again asking me if I want to shut down. At first I thought the power button broke, I even shut down the tablet and started it again and it still did it. I would put it to sleep and it would wake up asking me to slide the lock screen to shut down. 
    Now the thing is... if the power button really WAS stuck.. 3 things would happen;
    #1 as per Bios software these days, holding the power button for more then 10 seconds is a universal "power down" command. Especialy on devices like these where the battery can't be disconnected. This power down command is almost allways part of the hardware so that it works incase of software failure. 
    #2 pressing the stuck power button when the tablet was on wouldn't put it to sleep. 
    #3 the tablet would be powering back on when powered off. 
    Now the thing is, this issue is NOT HAPPENING NOW! As if related some how, during the 15 or so minutes this happened, when I booted the tablet up holding it in portrait orientation the HP logo was correct but the windows lock and password screen were stuck in landscape mode. If I rotated the tablet to landscape and back at the lock screen it would fix itself, but during this issue it seemed like the orientation of the tablet was not being acknowledged correctly during the boot sequence and the lock screen would be oriented wrong. I some how fixed it by telling the tablet to reboot from the logon screen at which point it got stuck on the shutting down screen and I had to do a hard power down. After booting up once more all was well. 
    So.. as much as it seemed like a button failure, it really looks like there was a software glitch somewhere, either the bios or windows. I was unable to find anyone having a simular issue with windows tablets. 

    Didn't find a cause, but found the solution. It has nothing to do with diagnostics or anything, but rather doing a hard reboot. You see by default the tablet is configured to fast boot. What this means is when we shut down, a small hibernation file is written for the drivers and kernal (but not the user logon and data). So we never actually shut down, we log out and then hybernate. 
    So when the glitch pops up, even if we shut down, we arn't shutting down. We don't truly reset windows unless we RESTART, or do a hard shut down by holding the power switch which doesn't allow the computer to hybrnate. Both instances force windows to load from scratch. 

  • Making the program react to input from keyboard

    Hello,-
    I am trying to write a program that reacts to user input: when one hits the "y" key on keyboard the program should print out a statement or perform some other action. The following piece of code compiles, but ignores the if-part. Does anyone have any tips?
    Thanks, Vahagn
    import java.io.*;
    public class InputPrinter {
        public static void main(String[] arg) throws IOException {
         InputStreamReader isr = new InputStreamReader(System.in);
         BufferedReader br = new BufferedReader(isr);
         String line = br.readLine();
         //works perfectly
         //doesn't work:
         if (line == "y")
             System.out.println("Hello World!");
    }

    Thanks, that was exactly what I needed:
    import java.io.*;
    public class InputPrinter {
        public static void main(String[] arg) throws IOException {
         InputStreamReader isr = new InputStreamReader(System.in);
         BufferedReader br = new BufferedReader(isr);
         String line = br.readLine();
         //works perfectly
         //doesn't work: if (line == "y")
         if (line.equals("y"))
             System.out.println("Hello World!");
         else
             System.out.println(4+4);
    }In the long run I AM interested in a program that processes input as it happens, without printing the input itself and without hitting the ENTER key. It was nice though to have sorted the above problem out.
    Regards to all, Vahagn

  • Making disabled links appear like textview

    Hi there,
    I have to display a combination of links and textviews in the same column within a table.  Because I cannot intermix cell editor types in the same column, I have to disable the links in order to achieve this.  The issue then is, my disabled links are greyed out, when in fact, I want them to be a solid black (appearing like textviews)  Does anyone have any hints as how I can do this?
    Thanks,
    MP

    If you don't mind that the link remains clickable, you might set its "type" property value to WDLinkType.RESULT. I'm not sure if a disabled link of this type is also greyed out, you might check this out.
    Armin
    Message was edited by: Armin Reichert

  • Java 3D: making a sphere rotate like a planet.

    Hey guys, could anyone possible show me to make a spher rotate on its axis, like a plant? I'm fairly new to java 3d.
         Sphere sp = new Sphere(.4f, Sphere.GENERATE_TEXTURE_COORDS, earthApp);
         t.set(1.0, new Vector3d(0f, 0f, 0f));
         TransformGroup tg1 = new TransformGroup(t);
         tg1.addChild(sp);
         mainTG.addChild(tg1);
    That basically puts a sphere in the middle of the screen, earthApp references a file called earth.JPG which colours the sphere to make it look like the earth.
    But i need help rotating it guys!

    I'm pretty new to Java3D as well, but:
    If you look under %JAVA_HOME%\demo\java3d\index.html there are several very clear examples (with source). The ConicWorld example looks similar to what you want to do. Check out the createObject method in %JAVA_HOME%\demo\java3d\ConicWorld\ConicWorld.java. It's slightly more complicated than it has to be because they're using arrays of objects, but the general spin idea is there.

  • ITunes making the playlist look like garbage

    When having iTunes minimized for a little while the playlist looks like crap when it comes back up.
    I have an image of it here; http://zappa.halden.net/~kjes/itunes.PNG
    I wouldnt be surprised if this has been answered already, but I couldnt find anything with a quick sweep of the forums.
    Dell X1   Windows XP Pro  

    Some earlier discussions:
    http://discussions.apple.com/click.jspa?searchID=-1&messageID=633958
    http://discussions.apple.com/message.jspa?messageID=1065443#1065443
    and an example with Shake:
    all kinds of fun to be had...
    Patrick

Maybe you are looking for