Java Button size changing when adding html - java

I'm just upping my knowledge on GUI and implementation of GUI's and buttons, and I've run into a little issue. I've searched for this, and even compared button codes but nothing seems different from what I'm seeing in comparison to others' code. When I add html to any button, take testOne for instance if I use:
JButton testOne = new JButton("<html><b><u>T</u>est<br>1</b></html>");
I have a button, of course, but the button is so large with tiny font, while my other buttons are normal size. Anyone have an idea why? I posted the code without a homework tag, because it's not homework, just fun practice.
public FunProject(){
super("Fun Project"); //child
//create layout and get the content pane for content
contents = getContentPane();
contents.setLayout(new FlowLayout(FlowLayout.CENTER));
leftBox = getContentPane();
leftBox.setLayout(new BoxLayout(leftBox, BoxLayout.X_AXIS));
//menuBar = new
//Create the buttons to use
JButton testOne = new JButton("Test 1");
JButton testTwo = new JButton("Test 2");
JButton testThree = new JButton("Test 3");
Also, for anyone feeling like spreading a little knowledge, how would I go about stacking my buttons? Right now they're just in a horizontal plane unstacked, but at the location I want (Center to the left). Thank you in advance.
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import java.awt.*;
import java.awt.event.*;
public class FunProject extends JFrame implements ActionListener, KeyListener, MenuListener{
//Content only visible to me
private Container contents;
private Container leftBox;
private JButton testOne, testTwo, testThree;
private JMenuBar menuBar;
private JMenu men, file, edit, exit;
private JMenuItem fileOpen, fileSave, fileType;
private JMenuItem editOpen, editSave, editType;
//Constructor
public FunProject(){
super("Fun Project");
//create layout and get the content pane for content
contents = getContentPane();
contents.setLayout(new FlowLayout(FlowLayout.CENTER));
leftBox = getContentPane();
leftBox.setLayout(new BoxLayout(leftBox, BoxLayout.X_AXIS));
//Key Listener
this.addKeyListener(this);
//Creating Menu bar
menuBar = new JMenuBar();
//Adding header to menuBar
men = new JMenu("Test Menu");
men.addMenuListener(this);
menuBar.add(men);
//Adding exit to menuBar
exit = new JMenu("Exit Menu");
exit.setMnemonic(KeyEvent.VK_X);
exit.addMenuListener(this);
menuBar.add(exit);
//Add submenu
file = new JMenu("FILE");
file.addMenuListener(this);
men.add(file);
edit = new JMenu("EDIT");
edit.addMenuListener(this);
men.add(edit);
//Add item to submenu FILE
fileOpen = new JMenuItem("Open a file");
fileOpen.addActionListener(this);
file.add(fileOpen);
fileSave = new JMenuItem("Save a file");
fileSave.addActionListener(this);
file.add(fileSave);
fileType = new JMenuItem("File type");
fileType.addActionListener(this);
file.add(fileType);
//Add item to submenu EDIT
editOpen = new JMenuItem("Open a file");
editOpen.addActionListener(this);
edit.add(editOpen);
editSave = new JMenuItem("Save a file");
editSave.addActionListener(this);
edit.add(editSave);
edit = new JMenuItem("File type");
editType.addActionListener(this);
edit.add(editType);
//Add menu bar
this.setJMenuBar(menuBar);
//Create the buttons to use
JButton testOne = new JButton("Test 1");
JButton testTwo = new JButton("Test 2");
JButton testThree = new JButton("Test 3");
//Button modifications
testOne.setPreferredSize(new Dimension(100, 100));
//Add buttons and such to the leftBox (frame > pane)
leftBox.add(testOne);
leftBox.add(testTwo);
leftBox.add(testThree);
//Tell the program what Listener will handle events for the button or whatever you
//are implementing
testOne.addActionListener(this);
testTwo.addActionListener(this);
testThree.addActionListener(this);
//Set size and visibility to display content and color
setSize(400,300);
setVisible(true);
}
public static void main(String[] args){
FunProject fp = new FunProject();
fp.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
I was messing around with menu's (So ignore the menu code) and what they're all about. That's for later time when I learn it better.

1)try to use
h1 Tag -> JButton testOne = new JButton("<html><b><u><h1>T</u>est<br>1</b></html>");
for increase the size or font use <font> tag for changing the color or size of the font.
2)some time it depend upon the layout you used check it out
3) try ButtonObject.setBounds();

Related

How can I check if a user is pressing a specific key i.e. Enter Key Like python's keyboard module?

I am working on making a gui chat app in java (I know too ambitious) that jus sends a message to the connected room. I have not yet done the networking stuff but jus the bare bones gui. I have a text field where the input message will be and a text area where the sent message will go with a button to send it. I want it so that when I press the enter key the sending task takes place. My code is
import javax.swing.*;
import java.awt.*;
public class Jabba {
//Class
public static void main(String args[]) {
//Main Method
//main frame
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
//The Menu that will later allow us to connect and create rooms to join a chat
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("Connect");
JMenu m2 = new JMenu("Help");
//This is for help
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Create new room");
JMenuItem m22 = new JMenuItem("Join an Existing Room");
m1.add(m11);
m1.add(m22);
//Our panel
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter Text");
//The Message field
JTextField tf = new JTextField(15);
//The Sending button
JButton send = new JButton("Send");
//The resetting button
JButton reset = new JButton("Reset");
//Adding the panel
panel.add(label);
panel.add(tf);
panel.add(send);
panel.add(reset);
//The text area where the messages will go
JTextArea ta = new JTextArea();
//Adding it to the Scroll Pane so that It has scrolls
JScrollPane sp = new JScrollPane(ta);
//Actionlisteners allow us to listen to the actions that take place with
//The Specific components like here when the button is pressed
send.addActionListener(e ->{
//It will first store the text of the the text field in a
//variable called msg
String msg = tf.getText();
//Then Will remove the Text from the field so that new messages can be
//sent
tf.setText(null);
//Now it will send The message to the message text area
ta.append(msg+"\n");
});
reset.addActionListener(e ->{
//This is for the reset option
ta.setText(null);
//It will jus set all the text of the message area to null
//i.e. Nothing
}
);
//adds all the content and components to the main frame.
frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, mb);
/*notice the BorderLayout here, it is from the awt package and it
is letting us lay the components in a specific layout.
Also we have changed the component below after the center to sp
i.e. it is the scrollpane instead of our textarea to get the Scroll Bars!!*/
frame.getContentPane().add(BorderLayout.CENTER, sp);
frame.setVisible(true);
//Pretty Self-Explanatory
}
}
enter image description here
Please help me and forgive me if I asked the question wrong as I couldn't quite understand how to us the KeyListener classs...## Heading ##
So as Mad Programmer told me and helped me I used an action Listener in that textfield and copied the code I used for the send message in an action listener for the text field var tf. So in pseudocode it is:
tf.addActionListener(e ->{
String msg = tf.getText();
tf.setText(null);
ta.append(msg+"\n");
});

Expand JMenu to left, while retaining default text alignment

I have a JMenu A within a JMenuBar aligned to the right of the screen. Within this menu are several JMenuItems, along with another JMenu B. Since menu A is right aligned, I need menu B to open to the left. In order to do this I found the code
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);.
The issue however, is that this messes with the text alignment of menu 2, which I would like to stay exactly like the other menu items.
I have also tried manually aligning menu 2 using SwngConstants.leftAlign, however this is too severe:
How can I make the menu expand to the left, while retaining the default text alignment? Thanks in advance! The code I used to produce the above images is seen below:
import java.awt.*;
import javax.swing.*;
public class Test{
public Test(){
JFrame frame = new JFrame();
JMenuBar menuBar = new JMenuBar();
JMenu menu1 = new JMenu("Menu 1");
JMenu menu2 = new JMenu("Menu 2");
JMenuItem menuitem1 = new JMenuItem("Menu Item 1");
JMenuItem menuitem2 = new JMenuItem("Menu Item 2");
JMenuItem menuitem3 = new JMenuItem("Menu Item 3");
JMenuItem menuitem4 = new JMenuItem("Menu Item 4");
menuBar.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
menu1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
menu2.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
menu2.setHorizontalAlignment(SwingConstants.LEFT);
menuBar.add(menu1);
menu1.add(menuitem1);
menu1.add(menuitem2);
menu1.add(menu2);
menu2.add(menuitem3);
menu2.add(menuitem4);
frame.setJMenuBar(menuBar);
frame.getContentPane().setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(270,170));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.getLookAndFeelDefaults().put("Label.font", new Font("Arial", Font.PLAIN, 12));
UIManager.getLookAndFeelDefaults().put("Button.font", new Font("Arial", Font.PLAIN, 12));
UIManager.getLookAndFeelDefaults().put("ComboBox.font", new Font("Arial", Font.PLAIN, 12));
UIManager.getLookAndFeelDefaults().put("JTextField.font", new Font("Arial", Font.PLAIN, 12));
new Test();
} catch(Exception e){
JOptionPane.showConfirmDialog(null, e.getMessage());
}
}
}
UPDATE: If I remove the lines of code aligning the menus right to left and move the frame to the edge of the display screen, then the menus act as desired (i.e. the menu will not expand off the monitor). Perhaps there is a way to tell the menu not to expand off the JFrame rather than the monitor?
UPDATE: Thank you #StanislavL for the idea. Overriding menu 2 with the following code does the trick, it also gets rid of that unsightly overlap between the two menus. Note that menu 2 no longer needs ComponentOrientation.RIGHT_TO_LEFT.
JMenu menu2 = new JMenu("Menu 2"){
protected Point getPopupMenuOrigin(){
return new Point(-this.getPopupMenu().getPreferredSize().width, 0);
}
};
You can try to override
public ComponentOrientation getComponentOrientation()
method of JMenu to return your alignmnet
or JMenu has method you can override
protected Point getPopupMenuOrigin()

Java Swing Menu Beginners Advice

I just started studying some java GUI techniques and I have created a small program which has a menu bar a menu as well as an item within that menu. Now what I want to do is to implement a file chooser so when the item in the menu is selected then the file chooser is executed. The problem is that the file chooser that I created is in another class. Is there any possible way to start my file chooser's class when the item in the menu is clicked?
Here is my code
public class menu {
public static void main(String[] args){
//to menu
JFrame frame = new JFrame("Menu");
frame.setVisible(true);
frame.setSize(600,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
frame.setJMenuBar(bar);
JMenu search = new JMenu("Browse");
bar.add(search);
final JMenuItem songstoplay = new JMenuItem("Browse Songs To Play");
search.add(songstoplay);
//to outline
final Container content = frame.getContentPane();
content.setLayout(new GridLayout(3, 1));
JLabel text = new JLabel("My first iteration", JLabel.CENTER);
text.setVerticalAlignment(JLabel.TOP);
text.setFont(new Font("Serif", Font.PLAIN, 30));
content.add(text);
JLabel text2 = new JLabel();
text2.setText("List of drives connected: C:/");
text2.setFont(new Font("Serif", Font.PLAIN, 20));
text2.setVerticalAlignment(JLabel.TOP);
content.add(text2);
}
}
If you want to use the JFileChooser, you have to add an eventlistener on your menuitem. Better you take a look at this: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
or the direct link to the code from the example above:
http://docs.oracle.com/javase/tutorial/uiswing/examples/components/FileChooserDemoProject/src/components/FileChooserDemo.java

JPanel java not showing up

Im trying to get it so that when i click on a menu option, the windows changes from the 'welcome text' to 4 buttons which the user can then click on. However, when i click on the simulation button, nothing happens.. the window doesnt change at all.. Ive summarized my code to the basic stuff by the way. anyone see anything i cant?
JFrame GUI = new JFrame("Graphical User Interface");
public gui()
{
JMenuBar menubar = new JMenuBar();
JMenu Simulation = new JMenu("Simulation");
theLabel = new JLabel("Welcome to the Main Menu. ",JLabel.CENTER);
GUI.add(theLabel);
menubar.add(Simulation);
Simulation.add(Simulationmenu);
Simulationmenu.addActionListener(this);
GUI.setJMenuBar(menubar);
GUI.setLocation(500,250);
GUI.setSize(300, 200);
GUI.setVisible(true);
}
public void actionPerformed(ActionEvent E){
if(E.getSource() == Simulationmenu){
// Buttons in the menu i want to output once clicked on 'simulation'
thePanel = new JPanel(new GridLayout(4,0));
Run = new JButton("Run");
Pause = new JButton("Pause");
Reset = new JButton("Reset");
DisplayMaps = new JButton("Display Maps?");
// Add the components to the panel:
thePanel.add("West", Run);
thePanel.add("Center", Pause);
thePanel.add("East", Reset);
thePanel.add("West", DisplayMaps);
// Add the panel to the contentPane of the frame:
GUI.add(thePanel);
// add this object as listener to the two buttons:
Run.addActionListener(this);
Seems your problem in next, you add a new panel(thePanel) to your JFrame(GUI) when it is showing, but in this case you must to call revalidate() method of JFrame(GUI).
Add GUI.revalidate() after GUI.add(thePanel);, it helps you.

a GUI java program needing an action event button

I am making a simple java program that represents a Microsoft Word menu bar, and in the file menu I add an exit button... it does nothing.
I need your help to tell me what to do to make the exit button actually exit and close the program.
Here is my code:
public class MicrosoftWordMenu {
public static void main(String [] args)
{
JPanel panel = new JPanel();
JFrame frame = new JFrame("Microsoft Word");
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenu menu1 = new JMenu("Edit");
JMenu menu2 = new JMenu("View");
JMenu menu3 = new JMenu("Insert");
JMenu menu4 = new JMenu("Format");
JMenu menu5 = new JMenu("Tools");
JMenu menu6 = new JMenu("Table");
JMenu menu7 = new JMenu("Window");
JMenu menu8 = new JMenu("Help");
frame.add(bar, BorderLayout.NORTH);
frame.add(panel);
bar.add(menu);
bar.add(menu1);
bar.add(menu2);
bar.add(menu3);
bar.add(menu4);
bar.add(menu5);
bar.add(menu6);
bar.add(menu7);
bar.add(menu8);
JMenuItem menuitem = new JMenuItem("New...");
JMenuItem menuitem1 = new JMenuItem("Open...");
JMenuItem menuitem2 = new JMenuItem("Close");
JMenuItem menuitem3 = new JMenuItem("Save");
JMenuItem menuitem4 = new JMenuItem("Save as...");
JMenuItem menuitem5 = new JMenuItem("Save as web page...");
JMenuItem menuitem6 = new JMenuItem("Web page preview ");
JMenuItem menuitem7 = new JMenuItem("Print ");
JMenuItem menuitem8 = new JMenuItem("Exit");
menu.add(menuitem);
menu.add(menuitem1);
menu.add(menuitem2);
menu.add(menuitem3);
menu.add(menuitem4);
menu.add(menuitem5);
menu.add(menuitem6);
menu.add(menuitem7);
menu.add(menuitem8);
frame.setSize(600,100);
frame.setVisible(true);
}
}
Also consider using Action to let components share functionality, as shown here.
Calling System.exit(0) on menu selection would do just fine.
At the moment you're just creating the GUI element, but they're basically empty shells. In particular, you've created items that appear on the menu, but you haven't added any behaviour to those items. (Since you haven't told your program anywhere what to do when an item is clicked, what did you think would happen)?
In order to provide this behaviour, you'll need to register an ActionListener, which will be called when something happens on an element, and will let you take an appropriate action at that point (such as calling System.exit(0). See the tutorial on Writing [Swing] Event listeners for details.
I always extend the AbstractAction class (which implements the ActionListener interface) which allows you to reuse your actions. By extending the AbstractAction, the actionPerformed(ActionEvent e) method will be invoked very time your button is clicked.
public class CloseAction extends AbstractAction {
public CloseAction() {
super("Close");
}
public actionPerformed(ActionEvent e) {
System.exit(1);
}
}
Now, to apply the above action to one of your buttons, you simply need to follow the below piece of code.
CloseButton.setAction(new CloseAction());
The close button will now shut down your application each time it gets pressed.
Use the ExitAction defined in Closing an Application. Then clicking on the Exit menu item will be just like clicking on the Close icon at the top right of the window. This allows for consistency when closing an application in case you ever need to do close processing.
Edit:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
// JMenuItem menuitem8 = new JMenuItem("Exit");
JMenuItem menuitem8 = new JMenuItem( new ExitAction() );

Categories