Tool tip in gui not displaying? - java

I am using the .setToolTipText component so that the text "This will show up when you hover over it" shows up when the mouse is hovered over the window. Currently, everything else is working, except for the tooltip. Right now the tool tip only displays when hovered above the words, how do I make it display whenever I hover over the window itself? This is the code:
Here is the main class:
import javax.swing.JFrame;
class evenmoregui{
public static void main (String[ ] args){
moregui guiobject = new moregui();
guiobject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Makes the program terminate when the x is clicked
guiobject.setSize(275,180); //This is the size
guiobject.setVisible(true); //Means it should show up, actually puts the window on screen
}
}
Here is the class with the actual .setToolTip part:
import java.awt.FlowLayout; //Make it so the windows don't overlap, it just formats the windows properly
import javax.swing.JFrame; //Gives you all the windows features in the window, like minimize
import javax.swing.JLabel; //Allows text and simple images on window
public class moregui extends JFrame { //JFrame gives you all the basic windows features.
private JLabel item1;
public moregui(){ //Constructor
super("This is the title bar"); //These are all imported methods
setLayout(new FlowLayout()); //Gives default layout
item1 = new JLabel("This is a sentence"); //Text on the screen
item1.setToolTipText("This will show up when you hover over it");
add(item1); //Adds item1 into window
}
}

Try adding getRootPane().setToolTipText("String");
this will make sure that the tool tip is shown when hovered over JFrame
import java.awt.FlowLayout;
import javax.swing.JFrame; window, like minimize
import javax.swing.JLabel;
public class moregui extends JFrame{
private JLabel item1;
public moregui(){ //Constructor
super("This is the title bar"); //These are all imported methods
getRootPane().setToolTipText("Hovering over window");
setLayout(new FlowLayout()); //Gives default layout
item1 = new JLabel("This is a sentence"); //Text on the screen
item1.setToolTipText("This will show up when you hover over it");
add(item1); //Adds item1 into window
}
}

This is a correct code. Try hovering over it longer.
JPanel panel = new JPanel();
panel.setToolTipText("ToolTIp");
contentPane.add(panel, BorderLayout.NORTH);
JLabel lblLabel = new JLabel("Label");
panel.add(lblLabel);
Let me know if you ran into any more problems.

Related

My JCheckBox program only displays one box. Why is that?

I am attempting to add another checkbox to this program but for some reason it will not display when I run the program. Only the check box for the blue pill displays. I have attempted to add a couple things or change the way the program is structured, but nothing I have done so far has helped.
Code Below:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CMIS242WK4DonnersonAReply {
static JCheckBox red;
static JCheckBox blue;
static JButton button;
public CMIS242WK4DonnersonAReply() {
button = new JButton("submit"); // Creates submit button
widget
ButtonHandler listener = new ButtonHandler(); // Creates the handler for the button.
button.addActionListener((ActionListener) listener); // adds the handler to the button widget
JPanel content = new JPanel(); // "container"
content.setLayout(new BorderLayout());
content.add(button, BorderLayout.PAGE_END);// places submit button at the bottom of panel.
JLabel label = new JLabel("At last. Welcome, Neo. As you no doubt have guessed, I am Morpheus. This is your last chance. After this there is no turning back."); // Label in frame.
content.add(label, BorderLayout.NORTH);// places label at the top of the screen.
//Creating Check Boxes
JCheckBox red = new JCheckBox("You take the red pill, you stay in Wonderland and I show you how deep the rabbit hole goes.");
red.setBounds(100,100, 50,50);
content.add(red);
JCheckBox blue = new JCheckBox("You take the blue pill, the story ends, you wake up in your bed and believe whatever you want to believe. ");
blue.setBounds(100,100, 50,50);
content.add(blue);
//Adding Frame
JFrame window = new JFrame("Matrix Monologue"); // JFrame = Window
window.setContentPane(content);
window.setSize(750,200); // Length, Height
window.setLocation(200,200); // X/Y "OF THE ENTIRE FRAME" Not the contents
window.setVisible(true); // makes window visible
}
// Method handles what happens when button is pressed.
private static class ButtonHandler implements ActionListener{
public void actionPerformed1(ActionEvent e) {
// Checks if which pill was selected and responds to user depending on their action.
if (red.isSelected() == true) {
System.out.println("Follow me");
System.out.println();
}
if (blue.isSelected() == true) {
System.out.println("Very Well, You may go back to your world");
System.out.println();
}
else
System.out.println("You must make a choice for what pill you will take");
System.exit(0); //closes program
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
// Main/driver method that runs everything.
public static void main(String[] args) {
CMIS242WK4DonnersonAReply matrixMonologue= new CMIS242WK4DonnersonAReply();
}
}
Any pointers?
When you're stuck on a problem, it never hurts to go back and consult the documentation.
You'll find information like this:
A border layout lays out a container, arranging and resizing its
components to fit in five regions: north, south, east, west, and
center. Each region may contain no more than one component, and is
identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and
CENTER. When adding a component to a container with a border layout,
use one of these five constants...
When you add your button, you do this:
content.add(button, BorderLayout.PAGE_END);
But then, when it's time to add checkboxes, you do this:
content.add(red);
...
content.add(blue);
Are you seeing what's missing? My bet is that you only see the blue checkbox because you added it on top of (or simply displaced) the red checkbox. Remember, the doc says "Each region may contain no more than one component..."
Try specifying the region of your BorderLayout where you want to see each checkbox.
If you want them to appear in the same region, put them in a JPanel of their own and lay them out at NORTH and SOUTH or EAST and WEST and then add that checkbox panel to your content panel in the region you want them to appear.
I feel that you need some guidance with your Swing programming. I have rewritten your CMIS242WK4DonnersonAReply class. Code is below. But first some comments about the code in your question.
JCheckBox red = new JCheckBox("You take the red pill, you stay in Wonderland and I show you how deep the rabbit hole goes.");
You have created a local variable which is hiding the class member. Hence static JCheckBox red; remains null and consequently the following if statement will throw NullPointerException.
if (red.isSelected() == true) {
By the way, the == true is not necessary. The following is sufficient.
if (red.isSelected()) {
Now another point.
red.setBounds(100,100, 50,50);
Since you are using a layout manager, namely BorderLayout, method setBounds will be ignored. The layout manager determines where to place the component on the screen.
window.setContentPane(content);
By default, the content pane of JFrame is a JPanel with BorderLayout so no need to replace the default content pane.
private static class ButtonHandler implements ActionListener
No need to create a nested class. Simply make class CMIS242WK4DonnersonAReply implement the ActionListener interface.
System.out.println("Follow me");
I don't think it's a good idea to involve the console in a GUI application. I would use JOptionPane to display a message to the user.
static JCheckBox blue;
I think that JRadioButton is more appropriate than JCheckBox in your situation.
Here is my code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class CMIS242WK4DonnersonAReply implements Runnable, ActionListener {
private JButton button;
private JRadioButton blue;
private JRadioButton red;
private JFrame window;
#Override
public void actionPerformed(ActionEvent event) {
if (red.isSelected()) {
JOptionPane.showMessageDialog(window, "Follow me.");
}
else if (blue.isSelected()) {
JOptionPane.showMessageDialog(window, "Very Well, You may go back to your world");
}
else {
JOptionPane.showMessageDialog(window, "You must make a choice for what pill you will take");
}
}
#Override
public void run() {
createAndShowGui();
}
private void createAndShowGui() {
window = new JFrame("Matrix Monologue");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("At last. Welcome, Neo. As you no doubt have guessed, I am Morpheus. This is your last chance. After this there is no turning back."); // Label in frame.
window.add(label, BorderLayout.PAGE_START);
window.add(createCheckBoxes(), BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
button = new JButton("submit");
button.addActionListener(this);
buttonPanel.add(button);
window.add(buttonPanel, BorderLayout.PAGE_END);
window.setSize(750,200); // Length, Height
window.setLocation(200,200); // X/Y "OF THE ENTIRE FRAME" Not the contents
window.setVisible(true); // makes window visible
}
private JPanel createCheckBoxes() {
JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);
red = new JRadioButton("You take the red pill, you stay in Wonderland and I show you how deep the rabbit hole goes.");
blue = new JRadioButton("You take the blue pill, the story ends, you wake up in your bed and believe whatever you want to believe.");
ButtonGroup grp = new ButtonGroup();
grp.add(red);
grp.add(blue);
panel.add(red);
panel.add(blue);
return panel;
}
public static void main(String[] args) {
EventQueue.invokeLater(new CMIS242WK4DonnersonAReply());
}
}
Here is how the app looks when I run it.

Swing JDialog width too wide

I am trying to make a modeless dialog menu in Swing that is displayed upon the press of a button. The dialog contains several menu items. My problem is that the dialog window is much wider than necessary. I am looking for help on setting the window width.
Here's what the output looks like. Notice that the window containing the menu items is much wider than the items themselves. That's what I want to fix.
Here's minimal code that shows this problem:
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test().run();
}
TestDialog testDialog;
private void run() {
JFrame jframe = new JFrame();
JButton jbutton = new JButton("test");
jframe.add(jbutton);
jbutton.setBounds(130, 100, 100, 40);
jframe.setSize(400, 500);
jframe.setLayout(null);
jframe.setVisible(true);
testDialog = new TestDialog(SwingUtilities.windowForComponent(jframe));
jbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
testDialog.show();
}
});
}
private class TestDialog {
JDialog jdialog;
public TestDialog(Window parent) {
jdialog = new JDialog(parent, "Test", Dialog.ModalityType.MODELESS);
jdialog.setPreferredSize(new Dimension(100, 0));
jdialog.setLayout(new BoxLayout(jdialog.getContentPane(), BoxLayout.Y_AXIS));
JMenuItem jmenuItem1 = new JMenuItem("MenuItem 1");
Dimension jmiDimension = jmenuItem1.getPreferredSize();
System.out.printf("jmenuItem1 is %f x %f%n", jmiDimension.getWidth(), jmiDimension.getHeight());
jdialog.add(jmenuItem1);
jdialog.add(new JMenuItem("MenuItem 2"));
jdialog.pack();
Dimension d = jdialog.getSize();
System.out.printf("jdialog is %f x %f%n", d.getWidth(), d.getHeight());
}
public void show() {
jdialog.setVisible(true);
}
}
}
The program prints this output, showing that the dialog is 324 pixels wide but the menu items are 87:
jmenuItem1 is 87.000000 x 21.000000
jdialog is 324.000000 x 88.000000
I have also tried using the jdialog.setSize() and jdialog.setMaximumSize() methods. And I've tried setting the maximum size of the menu items. None of them seem to have any affect upon the dialog's window size.
I also tried a GridLayout, rather than a BoxLayout - that also made no difference.
I also tried setting the width of the dialog's content pane and layered pane. Still no difference.
I noted that the dialog has no owner nor parent.
testDialog = new TestDialog(SwingUtilities.windowForComponent(jframe));
You don't need to use the windowForComponent(...) method. You already have a reference to the parent frame:
testDialog = new TestDialog( jframe );
Don't attempt to hard code sizes. Each component will determine its own preferred size and the then layout manager will use this information to determine the overall size.
//jdialog.setPreferredSize(new Dimension(100, 0));
A JMenuItem was designed to be used on a JMenu. Instead you should be using a JButton to add to a regular panel.
I don't have a problem with the size. The width/height of the dialog is as expected.
Note I use JDK 11 on Windows 10. When I ran your original code, the dialog had no size since the setPreferredSize() statement caused the height to be 0. So I'm not sure how you get the display shown in your image.
And yes the dialog width is wider than the component added to the frame because there is a minimum width to the dialog to be able to be able to display the title bar even if no components are added to the dialog.

Swing: grayable multi-line JCheckBox?

I want to have a checkbox with multi-line text and I want to disable it sometimes.
Simple JCheckBox works fine and gets disabled, but it's not multiline.
Putting <html>line1<br>line2</html> provides correct size and layout, but when I disable the control, only the checkbox itself is grayed, the text remains black.
I know I can change the HTML text color to gray, but this will not work for the "Classic Windows" look-and-feel where disabled text should rendered as "sunken". Or, actually, it will work, but the appearance will differ from other disabled controls nearby, which is not good.
I can create a simple JCheckBox containing the first line of text and a JLabel with the second line and disable them simultaneously, but clicking the second line (the JLabel) doesn't activate the checkbox, and clicking the checkbox displays the keyboard focus only around the first line which confuses the user.
Is it possible to have a checkbox and its label as separate controls and have some kind of link between them, as in HTML? Probably I would be able to cook something from this.
Is it possible to subclass JButton and override something there, for example, to change the way the focus rectangle is drawn? The rectangle is drawn by com.sun.java.swing.plaf.windows.WindowsButtonUI but I'm kinda afraid of subclassing that class because it's too deep in the standard library and my application may break with a new JRE.
EDIT 04.02.2015: The above applies to Java 1.6. In Java 1.7 and higher, disabling a multi-line checkbox changes its appearance, but it still looks not the same as a disabled single-line checkbox; in particular, on Classic Windows theme the text doesn't become sunken.
(source: keep4u.ru)
I might be missing something, but I just disable the JCheckBox and the JLabel.
Using Java 1.7 and Windows Vista.
Here's the code
package com.ggl.testing;
import java.awt.BorderLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class CheckBoxTest implements Runnable {
private JCheckBox checkBox;
private JLabel multiLineLabel;
private JFrame frame;
#Override
public void run() {
frame = new JFrame("Check Box Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel checkBoxPanel = new JPanel();
checkBox = new JCheckBox();
checkBoxPanel.add(checkBox);
String s = "<html>When in the course of human events it becomes"
+ "<br>necessary for one people to dissolve the political"
+ "<br>bands which have connected them with another and to"
+ "<br>assume among the powers of the earth, the separate"
+ "<br>and equal station to which the Laws of Nature and"
+ "<br>of Nature's God entitle them, a decent respect to the"
+ "<br>opinions of mankind requires that they should declare"
+ "<br>the causes which impel them to the separation.";
multiLineLabel = new JLabel(s);
multiLineLabel.setLabelFor(checkBox);
checkBoxPanel.add(multiLineLabel);
mainPanel.add(checkBoxPanel, BorderLayout.CENTER);
JPanel toggleButtonPanel = new JPanel();
JToggleButton toggleButton = new JToggleButton("Disable Checkbox");
toggleButton.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent event) {
JToggleButton toggleButton = (JToggleButton) event.getSource();
if (toggleButton.isSelected()) {
checkBox.setEnabled(false);
multiLineLabel.setEnabled(false);
} else {
checkBox.setEnabled(true);
multiLineLabel.setEnabled(true);
}
}
});
toggleButtonPanel.add(toggleButton);
mainPanel.add(toggleButtonPanel, BorderLayout.SOUTH);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new CheckBoxTest());
}
}

Not able to enable a button after it is disabled in java swing

I have just started learning java swing and I have been trying to create a simple game. The game is similar to minesweeper. A window with a matrix of bottons with just 1 mine. On clicking a button, if it's not a mine, i disable the button and display green color, and if it's a mine i disable the button and display red color. I have displayed the color by setting the button background to the required color. I have done the implementation so far just fine.
Next i added a reset button, on clicking which i renable all buttons by using : setEnabled(true).
But for some reason, the button is not getting enabled. I have confirmed that the program flow reaches the code for enabling the button, but i'm not able to find the reason why it is not working.
Here is a test program i wrote with a reset button and 1 button. Same issue. Can anyone point out what I maybe doing wrong?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test implements ActionListener{
JFrame frame = new JFrame("Mine");
JButton buttons = new JButton();
JButton reset = new JButton("Reset");
Container grid = new Container();
public Test(){
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
frame.add(reset, BorderLayout.NORTH);
reset.addActionListener(this);
buttons = new JButton();
buttons.addActionListener(this);
frame.add(buttons, BorderLayout.CENTER);
}
public static void main(String[] args){
new Test();
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(reset))
buttons.setEnabled(true);
else{
if(event.getSource()==buttons){
buttons.setBackground(Color.RED);
buttons.setEnabled(false);
}
}
}
}
Actually it's getting enabled when you click reset, all you forgot to do was reset the color:
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(reset)){
buttons.setEnabled(true);
buttons.setBackground(null);
}else{
if(event.getSource()==buttons){
System.out.println("xxx");
buttons.setBackground(Color.RED);
buttons.setEnabled(false);
}
}
}

positioning different component in java GUI

im trying to design java GUI frame which contains labels, textfields, radio buttons and button..
i want to position each component in specific place tried setBounds() but it didn't work..
also im trying to change background color of the frame using getContentPane().setBackground(Color.white) and setBackground(Color.white) but didnt work too.
how to do it ?
this is my code :
import javax.swing.*;
import java.awt.*;
import java.applet.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class test extends JFrame{
public static void main(String[] args) {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("WHO IS THE WINNER");
guiFrame.setSize(700,500);
guiFrame.setLocationRelativeTo(null);
final JPanel first = new JPanel();
JLabel un = new JLabel("UserName:");
JTextField textField = new JTextField(20);
JLabel sn = new JLabel("Server Name:");
JTextField textField2 = new JTextField(20);
un.setLabelFor(textField);
sn.setLabelFor(textField2);
first.add(un);
first.add(textField);
first.add(sn);
first.add(textField2);
final JPanel second = new JPanel();
JLabel level = new JLabel("Level:");
JLabel score = new JLabel("Score:");
JLabel question = new JLabel("Question:");
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox radio1 = new Checkbox("True", radioGroup,false);
Checkbox radio2 = new Checkbox("False", radioGroup,true);
second.add(score);
second.add(level);
second.add(question);
second.add(radio1);
second.add(radio2);
JButton next = new JButton( "Next");
next.addActionListener(
new ActionListener() {
#Override public void actionPerformed(ActionEvent event) {
first.setVisible(false);
} });
guiFrame.add(first, BorderLayout.NORTH);
guiFrame.add(second, BorderLayout.CENTER);
guiFrame.add(next,BorderLayout.SOUTH);
guiFrame.setVisible(true);
}
}
for the positioning for example i want the first label and text field under them the other label and text field not beside them.. same for other labels and radio buttons i don't want them it be beside each other i want o give them a specific position to be in..
can someone please help ?
Thanks :)
This answer is just for Eclipse IDE.
An easy way to place all the widgets is doing it from the Design tab, placed at the bottom-left side of the window. Just change from Source perspective to Design perspective. It will open a simple panel with everything you need. Just drag the different widgets and place them in their position.
To change the background of the frame, do it from the properties of the frame in the Design tab or add the following code to the constructor of the panel:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);

Categories

Resources