Is it possible to open a Jmenu on button click ? I have a button in Jtable and my requirement is that when user presses this button, a Jmenu should appear. So is this possible ?
Yes it is possible. You can by default hide the menus by menu.setVisible(false); method. And on click of button make it menu.setVisible(true);
JFrame frame = new JFrame("List of Metrics used");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ListModelExample());
frame.setSize(260, 200);
frame.setVisible(true);
First thing,these are not necessarily written in main method. And your problem of hiding menu doesn't affect by location of these lines. You can keep it as it is. Also render Jmenu at a required place only, but keep it invisible by default.
Do you want to display menuitem on a button click? Then use this code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.JButton;
public class TestFrame extends JFrame {
private JPanel contentPane;
JMenu mnFile;
JMenuItem mntmExit;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame frame = new TestFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JButton btnNewButton = new JButton("Click me");
contentPane.add(btnNewButton, BorderLayout.SOUTH);
mnFile = new JMenu("file");
menuBar.add(mnFile);
mntmExit = new JMenuItem("exit");
mnFile.add(mntmExit);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mnFile.doClick();
}
});
}
}
Related
I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}
Iam trying to build a desktop application with multiple screens inside one single JFrame.
So each button click event will take us to the separate screen with refreshed components in the screen. So far this approach is working for me but the problem I am facing is even after using ".dispose(), .repaint(), .revalidate(), .invalidate()" functions. JInternalFrame or Jpanel seems to not refresh its components.
Which works something like below gif.
Tabbed Style
I do know JtabbedPane exists but for my method JtabbedPane is not viable.
Below I am posting minified code by replicating the problem I am facing.
MainMenu.Java(file with Main Class)
package test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JInternalFrame;
public class MainMenu extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu frame = new MainMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 522);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 807, 63);
contentPane.add(panel);
panel.setLayout(new GridLayout(1, 0, 0, 0));
JButton Tab1 = new JButton("Tab1");
panel.add(Tab1);
JButton Tab2 = new JButton("Tab2");
panel.add(Tab2);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 88, 807, 387);
contentPane.add(scrollPane);
JInternalFrame internalFrame1 = new JInternalFrame();
JInternalFrame internalFrame2 = new JInternalFrame();
Tab1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel1 panel1 = new Panel1();
if(internalFrame1 !=null) {
internalFrame1.dispose();
panel1.invalidate();
panel1.revalidate();
panel1.repaint();
}
internalFrame1.setTitle("Panel 1");
scrollPane.setViewportView(internalFrame1);
internalFrame1.getContentPane().add(panel1);
internalFrame1.setVisible(true);
}
});
Tab2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel2 panel2 = new Panel2();
if(internalFrame2 !=null) {
internalFrame2.dispose();
panel2.invalidate();
panel2.revalidate();
panel2.repaint();
}
internalFrame2.setTitle("Panel 2");
scrollPane.setViewportView(internalFrame2);
internalFrame2.getContentPane().add(panel2);
internalFrame2.setVisible(true);
}
});
}
}
and the corresponding Jpanel class files where JInternal Frames
Panel1.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel1 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel1() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Example Button");
btnNewButton.setBounds(10, 156, 430, 21);
add(btnNewButton);
}
}
Panel2.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel2 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel2() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button2");
btnNewButton.setBounds(21, 157, 419, 21);
add(btnNewButton);
}
}
P.S: This is my first time asking question in Stackoverflow so forgive me and if possible guide me if i miss anything
Thank you :)
Edit:
The problem I am facing is on the surface it looks like the Jpanel has been refreshed but the components like JtextField Still hides the previously written text in it and only show the text when i click on that JTextField
Below I am Attaching another gif which show highlights the issue. I have highlighted the part where I am facing issue.
Issue I am Facing
The dispose() method does not remove components so you keep adding components to the internal frame when you use the following:
internalFrame1.getContentPane().add(panel1);
Instead you might do something like:
Container contentPane = internalFrame1.getContentPane();
contentPane.removeAll();
contentPane.add( panel1 );
contentPane.revalidate();
contentPane.repaint();
You can use the JPanels in the Jframes and then use the CardLayout to change the panel ( which could than act like the different screens )
Q1: MY JTextFeild and JMenuBar does not show up, and I don't know why
there is an picture of the program.
Q2: I have seen a lot of ways to write a program of interface, I don't know which way is better. Is this way or this way: https://www.youtube.com/watch?v=706Ye4ubtEY
import javax.swing.*;
import java.awt.*;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Real_Interface extends JFrame implements ActionListener {
public Real_Interface(){
JFrame window = new JFrame();
window.add(new JLabel("Rocket Data Visualization Tool"));
window.setTitle("Rocket Data Visualization Tool");
window.setSize(640, 480);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.setVisible(true);
window.setResizable(false);
JTextField tf = new JTextField();
tf.setText("New Text");
String str = tf.getText();
tf.setVisible(true);
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem menuItem = new JMenuItem("haha");
JMenuItem menuItem2 = new JMenuItem("haha2");
file.add(menuItem);
file.addSeparator();
file.add(menuItem2);
bar.add(file);
JButton button = new JButton("OK");
window.add(button);
button.setBounds(250, 400, 150, 40);
button.addActionListener(this);
}
public static void main(String[] args){
new Real_Interface();
}
public void actionPerformed(ActionEvent e) {
System.out.println("The Button Works!");
Plot.main(null);
}
}
A few reasons
The menubar has not been assigned to the frame
window.setJMenuBar(bar);
The textfield has not been added
window.add(textfield, BorderLayout.PAGE_START);
This component is visible by default so calling setVisible is unnecessary.
The frame needs to be made visible after all components have been added to the frame rather than beforehand
window.setVisible(true);
Your JTextField tf and JMenuBar bar aren't added to their parent (the window ?).
I'm currently writing an interface where a have a JFrame class and two JPanel classes. When the script is first executed, Panel A is shown. I have a JButton in Panel A which I would like, when clicked, to display Panel B instead of Panel A.
Is there any way I could do this?
Read tutorial for that.
You can use next() method of CardLayout for showing next card,
or you can use show(...); for showing specific card.
Simple example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Example {
public static void main(String[] args){
JFrame frame = new JFrame();
final JPanel panel = new JPanel(new CardLayout());
JLabel l1 = new JLabel("1");
JLabel l2 = new JLabel("2");
JLabel l3 = new JLabel("3");
panel.add(l1,"l1");
panel.add(l2,"l2");
panel.add(l3,"l3");
JButton btn = new JButton("next");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
CardLayout layout = (CardLayout) panel.getLayout();
layout.next(panel);
}
});
JButton btnSpec = new JButton("l3");
btnSpec.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
CardLayout layout = (CardLayout) panel.getLayout();
layout.show(panel, "l3");
}
});
frame.add(panel);
frame.add(btn,BorderLayout.SOUTH);
frame.add(btnSpec,BorderLayout.NORTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Edit - #Heuster linked another question that answers this.
I just found out about WindowBuilder and I'm making a simple chat client using it to teach myself. Right now I've got the basic chat frame done, but only some of the components that I've added are accessible in the code. Specifically, I can't access my input JTextArea, taInput. Is there something I need to do to be able to reference it (to get the text in it for sending, etc.)?
Here's a picture of the Design view:
And here's a the generated code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
public class frame extends JFrame
{
private JPanel contentPane;
private JButton btnSend;
private JTextArea taDisplay;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
frame frame = new frame();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public frame()
{
setResizable(false);
setTitle("Client");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 440, 316);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmConnect = new JMenuItem("Connect...");
mnFile.add(mntmConnect);
JMenuItem mntmSaveChatLog = new JMenuItem("Save chat log...");
mnFile.add(mntmSaveChatLog);
JMenuItem mntmSettings = new JMenuItem("Settings...");
mnFile.add(mntmSettings);
JMenuItem mntmClose = new JMenuItem("Close");
mnFile.add(mntmClose);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnView = new JMenu("View");
menuBar.add(mnView);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
btnSend = new JButton("Send");
btnSend.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0)
{
taDisplay.append("Send clicked.\n");
}
});
btnSend.setBounds(314, 197, 100, 50);
panel.add(btnSend);
taDisplay = new JTextArea();
taDisplay.setLineWrap(true);
taDisplay.setEditable(false);
taDisplay.setBounds(10, 11, 404, 180);
panel.add(taDisplay);
JScrollPane spInput = new JScrollPane();
spInput.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
spInput.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
spInput.setBounds(10, 197, 294, 49);
panel.add(spInput);
JTextArea taInput = new JTextArea();
taInput.setLineWrap(true);
spInput.setViewportView(taInput);
}
}
From the design tab you could right click on the item (taInput) then click rename on the context menu, in the diaog, at the right of the name there where 2 buttons, clic on the (f) button (field) and then ok.