JPanel in the middle of the frame - java

I'm trying to put my jpanel in the middle of the frame... so when the user try to change the size of the window frame, it remain in the middle...
something like this:
so if i change size it have to remain in the middle:
i Tried to change the layout of my contentPane with the BorderLayout and put my jpanel in the center position... but when i change size of my frame the panel go in the top left corner.
In my windows builder the situation is this:
my jpanel have to work exactly how works the redbox. i tried everything but the result is everytime the same:
this is my code:
package StudApp;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.Color;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class StudApp {
private JFrame frame;
private JPanel homeFirstRun;
private ArrayList<Corso> corsi = new ArrayList<Corso>();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new StudApp();
}
});
}
/**
* Create the frame.
*/
public StudApp() {
frame = new JFrame("Student Note");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu menuHelp = new JMenu("Help");
menuBar.add(menuHelp);
JMenuItem menuIstrStud = new JMenuItem("Intructions Student Note");
menuIstrStud.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.remove(homeFirstRun);
frame.revalidate();
frame.repaint();
homeFirstRun = null;
}
});
menuHelp.add(menuIstrStud);
homeFirstRun = new JPanel();
homeFirstRun.setBorder(new EmptyBorder(5, 5, 5, 5));
homeFirstRun.setLayout(null);
frame.getContentPane().add(homeFirstRun);
JLabel welcomeMessage = new JLabel("Welcome to Student Note");
welcomeMessage.setBounds(5, 5, 424, 18);
welcomeMessage.setForeground(Color.DARK_GRAY);
welcomeMessage.setHorizontalAlignment(SwingConstants.CENTER);
welcomeMessage.setFont(new Font("Verdana", Font.BOLD, 14));
homeFirstRun.add(welcomeMessage);
JTextArea welcomeTextArea = new JTextArea();
welcomeTextArea.setFont(new Font("Verdana", Font.PLAIN, 13));
welcomeTextArea.setText(" I think it's your first time here.\n\n"
+ " So the first step is to create a new course to\n insert your grades.\n\n"
+ " If you want my advice, read how this program\n works in the help section (it is very simple),\n "
+ "just 2 minutes ... believe me");
welcomeTextArea.setEditable(false);
welcomeTextArea.setBounds(27, 34, 381, 184);
homeFirstRun.add(welcomeTextArea);
frame.setVisible(true);
}
}

There are several ways to do this, but one of the easiest is to give the contentPane a GridBagLayout, and then add your JPanel of interest with no GridBagConstraints. If the JPanel of interest is the only thing added to this container, this will then place that JPanel into a central position.
e.g.,
import java.awt.*;
import javax.swing.*;
public class CentralPanel {
private static void createAndShowGui() {
JFrame frame = new JFrame("CentralPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new MyContentPane());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyContentPane extends JPanel {
private static final int PREF_W = 700;
private static final int PREF_H = 550;
public MyContentPane() {
setLayout(new GridBagLayout());
add(new JPanelOfInterest());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
}
class JPanelOfInterest extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
public JPanelOfInterest() {
setBorder(BorderFactory.createTitledBorder("JPanel of Interest"));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
}

Related

How to wait until JDialog is fully created

I need to calculate window decorations somehow. So I override JDialog's constructor. But when I call get_decoration_size() it sometimes returns wrong values. And my thought was: window creates later than get_decoration_size() executes(strange, because both in same thread and in same constructor). So I decided to sleep for a second, and it worked, and now decorations always valid.
My question is: is there a way to "join" to the creating process(wait until window is shown by setVisible(true))? If so, it must be something to replace unsafe_sleep(1000).
package swing.window;
import db.db;
import javax.swing.*;
import java.awt.*;
import static swing.util.*;
import static util.util.unsafe_sleep;
public class calc_decor extends JDialog {
{
//some initializations
setLayout(null);
setResizable(false);
JLabel label = new JLabel("Loading...");
add(label);
setxy(label, 3, 3);
fit(label);
setsize(this, label.getWidth() + 100, label.getHeight() + 100);
window_to_center(this);
setVisible(true);//trying to draw
unsafe_sleep(1000);//without that it looks like get_decoratoin_size()
//is called before setVisible(true)
db.sysdecor = get_decoration_size();//trying to get decorations
dispose();
}
private Dimension get_decoration_size() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
}
I had to assume a lot to create a runnable example.
Here's the result of your getDecorationSize method. The line didn't print until I closed the JDialog.
java.awt.Dimension[width=16,height=39]
And here's the code I used.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JDialogTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JDialogTest());
}
private JFrame frame;
#Override
public void run() {
frame = new JFrame("JDialog Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(
150, 100, 150, 100));
panel.setPreferredSize(new Dimension(400, 400));
JButton button = new JButton("Open JDialog");
button.addActionListener(new ButtonListener());
panel.add(button);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
new CalculateDecor(frame, "Spash Screen");
}
}
public class CalculateDecor extends JDialog {
private static final long serialVersionUID = 1L;
public CalculateDecor(JFrame frame, String title) {
super(frame, true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(title);
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(200, 200));
JLabel label = new JLabel("Loading...");
label.setHorizontalAlignment(JLabel.CENTER);
panel.add(label);
add(panel);
pack();
setLocationRelativeTo(frame);
setVisible(true);
System.out.println(getDecorationSize());
}
private Dimension getDecorationSize() {
Rectangle window = getBounds();
Rectangle content = getContentPane().getBounds();
int width = window.width - content.width;
int height = window.height - content.height;
return new Dimension(width, height);
}
}
}

How can I make the JMenuBar strape dissapear after the buttons?

How can I make the JMenuBar streak dissapear after the menuitems? I want to put a 2nd menu in the middle of the frame, and it looks weird with this streak.
I tried to set the background to Panel.background but it doesn't work.
import java.awt.*;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class SwingMenuDemo extends JPanel {
public SwingMenuDemo(){
setLayout(null);
JMenuBar menuBar = new JMenuBar();
menuBar.setBackground(UIManager.getColor("Panel.background"));
menuBar.setBounds(0, 0, 450, 25);
add(menuBar);
JButton btn1 = new JButton("Menu1");
menuBar.add(btn1);
JButton btn2 = new JButton("Menu2");
menuBar.add(btn2);
JButton btn3 = new JButton("Menu3");
menuBar.add(btn3);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("SwingMenuDemo");
frame.setPreferredSize(new Dimension(400,400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.PAGE_AXIS));
frame.getContentPane().add(new SwingMenuDemo());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If you want to create your own "menu" of several JButtons, then don't use JMenu and don't use null layout and setBounds(...) (you should avoid the latter just as a general rule). Instead nest JPanels, each using its own layout manager to allow for simple creation of complex GUI's.
For instance you could create a JPanel to hold the buttons, say called menuPanel, give it a new GridLayout(1, 0) layout, meaning it will hold a grid of components in 1 row, and a variable number of columns (that's what the 0 means). Then put your buttons in that.
Then place that JPanel into another JPanel that uses say FlowLayout.LEADING, 0, 0) as its layout -- it will push all its components to the left.
Then make the main GUI use a BorderLayout and add the above panel to it's top in the BorderLayout.PAGE_START position. For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwingMenuDemo2 extends JPanel {
private static final String[] MENU_TEXTS = {"Menu 1", "Menu 2", "Menu 3"};
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
public SwingMenuDemo2() {
JPanel menuPanel = new JPanel(new GridLayout(1, 0));
for (String menuText : MENU_TEXTS) {
menuPanel.add(new JButton(menuText));
}
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
topPanel.add(menuPanel);
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
SwingMenuDemo2 mainPanel = new SwingMenuDemo2();
JFrame frame = new JFrame("Swing Menu Demo 2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
You can do that with
menuBar.setBorderPainted(false);

Placing the JPanel in JScrollPane [duplicate]

I've got a probelm with my swing ui lately. Everything works fine,untill i trigger a tooltip from a JButton.After that moving the mouse over the rest of the ui is causing weird artifacts and glitching.
Bugged:
I can't show the whole code because its too much but here im initialising the button :
GridBagConstraints bottompane_gbc = new GridBagConstraints();
toggleTorConnectionButton = new JButton();
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
toggleTorConnectionButton.setIcon(new ImageIcon(ResourceHandler.Menueicon3_1));
toggleTorConnectionButton.setMinimumSize(new Dimension(removeFinishedDownloads.getMinimumSize().width, toggleTorConnectionButton.getIcon().getIconHeight()+5));
toggleTorConnectionButton.addActionListener(); // unimportant
bottompane_gbc.gridy = 1;
bottompane_gbc.fill = GridBagConstraints.BOTH;
bottompane_gbc.insets = new Insets(0,15,10,5);
bottompane.add(ToggleTorConnectionButton,bottompane_gbc);
this.add(bottompane,BorderLayout.PAGE_END);
If anybody needs more information to help me pls feel free to ask.Im kind of desperated. XD
EDIT:
After some tinkering im guessing that the problem is related to swing and my use of it.Currently im using alot of Eventlisteners (is this bad?), that might slow down the awt thread ?
Here is a brief extract from HPROF:
http://www.pastebucket.com/96444
EDIT 2:
I was able to recreate the error in a handy and simple example. When you move over the button,wait for the tooltip and then over the ui.You will see ghosting :(.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class Main_frame {
public static void main(String[] args) {
new Main_frame();
}
public Main_frame() {
JFrame frame = new JFrame("LOL");
frame.setFocusable(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 500));
frame.setLocationRelativeTo(null);
Download_window download_window = new Download_window();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Download", null, download_window, "Main Download Window.");
for (int i = 0; i < 5; i++) {
JPanel pane = new JPanel();
Dimension dim = new Dimension(370, 60);
pane.setPreferredSize(dim);
pane.setMaximumSize(dim);
pane.setBackground(Color.blue);
pane.setMinimumSize(dim);
download_window.jobpanel.add(pane);
}
download_window.jobpanel.repaint();
download_window.jobpanel.revalidate();
frame.add(tabbedPane);
frame.setVisible(true);
}
public class Download_window extends JPanel {
JPanel jobpanel;
public Download_window() {
this.setLayout(new BorderLayout());
jobpanel = new JPanel();
jobpanel.setLayout(new BoxLayout(jobpanel, BoxLayout.Y_AXIS));
JPanel bottompane = new JPanel();
bottompane.setPreferredSize(new Dimension(385, 40));
JButton toggleTorConnectionButton = new JButton();
toggleTorConnectionButton.setPreferredSize(new Dimension(100, 50));
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
bottompane.add(toggleTorConnectionButton);
this.add(bottompane, BorderLayout.PAGE_END);
JScrollPane jobScrollPane = new JScrollPane(jobpanel);
jobScrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(jobScrollPane, BorderLayout.CENTER);
}
}
}
Edit 3: Concerning trashgods ideas, I used the EventDispatchThread, I modified the setter to override the getter for size and i crossed out incompatibility by using trashgods code and it was working fine.... So where is the actual difference?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
public class Main_frame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Main_frame();
}
});
}
public Main_frame() {
JFrame frame = new JFrame("LOL");
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 500));
Download_window download_window = new Download_window();
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Download", null, download_window, "Main Download Window.");
frame.add(tabbedPane);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class Download_window extends JPanel {
JPanel jobpanel;
public Download_window() {
this.setLayout(new BorderLayout());
jobpanel = new JPanel();
jobpanel.setLayout(new BoxLayout(jobpanel, BoxLayout.Y_AXIS));
for (int i = 0; i < 5; i++) {
JPanel pane = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(370, 60);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(370, 60);
}
#Override
public Dimension getMinimumSize() {
return new Dimension(370, 60);
}
};
pane.setBackground(Color.blue);
jobpanel.add(pane);
}
JPanel bottompane = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(385, 40);
}
};
JButton toggleTorConnectionButton = new JButton("Button"){
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 30);
}
};
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
bottompane.add(toggleTorConnectionButton);
this.add(bottompane, BorderLayout.PAGE_END);
JScrollPane jobScrollPane = new JScrollPane(jobpanel);
jobScrollPane.getVerticalScrollBar().setUnitIncrement(16);
this.add(jobScrollPane, BorderLayout.CENTER);
}
}
}
Could anyone please verify that strange behavior himself? You just need to copy&paste the code from above in Edit3.
Your code exhibits none of the glitches shown above when run on my platform.
Verify that you have no painting problems e.g. neglecting super.paintComponent() as discussed here.
Verify that you have no driver incompatibilities, as discussed here.
Construct and modify all GUI objects on the event dispatch thread.
Don't use set[Preferred|Maximum|Minimum]Size() when you really mean to override get[Preferred|Maximum|Minimum]Size(), as discussed here. The example below overrides getPreferredSize() on the scroll pane, but you can implement Scrollable, as discussed here.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
/** #see https://stackoverflow.com/a/34319260/230513 */
public class MainFrame {
private static final int H = 64;
public static void main(String[] args) {
EventQueue.invokeLater(() -> new MainFrame());
}
public MainFrame() {
JFrame frame = new JFrame("LOL");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
for (int i = 0; i < 8; i++) {
panel.add(new DownloadPanel());
}
JScrollPane jsp = new JScrollPane(panel) {
#Override
public Dimension getPreferredSize() {
return new Dimension(6 * H, 4 * H);
}
};
tabbedPane.addTab("Download", null, jsp, "Main Download Window.");
tabbedPane.addTab("Options", null, null, "Options");
frame.add(tabbedPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class DownloadPanel extends JPanel {
JPanel jobPanel = new JPanel();
public DownloadPanel() {
this.setLayout(new BorderLayout());
this.setBackground(Color.lightGray);
JProgressBar jpb = new JProgressBar();
jpb.setIndeterminate(true);
this.add(jpb);
JPanel buttonPane = new JPanel();
JButton toggleTorConnectionButton = new JButton("Button");
toggleTorConnectionButton.setToolTipText("Toggles Tor Connection.");
buttonPane.add(toggleTorConnectionButton);
this.add(buttonPane, BorderLayout.WEST);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(4 * H, H);
}
}
}

JTabbedPane tab border removal

JTabbedPane - tab border is being shown even after using BasicTabbedPaneUI. Please let me know how can I change such that no border is shown between the tabs? Is there any method to remove the border completely ?
Please Send me the code snippet. Thanks in advance.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
public class TabbedPaneTest implements Runnable {
#Override
public void run() {
final JTabbedPane pane = new JTabbedPane();
pane.addTab("A", createTab(Color.RED));
pane.addTab("B", createTab(Color.YELLOW));
pane.addTab("C", createTab(Color.BLUE));
pane.setUI(new BasicTabbedPaneUI() {
#Override
protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex) {
}
});
pane.setBackground(Color.WHITE);
pane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
pane.setForegroundAt(pane.getSelectedIndex(), Color.GREEN);
}
});
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.pack();
//frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createTab(Color color) {
JPanel p = new JPanel(new BorderLayout()) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
};
p.setBorder(BorderFactory.createLineBorder(color, 2));
p.setBackground(Color.WHITE);
return p;
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new TabbedPaneTest());
}
}
// Remove the white line under a tab button
Insets insets = UIManager.getInsets("TabbedPane.contentBorderInsets");
insets.top = -1;
UIManager.put("TabbedPane.contentBorderInsets", insets);

Implement copy/paste in JTextArea?

I have a very simple code that creates a frame object from the class MyJFrame accepts the first string which is used as a title. Place the second string is the text to be displayed in a JScrollPane. You can see the code below. What I need is to use copy and paste of text highlighted. I need help implementing it. So that if copy selected from a menubar it copies the highlighted portion and if paste is pastes it.
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Container;
import javax.swing.JOptionPane;
public class DisplayText
{
private static JTextArea text;
public DisplayText(String title, String info)
{
MyJFrame f = new MyJFrame(title);
Container c = f.getContentPane();
//default text
text = new JTextArea(info);
//Scrollpane
JScrollPane sp = new JScrollPane(text);
c.add( sp );
f.setBounds(100,200, 500, 400 );
f.setVisible(true);
}
Use the Actions that are available in the DefaultEditorKit including DefaultEditorKit.CopyAction, DefaultEditorKit.CutAction, and DefaultEditorKit.PasteAction.
For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.text.*;
public class TestActions {
private String[] texts = {
"Hello", "Goodbye", "What the f***?", "Heck if I know", "Peace out man!"
};
private JTextArea textArea = new JTextArea(10, 30);
private Action[] textActions = { new DefaultEditorKit.CutAction(),
new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };
private JPanel mainPanel = new JPanel();
private JMenuBar menubar = new JMenuBar();
private JPopupMenu popup = new JPopupMenu();
private PopupListener popupListener = new PopupListener();
public TestActions() {
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
JMenu menu = new JMenu("Edit");
for (Action textAction : textActions) {
btnPanel.add(new JButton(textAction));
menu.add(new JMenuItem(textAction));
popup.add(new JMenuItem(textAction));
}
menubar.add(menu);
JPanel textFieldPanel = new JPanel(new GridLayout(0, 1, 5, 5));
for (String text: texts) {
JTextField textField = new JTextField(text, 15);
textField.addMouseListener(popupListener);
textFieldPanel.add(textField);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
((JTextComponent)e.getSource()).selectAll();
}
});
}
textArea.addMouseListener(popupListener);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel textFieldPanelWrapper = new JPanel(new BorderLayout());
textFieldPanelWrapper.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.add(btnPanel, BorderLayout.NORTH);
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(textFieldPanelWrapper, BorderLayout.EAST);
}
public JComponent getMainPanel() {
return mainPanel;
}
private JMenuBar getMenuBar() {
return menubar;
}
private class PopupListener extends MouseAdapter {
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());
}
}
}
private static void createAndShowGui() {
TestActions testActions = new TestActions();
JFrame frame = new JFrame("Test Actions");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(testActions.getMainPanel());
frame.setJMenuBar(testActions.getMenuBar());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
code borrowed from my answer here.
Edit
You ask in comment:
I appreciate the answer. However, could you make it a bit simpler to understand, I am fairly new to Java.
Sure, here is a simple JMenuBar that holds an edit JMenu that holds JMenuItems for copy, cut, and paste with just that code borrowed from my example. Note that as an aside, you should not setBounds on anything, you should instead set the rows and columns of your JTextArea, and that you should not use a static JTextArea, and in fact no Swing components should ever be static.
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Container;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultEditorKit;
public class DisplayText {
private JTextArea text;
private Action[] textActions = { new DefaultEditorKit.CutAction(),
new DefaultEditorKit.CopyAction(), new DefaultEditorKit.PasteAction(), };
public DisplayText(String title, String info) {
JMenu menu = new JMenu("Edit");
for (Action textAction : textActions) {
menu.add(new JMenuItem(textAction));
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
JFrame f = new JFrame(title);
f.setJMenuBar(menuBar);
Container c = f.getContentPane();
text = new JTextArea(info, 20, 50);
JScrollPane sp = new JScrollPane(text);
c.add(sp);
// f.setBounds(100,200, 500, 400 );
f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
new DisplayText("Title", "This is info text");
}
}

Categories