How to remove indents in the tabs JTabbedPane? - java

How to remove the indents around icon tabs in JTabbedPane? i.e. what would this icon was on the full size of the tabs?

You can try next trick with getTabInsets() method of BasicTabbedPaneUI:
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
public class TestFrame extends JFrame {
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
pack();
setVisible(true);
}
private void init() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JTabbedPane pane = new JTabbedPane(JTabbedPane.BOTTOM);
pane.addTab("", new ImageIcon(TestFrame.class.getResource("1111.png")), new JLabel("lbl"));
pane.addTab("test2", new JLabel("lbl2"));
pane.setFocusable(false);
pane.setUI(new BasicTabbedPaneUI() {
#Override
protected Insets getTabInsets(int tabPlacement, int tabIndex) {
return new Insets(0, 0, 0, 0);
}
});
add(pane);
}
public static void main(String... strings) {
new TestFrame();
}
}
Also try calculateTabWidth() and calculateTabHeight().

Related

JAVA: Screenshot after JFrame change just black

I've written a program which makes a screenshot of JFrame by clicking on JMenuItem. If I only run the .java file in Eclipse, everything works and the screenshot shows the JFrame perfectly. But if I open the JFrame as a link from another JFrame, the screenshot is black instead of showing the JFrame. Here's my code:
JFrame1.java:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JFrame1 extends JFrame {
static JFrame1 frame1 = new JFrame1();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void CloseFrame(){
super.dispose();
}
public JFrame1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
JButton ok = new JButton("OK");
getContentPane().add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CloseFrame();
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
}
});
}
}
With a button (ok) I can go to JFrame2.java.
JFrame2.java:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame2.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem screen = new JMenuItem("Screenshot");
screen.addActionListener(new AbstractAction() {
#Override
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
});
file.add(screen);
menubar.add(file);
setJMenuBar(menubar);
}
public JFrame2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
createMenuBar();
}
}
If I click now on "Screenshot", it is just black.
And if I run only JFrame2.java without running JFrame1.java before, the real image is saved.
Why does the screenshot is black after going from one JFrame1 to JFrame2?
You're painting from the wrong frame...
In your first frame, you are doing this...
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
Looks pretty harmless, but, in JFrame2 you are doing this...
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
And...
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
But, frame2 (inside JFrame2) is not visible on the screen.
This is why static is evil and should be avoid. This is also why you should not extend directly from something like JFrame. You can to easily get yourself into a knot of not knowing what is actually on the screen and what you are referencing...
For example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JavaApplication254 {
public static void main(String[] args) {
new JavaApplication254();
}
public JavaApplication254() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JButton btn = new JButton("Click me away...");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TestPane testPane = new TestPane();
SnapshotAction snapshotAction = new SnapshotAction(testPane);
JMenuBar mb = new JMenuBar();
JMenu mnuFile = new JMenu("File");
mnuFile.add(snapshotAction);
mb.add(mnuFile);
JFrame frame = new JFrame("More Testing");
frame.setJMenuBar(mb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(testPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(20, 20, 20, 20));
JLabel label = new JLabel("I be a bananan");
label.setOpaque(true);
label.setBackground(Color.YELLOW);
label.setForeground(Color.RED);
label.setBorder(
new CompoundBorder(
new LineBorder(Color.RED),
new EmptyBorder(20, 20, 20, 20)));
setLayout(new GridBagLayout());
add(label);
}
}
public class SnapshotAction extends AbstractAction {
private JComponent parent;
public SnapshotAction(JComponent parent) {
this.parent = parent;
putValue(NAME, "Take Snapshot...");
}
#Override
public void actionPerformed(ActionEvent e) {
if (parent.isDisplayable()) {
BufferedImage img = new BufferedImage(parent.getWidth(), parent.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
parent.printAll(g2d);
g2d.dispose();
try {
ImageIO.write(img, "png", new File("Snapshot.png"));
Toolkit.getDefaultToolkit().beep();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(parent, "Failed to generate snapshot: " + ex.getMessage());
}
}
}
}
}
Which will output...

Transparent JTexfield with background image

I wanted to know how to set an image to a JTextField if this is transparent, or how to make my JTextField look like this:
Here's how I make my field transparent, but I can't set its background image:
//Step 1: Remove the border line to make it look like a flat surface.
field.setBorder(BorderFactory.createLineBorder(Color.white, 0));
//Step 2: Set the background color to null to remove the background.
field.setBackground(null);
All Swing components have a concept of transparency, which is controlled via the use of opaque property. Setting the background to null tents to rest the background color of the field to it's UI default.
Having said that, some components can ignore this (partially or completely). In these case we can cheat...
In the following example, set the field transparent via the opaque property, this is important, as the RepaintManager will not paint areas behind components unless they are transparent, and use a fully transparent background color.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
field.setBackground(new Color(0, 0, 0, 0));
field.setOpaque(false);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.RED);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Updated based on comments...
This is a very specific example designed to provide a direct answer to the presented problem. Basically, what this does is creates a custom border and uses an Image to render the "border"
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;
import javax.swing.border.MatteBorder;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
try {
BufferedImage img = ImageIO.read(getClass().getResource("/FieldBorder.png"));
field.setBorder(new ImageBorder(img, 8, 6));
} catch (IOException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImageBorder implements Border {
private BufferedImage img;
private int bottomMargin;
private int leftMargin;
public ImageBorder(BufferedImage img, int leftMargin, int bottomMargin) {
this.img = img;
this.bottomMargin = bottomMargin;
this.leftMargin = leftMargin;
}
#Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.drawImage(img, x, y + height - img.getHeight(), c);
}
#Override
public Insets getBorderInsets(Component c) {
return new Insets(0, leftMargin, bottomMargin, 0);
}
#Override
public boolean isBorderOpaque() {
return false;
}
}
}
Now, this could also be done using custom painting within the custom Border instead, but was quicker this way ;)
Another option...
Is to simply use a JPanel and add the field and a JLabel holding the border outline together, for example...
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
public class TestTextField {
public static void main(String[] args) {
new TestTextField();
}
public TestTextField() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(20);
field.setBorder(null);
JPanel fieldPane = new JPanel(new GridBagLayout());
fieldPane.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 8, 0, 0);
fieldPane.add(field, gbc);
try {
BufferedImage img = ImageIO.read(getClass().getResource("/FieldBorder.png"));
gbc.insets = new Insets(0, 0, 0, 0);
fieldPane.add(new JLabel(new ImageIcon(img)), gbc);
} catch (IOException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(fieldPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
But this will come down to needs and requirements...
Text field with a background
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.Document;
public class TextFieldBackground {
public static void main(String[] args) {
new TextFieldBackground();
}
public TextFieldBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
TextFieldWithBackground field = new TextFieldWithBackground(40);
try {
field.setBackgroundImage(ImageIO.read(getClass().getResource("/clouds.jpg")));
} catch (IOException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TextFieldWithBackground extends JTextField {
private BufferedImage bg;
public TextFieldWithBackground() {
}
public TextFieldWithBackground(String text) {
super(text);
}
public TextFieldWithBackground(int columns) {
super(columns);
}
public TextFieldWithBackground(String text, int columns) {
super(text, columns);
}
public TextFieldWithBackground(Document doc, String text, int columns) {
super(doc, text, columns);
}
public void setBackgroundImage(BufferedImage bg) {
this.bg = bg;
setOpaque(bg == null);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
if (bg != null) {
int x = 0;
int y = (getHeight() - bg.getHeight()) / 2;
while (x < getWidth()) {
g.drawImage(bg, x, y, this);
x += bg.getWidth();
}
}
super.paintComponent(g);
}
}
}

Difference between LookAndFeel behavior

I created a JPopupmenu and i added a JTextField. When I am using metal or nimbus everything is alright. The problem is when I switch LookAndFeel to Windows. I can not press right ALT, because if I press this key, JPopupmenu will hide.
Can I use right ALT to write national signs in Windows LookAndFeel?
import javax.swing.*;
import java.awt.event.*;
public class Popup extends JFrame {
JPopupMenu popup;
JPanel panel;
JTextField field;
public Popup(){
setSize(500,400);
try {
//UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(this);
popup = new JPopupMenu();
field = new JTextField(10);
popup.add(field);
JButton button = new JButton("Options");
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
panel = new JPanel();
panel.add(button);
add(panel);
}
public static void main(String[] args){
Popup pop = new Popup();
pop.setVisible(true);
}
}
JPopupMenu has a very specific set of operation requirements, and yes, they do change between look and feels, that's kind of the point.
What you could do is create you own popup using an undecorated JFrame. The trick here is to mimic as much of the popup as need, for example, auto closer when another component gains focus, the ability to dismiss the popup with the escape key...etc...
This is just a quick example to provide a proof of concept, I'd personally also add a key binding for the escape key, some kind of listener interface to allow the search pane to request that the popup be dismissed and the ability to auto focus some component when the window was made visible, but that's just me...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestPopup {
public static void main(String[] args) {
new TestPopup();
}
public TestPopup() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton show;
public TestPane() {
setLayout(new GridBagLayout());
show = new JButton("...");
show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PopupWindow window = new PopupWindow();
window.show(show, 0, show.getHeight());
}
});
add(show);
}
}
public class SearchPane extends JPanel {
private JList list;
private JTextField search;
public SearchPane() {
setLayout(new BorderLayout());
list = new JList();
list.setPrototypeCellValue("This is just a test");
list.setVisibleRowCount(20);
search = new JTextField(10);
add(new JScrollPane(list));
add(search, BorderLayout.SOUTH);
}
}
public class PopupWindow extends JFrame {
private SearchPane searchPane;
public PopupWindow() {
setUndecorated(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowFocusListener(new WindowFocusListener() {
#Override
public void windowGainedFocus(WindowEvent e) {
}
#Override
public void windowLostFocus(WindowEvent e) {
dispose();
}
});
searchPane = new SearchPane();
add(searchPane);
pack();
}
public void show(JComponent parent, int x, int y) {
Point point = new Point(x, y);
SwingUtilities.convertPointToScreen(point, parent);
setLocation(point);
setVisible(true);
}
}
}

Get selected element's location in JList

Is it possible to get location of selected element in JList? I would like to get it to place JFrame just below clicked option.
You'll want to use JList#getCellBounds
int selectedIndex = list.getSelectedIndex();
Rectangle bounds = list.getSelectedBounds(selectedIndex, selectedIndex);
This will give you the location of the selected item within context to the JList, you'll need to translate this to screen space...
Point p = bounds.getLocation();
SwingUtilities.convertPointToScreen(p, list);
You may also want to take a look at The Use of Multiple JFrames: Good or Bad Practice?
For example...
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class List {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new List();
}
public List() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
final JFrame selected = new JFrame("Selected");
selected.add(new JLabel("Here I am"));
selected.pack();
DefaultListModel model = new DefaultListModel();
for (int index = 0; index < 1000; index++) {
model.addElement("#" + index);
}
final JList list = new JList(model);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int index = list.getSelectedIndex();
Rectangle bounds = list.getCellBounds(index, index);
Point p = bounds.getLocation();
p.y += bounds.height;
SwingUtilities.convertPointToScreen(p, list);
p.x -= selected.getWidth();
selected.setLocation(p);
selected.setVisible(true);
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(list));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You can use indexToLocation() method of JList, for example:
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class TestFrame extends JFrame {
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
pack();
setVisible(true);
}
private void init() {
final JPopupMenu menu = new JPopupMenu("test");
menu.add(new JMenuItem("1"));
final JList<String> list = new JList<String>(new String[]{"1","2","3"});
list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int selectedIndex = list.getSelectedIndex();
if(selectedIndex != -1){
Point indexToLocation = list.indexToLocation(selectedIndex);
Rectangle cellBounds = list.getCellBounds(selectedIndex, selectedIndex);
menu.show(list, indexToLocation.x, indexToLocation.y+cellBounds.height);
}
}
});
add(list);
}
public static void main(String... strings) {
new TestFrame();
}
}

How to highlight all the text in a JTextPane?

jTextPane1.selectAll();
With the correctly shared events, that command permit to highlight the text in a JTextPane area (I am a bit rusty, I need to not forget to share the "good event focus priorities" ; thank you to : MadProgrammer)
Since selectAll is a method of JTextComponent, which JTextPane extends from I would take a wild guess and say, probably, yes.
Five minutes of coding probably would have gotten you the same answer yourself...
Highlighting not seem to appear in the jTextPane area (note : I use Java 7)
This is likely because the JTextPane doesn't have focus, try using requestFocusInWindow to bring keyboard focus back to the JTextPane.
The JTextComponents don't always render selection highlighting when they don't have focus.
For example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextPane {
public static void main(String[] args) {
new TestTextPane();
}
public TestTextPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JTextPane tp = new JTextPane();
JButton withFocus = new JButton("Select with focus");
withFocus.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tp.selectAll();
tp.requestFocus();
}
});
JButton withOutFocus = new JButton("Select without focus");
withFocus.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tp.selectAll();
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(tp));
JPanel panel = new JPanel();
panel.add(withFocus);
panel.add(withOutFocus);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You could also test it by using
textPane.selectAll();
System.out.println(textPane.getSelectedText());
For example...
And now with double clicking
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTextPane {
public static void main(String[] args) {
new TestTextPane();
}
public TestTextPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JTextPane tp = new JTextPane();
JButton withFocus = new JButton("Select with focus");
tp.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(e)) {
tp.selectAll();
}
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(tp));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Categories

Resources