I have a JDesktopPane with some JInternalframe windows in it as seen in the image below:
When I minimize them, they don't show their full title. Is there a way to show it fully?
You might be able to override the iconifyFrame(...) method of DefaultDesktopManager and getPreferredSize() method of JInternalFrame.JDesktopIcon to set that DesktopIcon size.
import java.awt.*;
import javax.swing.*;
//https://stackoverflow.com/questions/35287367/changing-desktopicon-width-on-nimbus
public class DesktopIconWidthTest2 {
public JComponent makeUI() {
JDesktopPane desktop = new JDesktopPane();
desktop.setDesktopManager(new DefaultDesktopManager() {
#Override public void iconifyFrame(JInternalFrame f) {
Rectangle r = this.getBoundsForIconOf(f);
r.width = f.getDesktopIcon().getPreferredSize().width;
f.getDesktopIcon().setBounds(r);
super.iconifyFrame(f);
}
});
desktop.add(createFrame("looooooooooooong title #", 1));
desktop.add(createFrame("#", 0));
return desktop;
}
private JInternalFrame createFrame(String t, int i) {
JInternalFrame f = new JInternalFrame(t + i, true, true, true, true);
f.setDesktopIcon(new JInternalFrame.JDesktopIcon(f) {
#Override public Dimension getPreferredSize() {
Dimension d = f.getMinimumSize();
String title = f.getTitle();
FontMetrics fm = getFontMetrics(getFont());
//Magic Number 16: margin?
d.width += SwingUtilities.computeStringWidth(fm, title) - 16;
return d;
}
});
f.setSize(200, 100);
f.setVisible(true);
f.setLocation(5 + 40 * i, 5 + 50 * i);
return f;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
// MetalLookAndFeel: UIManager.put("DesktopIcon.width", 500);
} catch (Exception e) {
e.printStackTrace();
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new DesktopIconWidthTest2().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
Related
The problem: when you double click on word in JTextArea it is marked, but when you don't release the mouse button and try to mark next word, it is not marking whole word, but single characters instead.
It should mark the whole words (not single characters) when moving mouse (on double click). That's literally the default behavior in all programs which I tried, like: Notepad, Firefox, Chrome, Word, even Netbeans, etc.
Same thing with triple click (when holding and moving the mouse should mark the next line, not characters).
Any ideas? I had hard time Googling this, but since it's a very common thing I believe there must be a simple option or at least someone already have a solution.
Sample code:
public class TestJTextArea
{
public static void main(final String[] args)
{
final JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(500, 500));
panel.add(new JTextArea(), BorderLayout.CENTER);
final JFrame frame = new JFrame("Test");
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Maybe you need to create a customized Caret, for example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TestJTextArea2 {
public Component makeUI() {
String text = "The quick brown fox jumps over the lazy dog.";
JTextArea textArea1 = new JTextArea("default\n" + text);
JTextArea textArea2 = new JTextArea("setCaret\n" + text) {
#Override public void updateUI() {
setCaret(null);
super.updateUI();
Caret oldCaret = getCaret();
int blinkRate = oldCaret.getBlinkRate();
Caret caret = new SelectWordCaret();
caret.setBlinkRate(blinkRate);
setCaret(caret);
}
};
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(new JScrollPane(textArea1));
p.add(new JScrollPane(textArea2));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TestJTextArea2().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class SelectWordCaret extends DefaultCaret {
private boolean wordSelectingMode = false;
private int p0; // = Math.min(getDot(), getMark());
private int p1; // = Math.max(getDot(), getMark());
#Override public void mousePressed(MouseEvent e) {
super.mousePressed(e);
int nclicks = e.getClickCount();
if (SwingUtilities.isLeftMouseButton(e) && !e.isConsumed() && nclicks == 2) {
p0 = Math.min(getDot(), getMark());
p1 = Math.max(getDot(), getMark());
wordSelectingMode = true;
} else {
wordSelectingMode = false;
}
}
#Override public void mouseDragged(MouseEvent e) {
if (wordSelectingMode && !e.isConsumed() && SwingUtilities.isLeftMouseButton(e)) {
continuouslySelectWords(e);
} else {
super.mouseDragged(e);
}
}
private void continuouslySelectWords(MouseEvent e) {
Position.Bias[] biasRet = new Position.Bias[1];
JTextComponent c = getComponent();
int pos = c.getUI().viewToModel2D(c, e.getPoint(), biasRet);
if(biasRet[0] == null) {
biasRet[0] = Position.Bias.Forward;
}
try {
if (p0 <= pos && pos <= p1) {
setDot(p0);
moveDot(p1, biasRet[0]);
} else if (p1 < pos) {
setDot(p0);
moveDot(Utilities.getWordEnd(c, pos - 1), biasRet[0]);
} else if (p0 > pos) {
setDot(p1);
moveDot(Utilities.getWordStart(c, pos), biasRet[0]);
}
} catch (BadLocationException bl) {
UIManager.getLookAndFeel().provideErrorFeedback(c);
}
}
}
How can I repaint every time the coordinates of my GUI changes via Swing timer?
Here's a snippet of my code:
t = new Timer(500,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for(int i=0;i<=100;i++) {
panel.setBounds(i,100,550,336);
panel.repaint();
}
t.stop();
}
});
t.start();
My panel only repaints once the loop is done thus not showing the transition effect I wanted to see.
My panel only repaints once the loop is done thus not showing the transition effect I wanted to see.
Here is an example that successfully moves a component using only a Swing Timer. I conclude that the problem is in code not shown above.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class BouncingLabel {
private JComponent ui = null;
int xD = 1;
int yD = 1;
int l = 101;
int r = 100;
int t = 50;
int b = 50;
BouncingLabel() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new CompoundBorder(
new EmptyBorder(4, 4, 4, 4),
new LineBorder(Color.BLACK)));
final JLabel label = new JLabel(new ImageIcon(
new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB)));
ui.add(label);
EmptyBorder emptyBorder = new EmptyBorder(t, l, b, r);
label.setBorder(emptyBorder);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Border border = label.getBorder();
Insets insets = border.getBorderInsets(label);
if (l == 0 | r == 0) {
xD = -xD;
}
if (t == 0 || b == 0) {
yD = -yD;
}
l = l + xD;
r = r - xD;
t = t + yD;
b = b - yD;
label.setBorder(new EmptyBorder(t, l, b, r));
}
};
Timer timer = new Timer(15, listener);
timer.start();
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
BouncingLabel o = new BouncingLabel();
JFrame f = new JFrame("Bouncing Square");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
I have implemented my own closeable JTabbedPane (essentially following advice from here - by extending JTabbedPane and overriding some methods and calling setTabComponentAt(...)). It works perfectly except one thing - when there are too many tabs to fit on one row (when there are 2 or more rows of tabs), the cross button/icon is not aligned to the right of the tab but it remains next to the tab title, which looks ugly. I've tried the demo from Java tutorials and it suffers from the same problem.
What I want is that the cross button/icon is always aligned to the very right, but the text is always aligned to the center. Can this be achieved by some layouting tricks? Note: I do not want to implement a custom TabbedPaneUI as this leads to other problems.
UPDATE I'm forced to use Java 6
The complete code is below, just run it and add 5 or more tabs.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
/**
* CloseableTabbedPane is a tabbed pane with a close icon on the right side of all tabs making it possible to close a tab.
* You can pass an instance of TabClosingListener to one of the constructors to react to tab closing.
*
* #author WiR
*/
public class CloseableTabbedPane extends JTabbedPane {
public static interface TabClosingListener {
/**
* #param aTabIndex the index of the tab that is about to be closed
* #return true if the tab can be really closed
*/
public boolean tabClosing(int aTabIndex);
/**
* #param aTabIndex the index of the tab that is about to be closed
* #return true if the tab should be selected before closing
*/
public boolean selectTabBeforeClosing(int aTabIndex);
}
private TabClosingListener tabClosingListener;
private String iconFileName = "images/cross.gif";
private String selectedIconFileName = "images/cross_selected.gif";
private static Icon CLOSING_ICON;
private static Icon CLOSING_ICON_SELECTED;
private class PaintedCrossIcon implements Icon {
int size = 10;
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.drawLine(x, y, x + size, y + size);
g.drawLine(x + size, y, x, y + size);
}
#Override
public int getIconWidth() {
return size;
}
#Override
public int getIconHeight() {
return size;
}
}
public CloseableTabbedPane() {
super();
}
public CloseableTabbedPane(TabClosingListener aTabClosingListener) {
super();
tabClosingListener = aTabClosingListener;
}
/**
* Sets the file name of the closing icon along with the optional variant of the icon when the mouse is over the icon.
*/
public void setClosingIconFileName(String aIconFileName, String aSelectedIconFileName) {
iconFileName = aIconFileName;
selectedIconFileName = aSelectedIconFileName;
}
/**
* Makes the close button at the specified indes visible or invisible
*/
public void setCloseButtonVisibleAt(int aIndex, boolean aVisible) {
CloseButtonTab cbt = (CloseButtonTab) getTabComponentAt(aIndex);
cbt.closingLabel.setVisible(aVisible);
}
#Override
public void insertTab(String title, Icon icon, Component component, String tip, int index) {
super.insertTab(title, icon, component, tip, index);
setTabComponentAt(index, new CloseButtonTab(component, title, icon));
}
#Override
public void setTitleAt(int index, String title) {
super.setTitleAt(index, title);
CloseButtonTab cbt = (CloseButtonTab) getTabComponentAt(index);
cbt.label.setText(title);
}
#Override
public void setIconAt(int index, Icon icon) {
super.setIconAt(index, icon);
CloseButtonTab cbt = (CloseButtonTab) getTabComponentAt(index);
cbt.label.setIcon(icon);
}
#Override
public void setComponentAt(int index, Component component) {
CloseButtonTab cbt = (CloseButtonTab) getTabComponentAt(index);
super.setComponentAt(index, component);
cbt.tab = component;
}
//note: setToolTipTextAt(int) must NOT be overridden !
private Icon getImageIcon(String aImageName) {
URL imageUrl = CloseableTabbedPane.class.getClassLoader().getResource(aImageName);
if (imageUrl == null) {
return new PaintedCrossIcon();
}
ImageIcon result = new ImageIcon(imageUrl);
if (result.getIconWidth() != -1) {
return result;
} else {
return null;
}
}
private class CloseButtonTab extends JPanel {
private Component tab;
private JLabel label;
private JLabel closingLabel;
public CloseButtonTab(Component aTab, String aTitle, Icon aIcon) {
tab = aTab;
setOpaque(false);
setLayout(new GridBagLayout());
setVisible(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0, 0, 0, 5);
label = new JLabel(aTitle);
label.setIcon(aIcon);
add(label, gbc);
if (CLOSING_ICON == null) {
CLOSING_ICON = getImageIcon(iconFileName);
CLOSING_ICON_SELECTED = getImageIcon(selectedIconFileName);
}
closingLabel = new JLabel(CLOSING_ICON);
closingLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent();
int tabIndex = indexOfComponent(tab);
if (tabClosingListener != null) {
if (tabClosingListener.selectTabBeforeClosing(tabIndex)) {
tabbedPane.setSelectedIndex(tabIndex);
}
if (tabClosingListener.tabClosing(tabIndex)) {
tabbedPane.removeTabAt(tabIndex);
}
} else {
tabbedPane.removeTabAt(tabIndex);
}
}
#Override
public void mouseEntered(MouseEvent e) {
if (CLOSING_ICON_SELECTED != null) {
closingLabel.setIcon(CLOSING_ICON_SELECTED);
}
}
#Override
public void mouseExited(MouseEvent e) {
if (CLOSING_ICON_SELECTED != null) {
closingLabel.setIcon(CLOSING_ICON);
}
}
});
gbc.insets = new Insets(0, 0, 0, 0);
add(closingLabel, gbc);
}
}
static int count = 0;
/**
* For testing purposes.
*
*/
public static void main(String[] args) {
final JTabbedPane tabbedPane = new CloseableTabbedPane();
tabbedPane.addTab("test" + count, new JPanel());
count++;
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(tabbedPane, BorderLayout.CENTER);
JButton addButton = new JButton("Add tab");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tabbedPane.addTab("test" + count, new JPanel());
count++;
}
});
mainPanel.add(addButton, BorderLayout.SOUTH);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 400);
frame.getContentPane().add(mainPanel);
frame.setVisible(true);
}
}
Here is one possible implementation using JLayer:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class CloseableTabbedPaneTest {
public JComponent makeUI() {
UIManager.put("TabbedPane.tabInsets", new Insets(2, 2, 2, 50));
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("aaaaaaaaaaaaaaaa", new JPanel());
tabbedPane.addTab("bbbbbbbb", new JPanel());
tabbedPane.addTab("ccc", new JPanel());
JPanel p = new JPanel(new BorderLayout());
p.add(new JLayer<JTabbedPane>(tabbedPane, new CloseableTabbedPaneLayerUI()));
p.add(new JButton(new AbstractAction("add tab") {
#Override public void actionPerformed(ActionEvent e) {
tabbedPane.addTab("test", new JPanel());
}
}), BorderLayout.SOUTH);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new CloseableTabbedPaneTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class CloseableTabbedPaneLayerUI extends LayerUI<JTabbedPane> {
private final JPanel p = new JPanel();
private final Point pt = new Point(-100, -100);
private final JButton button = new JButton("x") {
#Override public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
};
public CloseableTabbedPaneLayerUI() {
super();
button.setBorder(BorderFactory.createEmptyBorder());
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setRolloverEnabled(false);
}
#Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
if (c instanceof JLayer) {
JLayer jlayer = (JLayer) c;
JTabbedPane tabPane = (JTabbedPane) jlayer.getView();
for (int i = 0; i < tabPane.getTabCount(); i++) {
Rectangle rect = tabPane.getBoundsAt(i);
Dimension d = button.getPreferredSize();
int x = rect.x + rect.width - d.width - 2;
int y = rect.y + (rect.height - d.height) / 2;
Rectangle r = new Rectangle(x, y, d.width, d.height);
button.setForeground(r.contains(pt) ? Color.RED : Color.BLACK);
SwingUtilities.paintComponent(g, button, p, r);
}
}
}
#Override public void installUI(JComponent c) {
super.installUI(c);
((JLayer)c).setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
#Override public void uninstallUI(JComponent c) {
((JLayer)c).setLayerEventMask(0);
super.uninstallUI(c);
}
#Override protected void processMouseEvent(MouseEvent e, JLayer<? extends JTabbedPane> l) {
if (e.getID() == MouseEvent.MOUSE_CLICKED) {
pt.setLocation(e.getPoint());
JTabbedPane tabbedPane = (JTabbedPane) l.getView();
int index = tabbedPane.indexAtLocation(pt.x, pt.y);
if (index >= 0) {
Rectangle rect = tabbedPane.getBoundsAt(index);
Dimension d = button.getPreferredSize();
int x = rect.x + rect.width - d.width - 2;
int y = rect.y + (rect.height - d.height) / 2;
Rectangle r = new Rectangle(x, y, d.width, d.height);
if (r.contains(pt)) {
tabbedPane.removeTabAt(index);
}
}
l.getView().repaint();
}
}
#Override protected void processMouseMotionEvent(MouseEvent e, JLayer<? extends JTabbedPane> l) {
pt.setLocation(e.getPoint());
JTabbedPane tabbedPane = (JTabbedPane) l.getView();
int index = tabbedPane.indexAtLocation(pt.x, pt.y);
if (index >= 0) {
tabbedPane.repaint(tabbedPane.getBoundsAt(index));
} else {
tabbedPane.repaint();
}
}
}
Edit:
Here is an example using a GlassPane(Note: this is NOT tested at all):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CloseableTabbedPaneTest2 {
public JComponent makeUI() {
UIManager.put("TabbedPane.tabInsets", new Insets(2, 2, 2, 50));
final JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("aaaaaaaaaaaaaaaa", new JPanel());
tabbedPane.addTab("bbbbbbbb", new JPanel());
tabbedPane.addTab("ccc", new JPanel());
JPanel p = new JPanel(new BorderLayout());
//p.setBorder(BorderFactory.createLineBorder(Color.RED, 10));
p.add(tabbedPane);
p.add(new JButton(new AbstractAction("add tab") {
#Override public void actionPerformed(ActionEvent e) {
tabbedPane.addTab("test", new JScrollPane(new JTree()));
}
}), BorderLayout.SOUTH);
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
JPanel gp = new CloseableTabbedPaneGlassPane(tabbedPane);
tabbedPane.getRootPane().setGlassPane(gp);
gp.setOpaque(false);
gp.setVisible(true);
}
});
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new CloseableTabbedPaneTest2().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class CloseableTabbedPaneGlassPane extends JPanel {
private final Point pt = new Point(-100, -100);
private final JButton button = new JButton("x") {
#Override public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
};
private final JTabbedPane tabbedPane;
private final Rectangle buttonRect = new Rectangle(button.getPreferredSize());
public CloseableTabbedPaneGlassPane(JTabbedPane tabbedPane) {
super();
this.tabbedPane = tabbedPane;
MouseAdapter h = new Handler();
tabbedPane.addMouseListener(h);
tabbedPane.addMouseMotionListener(h);
button.setBorder(BorderFactory.createEmptyBorder());
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setRolloverEnabled(false);
}
#Override public void paintComponent(Graphics g) {
Point glassPt = SwingUtilities.convertPoint(tabbedPane, 0, 0, this);
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
Rectangle tabRect = tabbedPane.getBoundsAt(i);
int x = tabRect.x + tabRect.width - buttonRect.width - 2;
int y = tabRect.y + (tabRect.height - buttonRect.height) / 2;
buttonRect.setLocation(x, y);
button.setForeground(buttonRect.contains(pt) ? Color.RED : Color.BLACK);
buttonRect.translate(glassPt.x, glassPt.y);
SwingUtilities.paintComponent(g, button, this, buttonRect);
}
}
class Handler extends MouseAdapter {
#Override public void mouseClicked(MouseEvent e) {
pt.setLocation(e.getPoint());
int index = tabbedPane.indexAtLocation(pt.x, pt.y);
if (index >= 0) {
Rectangle tabRect = tabbedPane.getBoundsAt(index);
int x = tabRect.x + tabRect.width - buttonRect.width - 2;
int y = tabRect.y + (tabRect.height - buttonRect.height) / 2;
buttonRect.setLocation(x, y);
if (buttonRect.contains(pt)) {
tabbedPane.removeTabAt(index);
}
}
tabbedPane.repaint();
}
#Override public void mouseMoved(MouseEvent e) {
pt.setLocation(e.getPoint());
int index = tabbedPane.indexAtLocation(pt.x, pt.y);
if (index >= 0) {
tabbedPane.repaint(tabbedPane.getBoundsAt(index));
} else {
tabbedPane.repaint();
}
}
}
}
I'm using this one: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TabComponentsDemoProject/src/components/ButtonTabComponent.java
The close button is painted by this itself so if can be placed anywhere.
I have a java application - a calculator. I want to resize font of buttons dynamically with resizing the window of the app. How to implement it?
My idea is using ComponentEvents. I have initial size of the window of application and initial fonts' sizes. I want to change font size according to button's size, affected by window size change. The problem is how to use the ratio [initial window size] / [initial font size] in the overriden method? The ratio is different for each font.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
public class Main extends JFrame {
public Main() {
super("Test");
JPanel cPane = (JPanel) getContentPane();
cPane.setLayout(new BorderLayout());
MyButton sampleButton = new MyButton("Sample text");
sampleButton.setFont(new Font("Sans Serif", Font.PLAIN, 20));
MyButton a, b, c, d;
a = new MyButton("a");
b = new MyButton("b");
c = new MyButton("c");
d = new MyButton("d");
cPane.add(a, BorderLayout.PAGE_START);
cPane.add(b, BorderLayout.PAGE_END);
cPane.add(c, BorderLayout.LINE_START);
cPane.add(d, BorderLayout.LINE_END);
cPane.add(sampleButton, BorderLayout.CENTER);
setSize(300, 200);
setResizable(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String... args) {
new Main();
}
class MyButton extends JButton implements ComponentListener {
public MyButton(String title) {
super(title);
}
#Override
public void componentResized(ComponentEvent e) {
//resizing font
}
#Override
public void componentMoved(ComponentEvent e) {
}
#Override
public void componentShown(ComponentEvent e) {
}
#Override
public void componentHidden(ComponentEvent e) {
}
}
}
See how you go with this code using GlyphVector to determine the largest Font that will fit.
The GUI was a little shaky unless there was a delay between setting the frame visible and adding the ComponentListener. I solved that by delaying adding the listener using a single shot Swing Timer.
Is is based on Calculet which is a fully functioning (if simple) calculator using the ScriptEngine.
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
import javax.script.*;
import javax.swing.border.Border;
class SwingCalculator implements ActionListener, KeyListener {
JTextField io;
ScriptEngine engine;
ArrayList<JButton> controls;
final BufferedImage textImage = new BufferedImage(
100, 100,
BufferedImage.TYPE_INT_ARGB);
public int getMaxFontSizeForControls() {
Graphics2D g = textImage.createGraphics();
FontRenderContext frc = g.getFontRenderContext();
int maxSize = 500;
for (JButton b : controls) {
// skip the = button..
if (!b.getText().equals("=")) {
int max = getMaxFontSizeForControl(b, frc);
if (maxSize > max) {
maxSize = max;
}
}
}
g.dispose();
return maxSize;
}
public int getMaxFontSizeForControl(JButton button, FontRenderContext frc) {
Rectangle r = button.getBounds();
Insets m = button.getMargin();
Insets i = button.getBorder().getBorderInsets(button);
Rectangle viewableArea = new Rectangle(
r.width -
(m.right + m.left + i.left + i.right),
r.height -
(m.top + m.bottom + i.top + i.bottom)
);
Font font = button.getFont();
int size = 1;
boolean tooBig = false;
while (!tooBig) {
Font f = font.deriveFont((float) size);
GlyphVector gv = f.createGlyphVector(frc, button.getText());
Rectangle2D box = gv.getVisualBounds();
if (box.getHeight() > viewableArea.getHeight()
|| box.getWidth() > viewableArea.getWidth()) {
tooBig = true;
size--;
}
size++;
}
return size;
}
SwingCalculator() {
// obtain a reference to the JS engine
engine = new ScriptEngineManager().getEngineByExtension("js");
JPanel gui = new JPanel(new BorderLayout(2, 2));
controls = new ArrayList<JButton>();
JPanel text = new JPanel(new GridLayout(0, 1, 3, 3));
gui.add(text, BorderLayout.NORTH);
io = new JTextField(15);
Font font = io.getFont();
font = font.deriveFont(font.getSize() * 1.7f);
io.setFont(font);
io.setHorizontalAlignment(SwingConstants.TRAILING);
io.setFocusable(false);
text.add(io);
JPanel buttons = new JPanel(new GridLayout(4, 4, 2, 2));
gui.add(buttons, BorderLayout.CENTER);
addButton(buttons, "7");
addButton(buttons, "8");
addButton(buttons, "9");
addButton(buttons, "/");
addButton(buttons, "4");
addButton(buttons, "5");
addButton(buttons, "6");
addButton(buttons, "*");
addButton(buttons, "1");
addButton(buttons, "2");
addButton(buttons, "3");
addButton(buttons, "-");
addButton(buttons, "0");
addButton(buttons, ".");
addButton(buttons, "C");
addButton(buttons, "+");
JButton equals = new JButton("=");
equals.addKeyListener(this);
controls.add(equals);
equals.addActionListener(this);
gui.add(equals, BorderLayout.EAST);
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
final JFrame f = new JFrame("Calculet");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(gui);
f.pack();
f.setMinimumSize(f.getSize());
f.setLocationByPlatform(true);
f.setVisible(true);
final ComponentListener cl = new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
int ii = getMaxFontSizeForControls();
for (JButton b : controls) {
if (!b.getText().equals("=")) {
b.setFont(b.getFont().deriveFont((float) ii));
}
}
}
};
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
f.addComponentListener(cl);
}
};
Timer t = new Timer(500, al);
t.setRepeats(false);
t.start();
}
public void addButton(Container c, String text) {
JButton b = new JButton(text);
b.addActionListener(this);
b.addKeyListener(this);
controls.add(b);
c.add(b);
}
public void calculateResult() {
try {
Object result = engine.eval(io.getText());
if (result == null) {
io.setText("Output was 'null'");
} else {
io.setText(result.toString());
}
} catch (ScriptException se) {
io.setText(se.getMessage());
}
}
public void actionPerformed(ActionEvent ae) {
String command = ae.getActionCommand();
if (command.equals("C")) {
io.setText("");
} else if (command.equals("=")) {
calculateResult();
} else {
io.setText(io.getText() + command);
}
}
private JButton getButton(String text) {
for (JButton button : controls) {
String s = button.getText();
if (text.endsWith(s)
|| (s.equals("=")
&& (text.equals("Equals") || text.equals("Enter")))) {
return button;
}
}
return null;
}
/*
* START - Because I hate mice.
*/
public void keyPressed(KeyEvent ke) {
}
public void keyReleased(KeyEvent ke) {
String s = ke.getKeyText(ke.getKeyCode());
JButton b = getButton(s);
if (b != null) {
b.requestFocusInWindow();
b.doClick();
}
}
public void keyTyped(KeyEvent ke) {
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new SwingCalculator();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
Compare the approaches shown here and here. The former uses an available JComponent.sizeVariant.
The latter cites an example using FontMentrics.
Or TextLayout.
JProgressBar in JProgressBar.VERTICAL mode rotates painted String.
Is it possible to save string HORIZONTAL?
Another option is to use a BorderLayout + JLabel
or if you are using Java 1.7.0, you can use a JLayer
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.LayerUI;
public class ProgressBarLabelTest {
private static JProgressBar makeProgressBar1(BoundedRangeModel model) {
JProgressBar progressBar = new JProgressBar(model) {
private JLabel label = new JLabel("000/100", SwingConstants.CENTER);
private ChangeListener changeListener = null;
#Override public void updateUI() {
removeAll();
if(changeListener!=null) removeChangeListener(changeListener);
super.updateUI();
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
setLayout(new BorderLayout());
changeListener = new ChangeListener() {
#Override public void stateChanged(ChangeEvent e) {
int iv = (int)(100 * getPercentComplete());
label.setText(String.format("%03d/100", iv));
}
};
addChangeListener(changeListener);
add(label);
label.setBorder(BorderFactory.createEmptyBorder(0,4,0,4));
}
});
}
#Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
Insets i = label.getInsets();
d.width = label.getPreferredSize().width + i.left + i.right;
return d;
}
};
initProgressBar(progressBar);
return progressBar;
}
private static JComponent makeProgressBar2(BoundedRangeModel model) {
final JLabel label = new JLabel("000/100");
label.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
LayerUI<JProgressBar> layerUI = new LayerUI<JProgressBar>() {
private final JPanel rubberStamp = new JPanel();
#Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
Dimension d = label.getPreferredSize();
int x = (c.getWidth() - d.width) / 2;
int y = (c.getHeight() - d.height) / 2;
JLayer jlayer = (JLayer)c;
JProgressBar progress = (JProgressBar)jlayer.getView();
int iv = (int)(100 * progress.getPercentComplete());
label.setText(String.format("%03d/100", iv));
SwingUtilities.paintComponent(
g, label, rubberStamp, x, y, d.width, d.height);
}
};
JProgressBar progressBar = new JProgressBar(model) {
#Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
Insets i = label.getInsets();
d.width = label.getPreferredSize().width + i.left + i.right;
return d;
}
};
initProgressBar(progressBar);
return new JLayer<JProgressBar>(progressBar, layerUI);
}
public JComponent makeUI() {
final BoundedRangeModel m = new DefaultBoundedRangeModel();
JProgressBar progressBar0 = new JProgressBar(m);
initProgressBar(progressBar0);
progressBar0.setStringPainted(true);
JPanel p = new JPanel();
p.add(progressBar0);
p.add(makeProgressBar1(m));
p.add(makeProgressBar2(m));
p.add(new JButton(new AbstractAction("+10") {
private int i = 0;
#Override public void actionPerformed(ActionEvent e) {
m.setValue(i = (i>=100) ? 0 : i + 10);
}
}));
return p;
}
private static void initProgressBar(JProgressBar progressBar) {
progressBar.setOrientation(SwingConstants.VERTICAL);
progressBar.setStringPainted(false);
progressBar.setForeground(Color.GREEN);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() { createAndShowGUI(); }
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new ProgressBarLabelTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
It is a true-Hack but if works for me:
I lookup in the Stack if UI asks for orientation while printing the label, if so I return another orientation.
JProgressBar progress = new JProgressBar(){
#Override
public int getOrientation() {
for( StackTraceElement elem : new Throwable().getStackTrace() ) {
if(elem.getMethodName().equals( "paintText" ) || (elem.getMethodName().equals( "paintString" ))) {
return JProgressBar.HORIZONTAL;
}
}
return JProgressBar.VERTICAL;
}
};
You can override paintString() in a custom BasicProgressBarUI. A related example is seen here.