Using a Key to stop a timer outside of the jframe - java

So I'm making a simple AutoClicker just to test myself. Now I've ran into a small problem. I am trying to make it so when I use "control + minus" it stops the auto clicker. Problem is I have to have the jframe focused to do so. Is there any way I get the key the user touched outside of the jframe?
For example: Your playing cookie clicker and you hit "control and =" to start the auto clicker, then you can stop it while playing cookie clicker by doing "control and +"
My Listener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "exit") {
GUIs.frame.dispose();
AutoClicker.getTimer().cancel();
} else if(e.getActionCommand() == "start") {
} else if(e.getActionCommand() == "stop") {
AutoClicker.getTimer().cancel();
}
}
}
My GUI:
import java.awt.Event;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class GUIs
{
public static JFrame frame = new JFrame("AutoClicker");
private JPanel panel = new JPanel();
private GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
private int width = gd.getDisplayMode().getWidth();
private int height = gd.getDisplayMode().getHeight();
//Componenets
private static JButton startbutton = new JButton("Start");
private static JLabel autoclick = new JLabel("AutoClicker 2.0");
public void createMainGui() {
//frame
frame.setSize(width/2,height/2);
frame.setResizable(true);
frame.setLocation(width/4, height/4);
//JPanel
panel.setLayout(null);
panel.setSize(frame.getWidth(), frame.getHeight());
//JMenu -> Different method
createJMenu(frame);
//Initialize Components
//startbutton.setBounds((frame.getWidth() / 2), (frame.getHeight()), 100, 25);
//Add components
panel.add(startbutton);
frame.add(panel);
//show frame
frame.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
System.out.println(e);
resizeComponents(frame);
}
});
frame.setVisible(true);
}
public static void createJMenu(JFrame fr) {
//Menu Bar
JMenuBar jbar = new JMenuBar();
//Listener -> different class
JListener l = new JListener();
//Exit Menu
JMenu exitmenu = new JMenu("Exit");
jbar.add(exitmenu);
//Exit Item
JMenuItem exit = new JMenuItem("Exit");
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK));
exit.setActionCommand("exit");
exit.addActionListener(l);
exitmenu.add(exit);
//Options Menu
JMenu optionsmenu = new JMenu("Options");
jbar.add(optionsmenu);
//Start Item
JMenuItem start = new JMenuItem("Start");
start.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, Event.CTRL_MASK));
start.setActionCommand("start");
start.addActionListener(l);
optionsmenu.add(start);
//Stop Item
JMenuItem stop = new JMenuItem("Stop");
stop.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, Event.CTRL_MASK));
stop.setActionCommand("stop");
stop.addActionListener(l);
optionsmenu.add(stop);
//set JMenu to frame
fr.setJMenuBar(jbar);
}
public void resizeComponents(JFrame frame) {
System.out.println(frame.getHeight());
startbutton.setBounds((frame.getWidth() / 2) - 50, (int) (frame.getHeight() / 1.5), 100, 25);
frame.revalidate();
frame.repaint();
}
}
Thank you!

Related

open another class with an action listener

Hi im currently working on a program but I need to be able to change the class (so that the frame changes) with just the click of a menu tab.
I would like someone to modify this to get my to class2.java
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
}
}
class 1.java
/*import needed packages*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JFormattedTextField;
import javax.swing.AbstractAction;
import javax.swing.SwingConstants;
import javax.swing.Action;
import javax.swing.InputVerifier;
import javax.swing.*;
import javax.xml.soap.Text;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Frame;
import java.math.*;
import java.lang.*;
import java.text.*;
import java.awt.EventQueue;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
#SuppressWarnings("unused")
public class circle_ac {
private JFrame frame;
private JTextField txtRadius;
private JTextField txtTheAreaOf;
private JTextField txtTheCircumfrenceOf;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
circle_ac window = new circle_ac();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public circle_ac() {
initialize();
}
/**
* Initialize the contents of the frame.
* #param arg0
* #param arg0
* #param arg0
*/
private void initialize() {
/*setup the JFrame*/
frame = new JFrame();
frame.setResizable(true);
frame.setBounds(1000, 1000, 2250, 1000);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.CENTER,new JLabel("MHMB 1.3.5"));
/*setup JMenu*/
Font f = new Font("sans-serif", Font.PLAIN, 25);
UIManager.put("Menu.font", f);
UIManager.put("MenuItem.font", f);
JMenuBar menu = new JMenuBar ();
frame.setJMenuBar(menu);
JMenu circles = new JMenu ("Circles");
menu.add(circles);
JMenuItem ac= new JMenuItem("Area And Circumference");
circles.add(ac);
JMenu measurements = new JMenu ("Measurements");
menu.add(measurements);
JMenuItem convert= new JMenuItem ("Convertions");
measurements.add(convert);
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,frame1);
this.revalidate();
this.repaint();
}
}
JMenu close = new JMenu ("Close");
menu.add(close);
JMenuItem exit = new JMenuItem ("Exit");
close.add(exit);
class eaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new eaction());
/*setup calculate button*/
JButton btnCalculate = new JButton("calculate");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
/*setup calculations*/
double rad;
double ans1;
double ans2;
double pi=3.1415926535897932384626433832795;
try {
rad=Double.parseDouble(txtRadius.getText()) ;
ans1= pi*(rad*rad);
ans2= 2*pi*rad;
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(25);
txtTheAreaOf.setText("The Area Is "+df.format(ans1));
txtTheCircumfrenceOf.setText("The Circumference Is "+df.format(ans2) );
/*setup error message*/
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Please Enter Valid Radius");
}
}
});
/*initialize calculate button*/
btnCalculate.setFont(new Font("Tahoma", Font.PLAIN, 60));
btnCalculate.setBackground(new Color(227, 227, 227));
btnCalculate.setForeground(Color.BLACK);
frame.getContentPane().add(btnCalculate, BorderLayout.SOUTH);
/*setup Radius text box*/
txtRadius = new JTextField();
txtRadius.setFont(new Font("Tahoma", Font.PLAIN, 55));
txtRadius.setCursor(null);
txtRadius.setInputVerifier(null);
txtRadius.setText(" Enter The Radius");
txtRadius.setBackground(SystemColor.controlHighlight);
frame.getContentPane().add(txtRadius, BorderLayout.CENTER);
txtRadius.setColumns(10);
/*setup Area text box*/
txtTheAreaOf = new JTextField();
txtTheAreaOf.setEditable(false);
txtTheAreaOf.setText("The Area Of The Circle Is ");
txtTheAreaOf.setBackground(SystemColor.control);
txtTheAreaOf.setFont(new Font("Tahoma", Font.PLAIN, 30));
frame.getContentPane().add(txtTheAreaOf, BorderLayout.WEST);
/*setup Circumference text box*/
txtTheCircumfrenceOf =new JTextField();
txtTheAreaOf.setEditable(false);
txtTheCircumfrenceOf.setFont(new Font("Tahoma", Font.PLAIN, 30));
txtTheCircumfrenceOf.setText("The Circumfrence Of The Circle Is ");
txtTheCircumfrenceOf.setBackground(SystemColor.control);
frame.getContentPane().add((Component) txtTheCircumfrenceOf, BorderLayout.EAST);
}
}
class2.java
/*import needed packages*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.JTextField;
import javax.swing.JFormattedTextField;
import javax.swing.AbstractAction;
import javax.swing.SwingConstants;
import javax.swing.Action;
import javax.swing.InputVerifier;
import javax.swing.*;
import javax.xml.soap.Text;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import java.awt.Font;
import java.awt.Frame;
import java.math.*;
import java.lang.*;
import java.text.*;
import java.awt.EventQueue;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
#SuppressWarnings("unused")
public class area_c {
private JFrame frame1;
private JTextField txtRadius;
private JTextField txtTheAreaOf;
private JTextField txtTheCircumfrenceOf;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
area_c window = new area_c();
window.frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public area_c() {
initialize();
}
/**
* Initialize the contents of the frame.
* #param arg0
* #param arg0
* #param arg0
*/
private void initialize() {
/*setup the JFrame*/
frame1 = new JFrame();
frame1.setResizable(true);
frame1.setBounds(1000, 1000, 2250, 1000);
frame1.pack();
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
frame1.add(BorderLayout.CENTER,new JLabel("MHMB 1.3.5"));
/*setup JMenu*/
Font f = new Font("sans-serif", Font.PLAIN, 25);
UIManager.put("Menu.font", f);
UIManager.put("MenuItem.font", f);
JMenuBar menu = new JMenuBar ();
frame1.setJMenuBar(menu);
JMenu circles = new JMenu ("Circles");
menu.add(circles);
JMenuItem ac= new JMenuItem("Area And Circumference");
circles.add(ac);
JMenu measurements = new JMenu ("Measurements");
menu.add(measurements);
JMenuItem convert= new JMenuItem ("Convertions");
measurements.add(convert);
JMenu area = new JMenu ("Area");
menu.add(area);
JMenuItem convertA= new JMenuItem ("Convertions");
area.add(convertA);
class aaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
}
}
JMenu close = new JMenu ("Close");
menu.add(close);
JMenuItem exit = new JMenuItem ("Exit");
close.add(exit);
class eaction implements ActionListener{
public void actionPerformed (ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new eaction());
System.out.println("Hello World!");
I need the menu tab to change it from class1.java to class2.java with an action listener.
is this possible, if so how do I do it.
I recommend to implement your two classes as JPanels. Then you can add these JPanels to your JFrame. Have a look at this small example, that shows the principle in a short and quick way. Hope it helps:
package test;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class TestFrame extends JFrame {
private Container contentPane;
private JPanel panel1,panel2;
public TestFrame() {
super("Test");
this.setJMenuBar(menubar());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = this.getContentPane();
createPanels();
contentPane.setLayout(new BorderLayout());
this.add(BorderLayout.CENTER,panel1);
this.pack();
this.setVisible(true);
}
private JMenuBar menubar() {
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem m1 =new JMenuItem("Selection 1");
JMenuItem m2 =new JMenuItem("Selection 2");
m1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel1);
refresh();
}
});
m2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel2);
refresh();
}
});
fileMenu.add(m1);
fileMenu.add(m2);
menubar.add(fileMenu);
return menubar;
}
private void refresh() {
this.revalidate();
this.repaint();
}
private void createPanels() {
panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(BorderLayout.CENTER,new JLabel("Hello World"));
panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
panel2.add(BorderLayout.CENTER,new JLabel("Goodbye World"));
}
public static void main(String[] args) {
TestFrame t = new TestFrame();
}
}
In most of the IDE's, when you right-click on the Button in the Design(GUI) pane, you can travel through:
Events -> Actions -> actionPerformed().
When you are in one frame, you can set it's visibility off to hide it, like this:
this.setVisible(false);
And you can create the object of another class (of the other frame where you want to redirect) and set it's visibility on to display it, like this:
area_c of = new area_c();
of.setVisible(true);
So, you will be transitioning from one class to another of different frames.
You can achieve the same using the object of JMenuItem object:
class1 = new JPanel();
class1.setLayout(new BorderLayout());
class1.add(BorderLayout.CENTER,new JLabel("Label_Name"));
class2 = new JPanel();
class2.setLayout(new BorderLayout());
class2.add(BorderLayout.CENTER,new JLabel("Label_Name"));
JMenuItem JMenuItemObject1 =new JMenuItem("Class 1");
JMenuItem JMenuItemObject2 =new JMenuItem("Class 2");
JMenuItemObject1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel1);
this.revalidate();
this.repaint();
}
});
JMenuItemObject2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.removeAll();
contentPane.setLayout(new BorderLayout());
contentPane.add(BorderLayout.CENTER,panel2);
this.revalidate();
this.repaint();
}
});
area.add(JMenuItemObject1);
area.add(JMenuItemObject2);
menubar.add(area);

How can I have a writable text box?

Using pure java, I would like to have a player press a JButton, have a text box pop up which they can type in, and then have a certain action happen when the player presses "Enter".
How could I do this?
I have not yet attempted this because I do not know where to start, however my current code is
package Joehot200;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main extends JFrame {
static boolean start = false;
private JPanel contentPane;
/**
* Launch the application.
*/
static Main frame = null;
String version = "0.4";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Main();
frame.setVisible(true);
frame.setTitle("Privateers");
} catch (Exception e) {
e.printStackTrace();
}
}
});
TerrainDemo.startGame();
}
boolean cantConnect = false;
/**
* Create the frame.
*/
public Main() {
setExtendedState(JFrame.MAXIMIZED_BOTH);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
final JButton btnEnterBattlefield = new JButton("Enter battlefield!");
btnEnterBattlefield.setForeground(Color.red);
//btnEnterBattlefield.setBackground(Color.green);
//btnEnterBattlefield.setOpaque(true);
menuBar.add(btnEnterBattlefield);
btnEnterBattlefield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println(new File(System.getProperty("user.dir") + "res/images/heightmap.bmp").getAbsolutePath());
//System.out.println("You clicked the button");
if (cantConnect){
btnEnterBattlefield.setText("Unable to connect to the server!");
}else{
btnEnterBattlefield.setText("Connecting to server...");
}
start = true;
}
});
//JMenu mnLogIn = new JMenu("Log in");
JMenu mnLogIn = new JMenu("Currently useless button");
mnLogIn.setForeground(Color.magenta);
menuBar.add(mnLogIn);
JButton btnLogIntoGame = new JButton("Log into game.");
mnLogIn.add(btnLogIntoGame);
JButton btnRegisterNewAccount = new JButton("Register new account");
mnLogIn.add(btnRegisterNewAccount);
final JButton btnGoToWebsite = new JButton("We currently do not but soon will have a website.");
btnGoToWebsite.setForeground(Color.BLUE);
//btnGoToWebsite = new JButton("Go to website.");
btnGoToWebsite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("Going to website!");
try {
java.awt.Desktop.getDesktop().browse(new URI("www.endcraft.net/none"));
} catch (Exception e1) {
btnGoToWebsite.setText("Error going to website!");
}
}
});
menuBar.add(btnGoToWebsite);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
FlowLayout flowLayout = (FlowLayout) contentPane.getLayout();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
ImageIcon icon = new ImageIcon(System.getProperty("user.dir") + "/res/background.png");
Image img = icon.getImage() ;
Image newimg = img.getScaledInstance(this.getWidth()*3, this.getHeight()*3, java.awt.Image.SCALE_SMOOTH ) ;
icon = new ImageIcon( newimg );
JLabel background=new JLabel(icon);
getContentPane().add(background);
background.setLayout(new FlowLayout());
//JProgressBar progressBar = new JProgressBar();
//contentPane.add(progressBar);
//JMenu mnWelcomeToA = new JMenu("Welcome to a pirate game!");
//contentPane.add(mnWelcomeToA);
//JButton btnStartGame = new JButton("Start game");
//mnWelcomeToA.add(btnStartGame);
//JSplitPane splitPane = new JSplitPane();
//mnWelcomeToA.add(splitPane);
//JButton btnRegister = new JButton("Register");
//splitPane.setLeftComponent(btnRegister);
//JButton btnLogin = new JButton("Login");
//splitPane.setRightComponent(btnLogin);
}
}
It is the "Register account" and "Log into game" button that I would like to have the above described action happen on.
Would be great if someone could tell me how to do this.
If you decide to implement a new frame (not best practice), with a new panel, and the JTextField or JTextArea within, you must bind a listener to the button that calls setVisible() on the newly created frame..
For example:
public void actionPerformed(ActionEvent e) {
yourFrame.setVisible(true);
}
Further, you could create the frame everytime the button is clicked, within the actionPerformed method aswell, however this is also not best practice..
A better alternative may be to implement a JOptionPane, see here or here..

Set size on component in JPanel

I am new for Java. I have searched how to set the size of the JTextField and JButton, but I still cannot make it work. Hope someone tell me how to solve it. I declare the height and width, but the component seems doesn't take it. The JTextField and JButton with red & yellow background should be same height. Also the JTextField width is very long.
There is my code:
package MyPackage;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.*;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.*;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.ComponentOrientation;
import javax.swing.JTextField;
public class MainForm extends JFrame implements ActionListener {
private PDFNotesBean PDFNotesBean = null;
private JMenuItem cascade = new JMenuItem("Cascade");
private int numInterFrame=0;
private JDesktopPane desktop=null;
private ArrayList<File> fileList=new ArrayList<File>();
private static int categoryButtonWidth= 40;
private static int categoryTextFieldWidth=60;
private static int categoryHight=40;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
new MainForm();
}
});
}
public MainForm(){
super("Example");
//it is equal to this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
//menuBar.add(menuWindow);
setJMenuBar(menuBar);
this.setMinimumSize(new Dimension(400, 500));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
desktop = new JDesktopPane();
this.setLayout(new BorderLayout());
setCategoryPanel();
this.add(desktop, BorderLayout.CENTER);
setVisible(true);
}
private void setCategoryPanel(){
//set the color label category
JPanel panelCategory=new JPanel();
panelCategory.setLayout(new BoxLayout(panelCategory, BoxLayout.LINE_AXIS));
JButton btnCategory_1=new JButton("");
btnCategory_1.setPreferredSize(new Dimension ( categoryButtonWidth, categoryHight));
btnCategory_1.setBackground(Color.red);
btnCategory_1.addActionListener(this);
panelCategory.add(btnCategory_1);
JTextField txtCategory_1 = new JTextField();
txtCategory_1.setPreferredSize(new Dimension (categoryTextFieldWidth, categoryHight));
panelCategory.add(txtCategory_1);
JButton btnCategory_2=new JButton("");
btnCategory_2.setPreferredSize(new Dimension ( categoryButtonWidth, categoryHight));
btnCategory_2.setBackground(Color.YELLOW);
btnCategory_2.addActionListener(this);
panelCategory.add(btnCategory_2);
JTextField txtCategory_2 = new JTextField( );
txtCategory_1.setPreferredSize(new Dimension (categoryTextFieldWidth, categoryHight));
panelCategory.add(txtCategory_2);
this.add(panelCategory, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit")) {
System.exit(0);
} else if (command.equals("Open")) {
// Open menu item action
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(MainForm.this);
if (returnVal == fileChooser.APPROVE_OPTION) {
numInterFrame=numInterFrame+1;
File file = fileChooser.getSelectedFile();
fileList.add(file);
AddNote(file);
// Load file
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
}
else if (command.equals("Save")) {
// Save menu item action
System.out.println("Save menu item clicked");
}
}
private JMenuItem makeMenuItem(String name) {
JMenuItem m = new JMenuItem(name);
m.addActionListener(this);
return m;
}
private void AddNote(File file){
JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation"
+ file.getName(), true, true, true, true);
internalFrame.setBounds(0, 0, 600, 100);
desktop.add(internalFrame);
PDFPanel p=new PDFPanel();
JPanel e =p.getJPanel(file);
internalFrame.add(e, BorderLayout.CENTER);
internalFrame.setVisible(true);
this.add(desktop, BorderLayout.CENTER);
//resize the internal frame as full screen
Dimension size = desktop.getSize();
int w = size.width ;
int h = size.height ;
int x=0;
int y=0;
desktop.getDesktopManager().resizeFrame(internalFrame, x, y, w, h);
}
}
Don't use the setPreferredSize() method.
All Swing components will have a preferred size.
For a JTextField you can use:
JTextField textField = new JTextField(5);
to indication how many characters you want to display at one time.
For the JButton, the width is determined by the text you add to the button.
When you use a BoxLayout, the width of the components is increased to fill the available space.
Just use a FlowLayout (which is the default for a JPanel) and the components will be displayed at their preferred sizes.

Update JFrame contents

How can I update the contents of a JFrame at a button click. I am building a image viewer where a list of photopath will be passed in and the user will have to click on the next or previous button to go back and forth and see the images. How can change the images and update the Jframe Below is my current implementation. I tried to dispose of the current frame and make a new one but that is not what I am looking for...
package cs213.photoAlbum.simpleview;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import model.photoNode;
public class ImageViewer {
private JFrame frame = new JFrame("Image Viewer");
private Container pane = frame.getContentPane();
private JPanel imgViewPanel = new JPanel();
JSlider slider = new JSlider(0, 100, 100);
JLabel percent = new JLabel("100%");
String imageFile = "";
private class ImageView extends JScrollPane {
JPanel panel = new JPanel();
Dimension originalSize = new Dimension();
Image originalImage;
JLabel iconLabel;
public ImageView(ImageIcon icon) {
this.originalImage = icon.getImage();
panel.setLayout(new BorderLayout());
iconLabel = new JLabel(icon);
panel.add(iconLabel);
setViewportView(panel);
originalSize.width = icon.getIconWidth();
originalSize.height = icon.getIconHeight();
}
public void update() {
int min = slider.getMinimum();
int max = slider.getMaximum();
int span = max - min;
int value = slider.getValue();
double multiplier = (double) value / span;
multiplier = multiplier == 0.0 ? 0.01 : multiplier;
Image scaled = originalImage.getScaledInstance((int) (originalSize.width * multiplier), (int) (originalSize.height * multiplier), Image.SCALE_FAST);
iconLabel.setIcon(new ImageIcon(scaled));
}
}
ImageView imageView;
public ImageViewer(String imgFile, final ArrayList<photoNode> list) {
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
});
createAndShowGUI();
imageFile = imgFile;
ImageIcon icon = new ImageIcon(imageFile);
imageView = new ImageView(icon);
JPanel panel = new JPanel();
panel.add(new JLabel("Set Image Size: "));
panel.add(slider);
panel.add(percent);
pane.add(panel, BorderLayout.NORTH);
imgViewPanel.add(imageView);
pane.add(imgViewPanel, BorderLayout.CENTER);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (!slider.getValueIsAdjusting()) {
percent.setText(slider.getValue() + "%");
imageView.update();
}
}
});
JButton next = new JButton("Next");
JButton prev = new JButton("Prev");
pane.add(next, BorderLayout.EAST);
pane.add(prev, BorderLayout.WEST);
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
imgViewPanel.remove(imageView);
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).fileName.equalsIgnoreCase(imageFile)) {
if (i + 1 < list.size()) {
//frame.dispose();
ImageIcon icon = new ImageIcon(list.get(i + 1).fileName);
ImageView imageView = new ImageView(icon);
imgViewPanel.add(imageView);
pane.add(imgViewPanel, BorderLayout.CENTER);
imgViewPanel.revalidate();
break;
}
}
}
}
}
});
}
private void createAndShowGUI() { // Creating the GUI...
frame.getContentPane().setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setTitle("PhotoAlbum55");
frame.pack();
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setResizable(true);
frame.setVisible(true);
}
}
The easiest way to swap images is to display them as ImageIcons in a JLabel and simply call setIcon(...) on the JLabel passing in another ImageIcon. If the images are small enough, you could create a collection of icons, perhaps a List<Icon>, and then move backwards or forwards through the list on next or previous button press.

Is the area too small for JPopupMenu?

In the last question I was asking the community why my JPopupMenu did not appear on the screen.
I was unable to come up with a simple , runnable, compilable example.
So, here is what I did for you guys:
Is the area too small to draw a popup?
I want my popup to be like this:
The code of what I did is visible in the first photo.
Code:
/* The old code entered here has been removed */
Complete code can be found here
edit 2
I copied the various JRadioButtonMenuItem and the setupJPopup() into a new file and ran. It works. Why doesn't it work in ScreenRecorder class?
Code
package demo;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class PopupTrial {
public PopupTrial(){
setupJPopup();
JFrame frame = new JFrame();
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){
}
frame.getContentPane().add(label);
label.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
frame.setVisible(true);
frame.setSize(300, 300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
new PopupTrial();
}
});
}
public void setupJPopup(){
encodingGroup.add(avi);
encodingGroup.add(quicktime);
popup.add(avi);
popup.add(quicktime);
popup.addSeparator();
recordingAreaGroup.add(entireScreen);
recordingAreaGroup.add(custom);
popup.add(entireScreen);
popup.add(custom);
popup.addSeparator();
cursorGroup.add(selectBlackCursor);
cursorGroup.add(selectWhiteCursor);
cursorGroup.add(selectNoCursor);
selectCursor.add(selectBlackCursor);
selectCursor.add(selectWhiteCursor);
selectCursor.add(selectNoCursor);
popup.add(selectCursor);
popup.pack();
}
JLabel label = new JLabel("Click Me");
ButtonGroup recordingAreaGroup = new ButtonGroup();
ButtonGroup cursorGroup = new ButtonGroup();
ButtonGroup encodingGroup = new ButtonGroup();
JPopupMenu popup = new JPopupMenu();
JRadioButtonMenuItem avi = new JRadioButtonMenuItem("AVI",true);
JRadioButtonMenuItem quicktime = new JRadioButtonMenuItem("QuickTime",false);
JRadioButtonMenuItem entireScreen = new JRadioButtonMenuItem("Entire Screen",true);
JRadioButtonMenuItem custom = new JRadioButtonMenuItem("Custom...",false);
JMenuItem selectCursor = new JMenu("Select a cursor");
JRadioButtonMenuItem selectWhiteCursor = new JRadioButtonMenuItem("White Cursor",true);
JRadioButtonMenuItem selectBlackCursor = new JRadioButtonMenuItem("Black Cursor",false);
JRadioButtonMenuItem selectNoCursor = new JRadioButtonMenuItem("No Cursor",false);
}
No, the size of the JFrame isn't related to why the PopupMenu isn't showing. Here's an example showing something similar to what you want (and using similar methods) working:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PopupMenu extends Box{
Dimension preferredSize = new Dimension(400,30);
public PopupMenu(){
super(BoxLayout.Y_AXIS);
final JPopupMenu menu = new JPopupMenu("Options");
for(int i = 1; i < 20; i++)
menu.add(new JMenuItem("Option" + i));
JLabel clickMe = new JLabel("ClickMe");
clickMe.setAlignmentX(RIGHT_ALIGNMENT);
clickMe.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e) {
menu.show(e.getComponent(), e.getX(), e.getY());
}});
add(clickMe);
}
public Dimension getPreferredSize(){
return preferredSize;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new PopupMenu());
frame.validate();
frame.pack();
frame.setVisible(true);
}
}

Categories