Java Swing OSX Window Menu Icon Alignment - java

Java Swing seems to place the 'Menu Text' after the icon (if present) on MenuItems. See example below.
It does NOT look very nice.
Is there a way around this?
On OSX the icon fits in the left margin and the text aligns with all other MenuItems.

Do you mean something like this :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextPaneExample
{
private Icon info = UIManager.getIcon("OptionPane.informationIcon");
private Icon error = UIManager.getIcon("OptionPane.errorIcon");
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JTextPane Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane tpane = new JTextPane();
tpane.setContentType("text/html");
JScrollPane scroller = new JScrollPane();
scroller.setViewportView(tpane);
try
{
java.net.URL url = new java.net.URL("http://maps.google.es/");
//tpane.setPage(url);
}
catch (Exception e)
{
e.printStackTrace();
}
frame.setJMenuBar(createMenuBar());
frame.getContentPane().add(scroller);
frame.setSize(300, 300);
frame.setVisible(true);
}
private JMenuBar createMenuBar()
{
JMenuBar menuBar = new JMenuBar();
JMenu windowMenu = new JMenu("Window");
JMenuItem minimizeItem = new JMenuItem("Minimize");
minimizeItem.setMargin(new java.awt.Insets(0, 10, 0, 0));
minimizeItem.setIcon(info);
minimizeItem.setIconTextGap(1);
minimizeItem.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
JMenuItem zoomItem = new JMenuItem("Zoom");
zoomItem.setMargin(new java.awt.Insets(0, 10, 0, 0));
zoomItem.setIconTextGap(1);
zoomItem.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem("Check Me", null, true);
cbmi.setMargin(new java.awt.Insets(5, 25, 5, 5));
cbmi.setIconTextGap(17);
cbmi.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
windowMenu.add(minimizeItem);
windowMenu.add(zoomItem);
windowMenu.add(cbmi);
menuBar.add(windowMenu);
return menuBar;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new JTextPaneExample().createAndDisplayGUI();
}
});
}
}
Here is the Output :

You could try either of these approaches:
Unicode characters are appealing, but they offer poor alignment in a variable pitch font:
JMenuBar menuBar = new JMenuBar();
JMenu windowMenu = new JMenu("Window");
windowMenu.add(new JMenuItem("♦ Item"));
windowMenu.add(new JMenuItem("✓ Item"));
windowMenu.add(new JMenuItem("• Item"));
menuBar.add(windowMenu);
frame.setJMenuBar(menuBar);
Better, implement the Icon interface, illustrated here and here, using a fixed-size implementation to control geometry. CellTest shows one approach to rendering an arbitrary unicode glyph.

Related

Double icons with JMenuItem setHorizontalTextPosition on Win

Two icons are rendered when using JMenuItem setHorizontalTextPosition(SwingConstants.LEFT) with Windows Look and Feel. It works fine with the default Java Look and Feel.
I just filed a Java bug report, posting here for anyone else having the same problem.
Does anyone have another workaround to suggest?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
public class WinMenuItemIcon {
public static void main(String[] args) {
//NOTE: Bug happens with Windows L&F
String name = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel( name );
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.setTitle("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
ImageIcon icon = createIcon();
JMenuItem menuItem = new JMenuItem("Command", icon);
menuItem.setHorizontalTextPosition(SwingConstants.LEFT);
menu.add(menuItem);
menuBar.add(menu);
frame.setJMenuBar(menuBar);
frame.setPreferredSize(new Dimension(500, 500));
frame.pack();
frame.setVisible(true);
}
protected static ImageIcon createIcon() {
BufferedImage bi = new BufferedImage(25,25,BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.setColor(Color.RED);
g.fillOval(0,0, 25, 25);
return new ImageIcon(bi);
}
}
Delete the line
menuItem.setHorizontalTextPosition(SwingConstants.LEFT);
and you will have only 1 icon
or use an if statement to exclude that line for windows look and feel as follows
if(!UIManager.getLookAndFeel().equals("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"))
{
menuItem.setHorizontalTextPosition(SwingConstants.LEFT);
}
here is an alternative to #aterai's code that will work better if tweaked a bit more according to your needs, probably it is some bug but here this does it i am not sure how #aterai needs center to look like but here is what i assumed :-
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class WinMenuItemIconTest {
private static JMenuBar makeManuBar() {
JMenuItem menuItem0 = new JMenuItem("Command", createIcon());
JMenuItem menuItem1 = new JMenuItem("LEFT bug?", createIcon()); // always left by defaulr
JMenuItem menuItem2 = new JMenuItem("CENTER bug?", createIcon());
menuItem2.setMargin(new Insets(5, 50, 5, 5)); // using set margin to centerise
JMenuItem menuItem3 = new JMenuItem("RIGHT_TO_LEFT", createIcon());
menuItem3.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); // Right to left seems to work
JMenu menu = new JMenu("Menu");
menu.add(menuItem0);
menu.add(menuItem1);
menu.add(menuItem2);
menu.add(menuItem3);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
//NOTE: Bug happens with Windows L&F
String name = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(name);
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(makeManuBar());
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
protected static ImageIcon createIcon() {
BufferedImage bi = new BufferedImage(25, 25, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.setColor(Color.RED);
g.fillOval(0, 0, 25, 25);
return new ImageIcon(bi);
}
}
Note:- I am on Windows 10 too
My envirment: Windows 10 64bit + JDK 1.8.0_72
I'm not sure if this is a bug... Now this bug seems fixed: JDK-8152981 Double icons with JMenuItem setHorizontalTextPosition on Win 10 - Java Bug System
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class WinMenuItemIconTest {
private static JMenuBar makeManuBar() {
JMenuItem menuItem0 = new JMenuItem("Command", createIcon());
JMenuItem menuItem1 = new JMenuItem("LEFT bug?", createIcon());
menuItem1.setHorizontalTextPosition(SwingConstants.LEFT);
//menuItem1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JMenuItem menuItem2 = new JMenuItem("CENTER bug?", createIcon());
menuItem2.setHorizontalTextPosition(SwingConstants.CENTER);
JMenuItem menuItem3 = new JMenuItem("RIGHT_TO_LEFT", createIcon());
menuItem3.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JMenu menu = new JMenu("Menu");
menu.add(menuItem0);
menu.add(menuItem1);
menu.add(menuItem2);
menu.add(menuItem3);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
//NOTE: Bug happens with Windows L&F
String name = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(name);
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(makeManuBar());
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
protected static ImageIcon createIcon() {
BufferedImage bi = new BufferedImage(25, 25, BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.setColor(Color.RED);
g.fillOval(0, 0, 25, 25);
g.dispose();
return new ImageIcon(bi);
}
}
For aligning icon and label text from left to right:
JMenuItem menuItem3 = new JMenuItem("LEFT_TO_RIGHT", createIcon());
menuItem3.setHorizontalTextPosition(JMenuItem.RIGHT);
menuItem3.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
The above code worked for me.

How do I divide windows in using Swing?

I am writing a program in Java and I'm learning Swing as I go, but I seem to be at a roadblock. I have attached a sketch to explain what I'm trying to do, and hopefully you can help me understand what to do.
+===============================================================================+
|File Edit View Help |
+================================================================================
| | |
| | |
|Content 1 | Content 2 |
| | |
| | |
+===============================================================================+
I am using JFrames and JPanels to construct this program, but I cannot understand how to make the two frames for the content. Also, I want the left column to always be 150px wide, and the entire height of the frame, while the right should always fill the remaining width of the window.
package mycookbook;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
public class MyCookBook extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new MyCookBook();
}
public MyCookBook() {
super("My Cook Book vers. 0.0.0.1");
setSize(1920, 1030);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setMenu();
setWindows();
}
public void setMenu() {
//Setting up the menubar.
JMenuBar menubar = new JMenuBar();
//Adding the menu bar.
setJMenuBar(menubar);
//Setting up the file menu.
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenu nwFile = new JMenu("New >>");
JMenuItem cbNwFile = new JMenuItem("Cookbook");
JMenuItem chNwFile = new JMenuItem("Chapter");
JMenuItem rcNwFile = new JMenuItem("Recipe");
JMenu opFile = new JMenu("Open >>");
JMenuItem cbOpFile = new JMenuItem("Cookbook");
JMenuItem chOpFile = new JMenuItem("Chapter");
JMenuItem rcOpFile = new JMenuItem("Recipe");
JMenuItem svFile = new JMenuItem("Save");
JMenuItem ipFile = new JMenuItem("Import");
JMenuItem epFile = new JMenuItem("Export");
JMenuItem pnFile = new JMenuItem("Print");
JMenuItem upFile = new JMenuItem("Update");
JMenuItem prFile = new JMenuItem("Properties");
JMenuItem exFile = new JMenuItem("Exit");
//Adding all the file menu and its contents to the menubar.
menubar.add(fileMenu);
fileMenu.add(nwFile);
nwFile.add(cbNwFile);
nwFile.add(chNwFile);
nwFile.add(rcNwFile);
fileMenu.add(opFile);
opFile.add(cbOpFile);
opFile.add(chOpFile);
opFile.add(rcOpFile);
fileMenu.addSeparator();
fileMenu.add(svFile);
fileMenu.add(ipFile);
fileMenu.add(epFile);
fileMenu.add(pnFile);
fileMenu.addSeparator();
fileMenu.add(upFile);
fileMenu.add(prFile);
fileMenu.addSeparator();
fileMenu.add(exFile);
exFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//Setting up the edit menu.
JMenu editMenu = new JMenu("Edit");
editMenu.setMnemonic(KeyEvent.VK_E);
JMenuItem cbEdit = new JMenuItem("Cookbook");
JMenuItem chEdit = new JMenuItem("Chapter");
JMenuItem rcEdit = new JMenuItem("Recipe");
menubar.add(editMenu);
editMenu.add(cbEdit);
editMenu.add(chEdit);
editMenu.add(rcEdit);
//Setting up the view menu.
JMenu viewMenu = new JMenu("View");
viewMenu.setMnemonic(KeyEvent.VK_V);
JMenu mdView = new JMenu("Mode >>");
JMenuItem pnView = new JMenuItem("Panel View");
JMenuItem pgView = new JMenuItem("Page View");
JMenuItem lsView = new JMenuItem("List View");
JMenu rsView = new JMenu("Resolution >>");
JMenuItem smRes = new JMenuItem("1024x718");
JMenuItem mdRes = new JMenuItem("1440x910");
JMenuItem lgRes = new JMenuItem("1920x1030");
menubar.add(viewMenu);
viewMenu.add(mdView);
viewMenu.add(rsView);
mdView.add(pnView);
mdView.add(pgView);
mdView.add(lsView);
rsView.add(smRes);
rsView.add(mdRes);
rsView.add(lgRes);
smRes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setSize(1024,718);
setLocationRelativeTo(null);
}
});
mdRes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setSize(1440,910);
setLocationRelativeTo(null);
}
});
lgRes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setSize(1920,1030);
setLocationRelativeTo(null);
}
});
exFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//Setting up the help menu.
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
JMenuItem hpHelp = new JMenuItem("My Cookbook Help");
JMenuItem abHelp = new JMenuItem("About My Cookbook");
menubar.add(helpMenu);
helpMenu.add(hpHelp);
helpMenu.add(abHelp);
revalidate();
}
public void setWindows() {
JScrollPane bookPane = new JScrollPane();
JScrollPane recPane = new JScrollPane();
JSplitPane content = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,bookPane, recPane);
Dimension bpDim = new Dimension(150, 400);
Dimension rpDim = new Dimension(650, 400);
bookPane.setMinimumSize(bpDim);
recPane.setMinimumSize(rpDim);
add(content);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Read the section from the Swing tutorial on How to Use Border Layout.
One component goes to BorderLayout.LINE_START the other to BorderLayout.CENTER.
Also, I want the left column to always be 150px wide
The width is determined by the preferred size of the component added to that area of the BorderLayout.
You can simply solve this problem by using a different layout for your GUI. I recommend you check out the GridBagLayout as this layout is highly customizible.
We can modify our GridBagLayout by supplying it with GridBagConstraints once you've learned how to modify your GridBagLayout using GridBagConstraints your problem will be extremely simple to solve.
You asked how to divide windows, simple just make three JPanels and put two of thoseJPanels in the main JPanel that will be displayed at the highest level.

Align icon and JCheckbox in JPopupmenu

I have a Problem with some icons and check-boxes in a JPopupMenu. The Check-boxes and Icons are not aligned
The Items are created like:
JMenuItem deleteAttributeMenuItem = new JMenuItem(locale.getString("TREE_AttrDelete"), iconDelete);
JMenuItem primaryKeyAttributeMenuItem = new JCheckBoxMenuItem(locale.getString("TREE_AttrChkBoxPK"));
Please take a look at the picture:
Any tips?
Have a look at this, in order to achieve what you wanted, I did this,
JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem("Check Me", null, true);
cbmi.setMargin(new java.awt.Insets(5, 25, 5, 5));
cbmi.setIconTextGap(15);
cbmi.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
helpMenu.add(cbmi);
And here is the OUTPUT of the said thingy :
right now I can't found the right way how to re_layout JCheckBoxMenuItem,
but do you agree with this standars output from Swing by using (default) Metal Look and Feel???, just to avoiding any missunderstand by using another Look and Feel(s), because there are some differencies in the API betweens Swing's Standard Look and Feels too
from tutorials code (modified and removed balasts and noises)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuLookDemo {
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
private JTextArea output;
private JScrollPane scrollPane;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuItem;
private JRadioButtonMenuItem rbMenuItem;
private JCheckBoxMenuItem cbMenuItem;
public JMenuBar createMenuBar() {
menuBar = new JMenuBar();
menu = new JMenu("A Menu");
menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
menuBar.add(menu);
menuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon", errorIcon);
menu.add(menuItem);
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(true);
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Another one", infoIcon);
group.add(rbMenuItem);
menu.add(rbMenuItem);
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item", warnIcon);
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
menu.add(cbMenuItem);
menu.addSeparator();
return menuBar;
}
public Container createContentPane() {
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("MenuLookDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MenuLookDemo demo = new MenuLookDemo();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
frame.setSize(450, 260);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
these methods talking about possitions in pixels

JToolBar not showing

I had a simple drawing application. I need to add a menu and a toolbar on the left side.
So now, instead of using a simple JFrame, I'm creating a simple class that extends JFrame. I was able to add the menu following some examples online, but can't figure out how to add a JToolBar. I've tried a few different ways, but nothing works. I don't get an error, everything complies just fine, but I don't see any JToolBar.
Here's the code for my JFrame, I hope you can help.
class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
public Menu(String title) {
openItem = new JMenuItem("Open...");
openItem.setMnemonic('O');
openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
saveAsItem = new JMenuItem("Save As...");
saveAsItem.setMnemonic('S');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
// (2) Build menubar, menus, and add menuitems.
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
menubar.add(fileMenu);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(saveItem);
// (3) Add listeners to menu items
openItem.addActionListener(new OpenAction()); // TODO change
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
// JPanel panel = new JPanel();
// panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JButton newb = new JButton("new");
toolbar.add(newb);
// toolbar.setOpaque(true);
toolbar.setLocation(100, 100);
toolbar.setVisible(true);
// toolbar.setMinimumSize(new Dimension(100, 100));
// toolbar.setAlignmentX(0);
// panel.add(toolbar);
add(toolbar, BorderLayout.NORTH);
getContentPane().add(toolbar, BorderLayout.NORTH);
// getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
setTitle(title);
pack();
setLocationRelativeTo(null); // Center window.
}
// OpenAction
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
}
}
}
its work fine, and you don't need to setVisible tool bar because its showing by default, also don't add the tool bar two time in the same place (NORTH)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MenuDemo {
public static void main(String... args) {
EventQueue.invokeLater(
new Runnable() {
#Override
public void run() {
JFrame menu = new Menu("Testing");
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setVisible(true);
}
}
);
}
}
class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;
public Menu(String title) {
openItem = new JMenuItem("Open...");
openItem.setMnemonic('O');
openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));
saveItem = new JMenuItem("Save");
saveItem.setMnemonic('S');
saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
saveAsItem = new JMenuItem("Save As...");
saveAsItem.setMnemonic('S');
saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
// (2) Build menubar, menus, and add menuitems.
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
menubar.add(fileMenu);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(saveItem);
// (3) Add listeners to menu items
openItem.addActionListener(new OpenAction()); // TODO change
setJMenuBar(menubar);
JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
JButton newb = new JButton("new");
toolbar.add(newb);
add(toolbar, BorderLayout.NORTH);
setTitle(title);
setLocationRelativeTo(null);
pack();
}
// OpenAction
private class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
}
}
}
My problem was that I was the way I was instantiating my JFrame. I was using a helper function like this one:
public static JFrame openInJFrame(Container content, int width, int height,
String title, Color bgColor) {
// ...
frame.setContentPane(content);
frame.setVisible(true);
return (frame);
}
So my JToolBar was getting replaced by the Container object...
Thanks guys! Your answers helped me figure out my problem.

Java GUI not displaying my file when opened

So I have a simple GUI that can only open text files and should just display them in a text area to be edited. I know my string contains the files contents since I can print it out, but when I try and add it to my text area, it does not show up. I was wondering if this was a problem of overlapping text areas but I can't seem to find the error.
The first part of my code just creates the GUI. The other part should open a file and fill the text area with it. Where exactly is the problem and how do I fix it? Any help would be appreciated.
Here is part of my code which deals with creating the frames and panels:
public class MenuView extends JFrame {
private JPanel centerPanel;
private JPanel bottomPanel;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem openItem;
private JMenuItem closeItem;
private JButton setButton;
private JTextField text;
private JTextArea label;
private JMenuItem fileNew;
public MenuView(){
super();
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setTitle("Menu Demo");
//The center panel that will contain text
centerPanel = new JPanel();
centerPanel.setLayout(new FlowLayout());
label = new JTextArea(400,500);
centerPanel.add(label);
add(centerPanel, BorderLayout.CENTER);
//The bottom panel with the text field and button
bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(1, 2));
setButton = new JButton("Set Text");
text = new JTextField();
bottomPanel.add(setButton);
bottomPanel.add(text);
add(bottomPanel, BorderLayout.SOUTH);
//Setting up the menu
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
fileNew = new JMenu("New");
openItem = new JMenuItem("Open");
closeItem = new JMenuItem("Exit");
fileMenu.add(openItem);
fileMenu.add(closeItem);
fileMenu.add(fileNew);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
setButton.addActionListener(new ButtonCommand(label, text));
closeItem.addActionListener(new QuitMenuCommand());
openItem.addActionListener(new OpenMenuCommand(label));
}
public static void main(String [] args){
MenuView v = new MenuView();
v.setVisible(true);
}
}
Here is the code that deals with opening the files:
public class OpenMenuCommand implements ActionListener {
private JTextArea theLabel;
private JFileChooser fc;
private String k = "";
public OpenMenuCommand(JTextArea l){
theLabel = l;
theLabel.getParent();
fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("Text file", "txt"));
}
public void actionPerformed(ActionEvent e) {
StringBuffer text = new StringBuffer();
int returnValue = fc.showOpenDialog(null);
if(returnValue == fc.APPROVE_OPTION){
theLabel.removeAll();
File f = fc.getSelectedFile();
try{
BufferedReader inFile = new BufferedReader(new FileReader(f));
String in = inFile.readLine();
while(in != null){
k = k + in;
in = inFile.readLine();
}
System.out.println(k);
theLabel.setText(k);
inFile.close();
theLabel.setVisible(true);
}catch(FileNotFoundException exc){
//Should never trigger
}catch(IOException exc){
theLabel.setText("Error reading in file.");
}
}
}
}
Your stuff is being added to the JTextArea but you're not seeing due the size of the JTextArea. It's actually a friggin' big JTextArea:
label = new JTextArea(400, 500);
And by adding the huge JTextArea to a FlowLayout-using JPanel much of it is off the screen.
To see what I mean, add this to your actionPerformed method:
System.out.println(theLabel.getBounds());
You'll see that the width and height are tremendous, and what's more, the left side is a large negative number.
Solution: Make your JTextArea more reasonable size (see in the API what these numbers mean -- row and column, not points) and add it to a JScrollPane and then add that BorderLayout.CENTER to a BorderLayout using container.
For example, the small GUI SSCCE shows your JTextArea in a FlowLayout using JPanel on the left and my JTextArea inside of a JScrollPane on the right:
import java.awt.*;
import javax.swing.*;
public class MenuViewSSCCE {
private static final Dimension APP_SIZE = new Dimension(500, 400);
private static void createAndShowUI() {
JTextArea label = new JTextArea(400, 500); // friggin big!
JTextArea label2 = new JTextArea(400, 500); // friggin big!
label.setText("Look at how big this JTextArea is!");
label2.setText("Look at how big this JTextArea is!");
JPanel centerPanel = new JPanel();
centerPanel.setPreferredSize(APP_SIZE);
centerPanel.setLayout(new FlowLayout()); // this line is redundant
centerPanel.add(label);
JScrollPane myScrollpane = new JScrollPane(label2);
myScrollpane.setPreferredSize(APP_SIZE);
JPanel gridPanel = new JPanel(new GridLayout(1, 0));
gridPanel.add(centerPanel);
gridPanel.add(myScrollpane);
JFrame frame = new JFrame("Your code on left, mine on right");
frame.getContentPane().add(gridPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Categories

Resources