With NetBeans (Java), I am having problems in JLabel. I have assigned an image as the icon of that JLabel.
Problem - 1st:
I want to display some text (e.g - logout) below that icon (image). How to do this?
Problem - 2nd:
I want to display some text when mouse is rolled over that JLabel. What should I do?
So , please guys tell me how to these things by writing code.
I recommend reading the basic Oracle tutorials which describe in detail how to accomplish this. You can use a MouseMotionListener to determine when the mouse is rolled over the JLabel, and you can position the JLabel text underneath the Icon of the JLabel by setting its vertical text position as described in the JLabel Tutorial. This should have all been found with a simple internet search of your questions, something that your question suggests was not done (and should have been) before asking
1.
Create a JPanel that contains two JLabels. This way you can control the layout of the internal components.
I used BoxLayout with the parameter BoxLayout.Y_AXIS to get the label below the icon.
2.
Add a MouseListener using the method component.addMouseListener(new MouseAdapter() { ... });, you'll need to create a MouseAdapter and implement any methods you need (click here).
Here is a working example for you buddy... Adapt this however you need to.
Note: You'll need to change the file-path of the ImageIcon()
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel container = new JPanel();
JPanel iconLabelPanel = new JPanel();
String TEXT_FIELD_TEXT = "Hover over the logout label.";
JLabel icon = new JLabel(new ImageIcon("C:\\Users\\Gary\\Google Drive\\Pictures\\puush\\ss (2015-02-19 at 06.00.00).png"));
JLabel label = new JLabel("Logout!");
JTextField textField = new JTextField(TEXT_FIELD_TEXT);
//Add a mouse motion listener for the JLabel
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
//Set text of another component
textField.setText("You're over Logout!");
}
#Override
public void mouseExited(MouseEvent e) {
//Set text of another component
textField.setText(TEXT_FIELD_TEXT);
}
});
//Add components and set parameters for iconLabelPanel
iconLabelPanel.setLayout(new BoxLayout(iconLabelPanel, BoxLayout.PAGE_AXIS));
iconLabelPanel.add(icon);
iconLabelPanel.add(label);
//Add components and set parameters for container
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
container.add(iconLabelPanel);
container.add(textField);
//Set parameters for frame
frame.add(container);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(400, 400);
frame.setVisible(true);
}
Related
I have been searching for a while now, but couldnt find a solution so I have decided to ask here.
I am using Java Swing for my gui implementation of calculator. I have custom made layout(which works correctly 100%). I have added all buttons and all buttons are positioned correctly, always. Last component I have inserted is "Inv" and it is checkbox which I cant find a way to center it inside its area. I have tried putting it in panel,in panel with borderlayout.center, setting the horizontal and vertical text alignment, but nothing works.
invert = new JCheckBox("Inv");
invert.setBackground(Color.decode("#8DA336"));
invert.addActionListener(new CommandListener(this,"invert"));
container.add(invert, new RCPosition(5, 7));
This RCPosition is nothing more than object which says in which row and column this component is (nothing wrong with that).
Checkbox is by default left-aligned. Try make it center-aligned:
invert = new JCheckBox("Inv");
invert.setHorizontalAlignment(SwingConstants.CENTER);
// styling and add to container
If it don't help, then you should publish your layout manager.
You could try putting it in a JPanel with BoxLayout, then add horizontal glue on the left and right.
final JFrame frame = new JFrame();
final JPanel jp = new JPanel();
jp.setLayout(new BoxLayout(jp, BoxLayout.X_AXIS));
jp.add(Box.createHorizontalGlue());
final JCheckBox jcb = new JCheckBox("inv");
jp.add(jcb);
jp.add(Box.createHorizontalGlue());
frame.getContentPane().add(jp);
frame.pack();
frame.setLocationRelativeTo(null);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});
This is just one way to do it, setHorizontalAlignment should work as well.
I am trying to use Java Swing to create a simple GUI in which I have a drawing pad and some buttons it all works fine until I add this code for the JTextField:
String text = "hello";
JTextArea textArea = new JTextArea(text);
textArea.setPreferredSize(new Dimension(500, 50));
textArea.setEditable(false);
Before adding this code the drawpad displays on the left of the screen followed by the buttons, when I add this only the drawpad is displayed unless I resize the frame in which case the buttons and text field reappear although the text field is hidden behind the drawpad slightly. Here is the full code:
public class testGUI extends Frame{
public static void main(String[] args) {
JFrame frame = new JFrame("Neural Networks");
frame.setSize(700, 300); //set the size of the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); //make it visible
Container content = frame.getContentPane();
content.setLayout(new BorderLayout());
JPanel mainPanel = new JPanel();
final PadDraw drawPad = new PadDraw();
drawPad.setSize(100, 100);
content.add(drawPad);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
drawPad.clear();
}
});
JButton loadButton = new JButton("Load");
loadButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Load something here
}
});
JButton testButton = new JButton("Test Draw Pad Image");
testButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//
}
});
JButton loadImage = new JButton("Test image from file");
loadImage.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//String filename = textField.getText();
}
});
String text = "hello";
JTextArea textArea = new JTextArea(text);
textArea.setPreferredSize(new Dimension(500, 50));
textArea.setEditable(false);
mainPanel.add(clearButton);
mainPanel.add(loadButton);
mainPanel.add(testButton);
mainPanel.add(loadImage);
mainPanel.add(textArea);
content.add(mainPanel);
}
}
You're adding the drawPad and the mainPanel to the content panel, which uses BorderLayout, without specifying any location. They thus end up both in the center position of the border layout, which is supposed to contain only one component.
See How to use BorderLayout in the Swing tutorial.
Also note that setting the preferred size is not something you should do. Instead, the preferred size is supposed to be automatically computed based on other sttings (the contained components, the number of rows and columns of a text area, etc.)
And a JTextArea should be enclosed into a JScrollPane to be good-looking and allow you to scroll.
JPanel mainPanel = new JPanel();
The default layout for a JPanel is a FlowLayout, so all the components flow on a single row. If there is not enough room on the row then the components wrap to the next row.
So when you add the JTextArea the flow is disturbed. The solution is to use a combination of layout managers to get your desired layout effect. Read the section from the Swing tutorial on Using Layout Managers for more information and examples.
JTextArea textArea = new JTextArea(text);
textArea.setPreferredSize(new Dimension(500, 50));
Also, you should NOT set the preferred size of the text area (or any Swing component for that matter). Instead you should do something like:
JTextArea textArea = new JTextArea(rows, columns);
and let the component determine its own preferred size. Also a text area is typically used with a JScrollPane and then you add the scroll pane to your panel:
JScrollPane scrollPane = new JScrollPane( textArea );
Edit:
Taking a second look at your code you have many more problems.
The point of using a layout manager is to have the layout manager set the size and location of the components. So your code should not have any logic related to the size/location of a component.
When you use the add(...) statement on a BorderLayout without a constraint, the component gets added to the CENTER. However only the last component added is managed by the BorderLayout. So only the "mainPanel" is given a size/location by the layout manager. That is why you need the setSize(...) statement on the drawPad to make the component visible. Although you now have the problem that two components are painted in the same space.
So to see the drawPad on the left you might want to use:
content.add(drawPad.BorderLayout.LINE_START);
However this still probably won't work because I'm guessing you are doing custom painting on the draw pad which means you will also need to override the getPreferredSize() method of the class so the layout manager can use the information to determine the size of the component. Read the section from the Swing tutorial on Custom Painting for more information and working examples.
Finally some other issues:.
The setVisible(...) statement should be invoked AFTER all the components have been added to the frame.
To follow Java standards, class names should start with an upper case character.
You should NOT be extending "Frame". There is no need to extend any class in your example.
Read the tutorial and download the demos for examples of better structured code.
I'm writing a simple java game and I'm facing this problem:
My different layouts are in different JPanels (1 JPanel for the welcoming page, where I have to press 'start game' and another one with the actuall functionallity)
I start the game from a JFrame
import javax.swing.JFrame;
public class RType extends JFrame {
public RType() {
add(new Welcome());//first panel
add(new Board());//panel with the game
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(100, 100);
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new RType();
}
}
obviuosly, this launches the second panel right after the first, and I cant see the first one.
I've tried some stuff, trying to invoke the second panel in the main method, when the first panel is clicked that way:
RType rt=new RType();
rt.add(new Board()); //in this case add(new Board()); is removed from constructor
but it's doing nothing.
how can I solve it?
As #nachokk has said, you should be using a CardLayout instead. It lets you do things like tabs in a browser, but you don't need to make the tabs visible for your game if you don't want to. You make your welcome "card" visible at first, then when the user clicks you switch to the Board "card".
I don't recommend to add directly to the JFrame components, instead use another container as JPanel . JFrame default layout is BorderLayout, when you add in the way you are adding it always put in the center.
Make something like this:
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new CardLayout());
mainPanel.add(new Welcome(), "Welcome");
mainPanel.add(new Board(),"Board");
frame.add(mainPanel);
Here is a tutorial How to use CardLayout
on first panel of welcome add a button, and apply actionperformed like
JButton myButton = new JButton("Add Component ");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.remove(welcome);
frame.add(Board, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
});
By default, both panels will fill up the entire Frame's area. To fix this, you will need to use another layout, such as a GridLayout to structure the areas in which the panels will take up the Frame's area.
You can also go with no layout to hard code the pixel values of where you want the panels to fit in your frame.
EDIT: Based on what you're looking to do, the CardLayout is probably what you'll want to use for your Frame's layout.
I have a program which creates 2 Panels and then places a label and two buttons in them. The label is set to invisible setVisible(false) and then the two buttons are added and the frame is packed. When i click the first button, the label is shown, setVisible(true), and the seccond one hides it again, setVisible(false). When i click each button, they move to fill the space of the label as it hides, and move again to get out of the way of the label as it is shown. I want to stop this from happening and have the buttons stay in the same place even when the label is hidden.
Here is the code:
public class MainFrame extends JFrame{
public JLabel statusLabel;
public JButton show;
public JButton hide;
public MainFrame(){
super("MagicLabel");
JPanel topPanel = new JPanel(); //Create Top Panel
statusLabel = new JLabel(""); //Init label
statusLabel.setVisible(false); //Hide label at startup
topPanel.setSize(400, 150); //Set the size of the panel, Doesn't work
topPanel.add(statusLabel); //Add label to panel
JPanel middlePanel = new JPanel(); //Create Middle Panel
show= new JButton("Show"); //Create show button
hide= new JButton("Hide"); //Create hide button
middlePanel.setSize(400, 50); //Set the size of the panel, Doesn't work
middlePanel.add(show); //Add show button
middlePanel.add(hide); //Add hide button
this.add(topPanel, "North"); //Add Top Panel to North
this.add(middlePanel, "Center"); //Add Middle Panel to Center
addActionListeners(); //void:adds action listeners to buttons
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 512, 400);
this.setPreferredSize(new Dimension(400,200)); //Set size of frame, Does work
this.pack();
this.setVisible(true);
}
public void animateInstall(boolean var0){ //Void to show and hide label from action listeners
statusLabel.setVisible(var0);
sendWorkingMessage("Boo!");
}
public void sendWorkingMessage(String message){ //Void to set text of label
this.statusLabel.setForeground(new Color(225, 225, 0));
this.statusLabel.setText(message);
}
void addActionListeners(){
show.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
animateInstall(true);
}
});
hide.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
animateInstall(false);
}
});
}
this.setPreferredSize(new Dimension(400,200));
this.setMinimumSize(new Dimension(400,200));
So pack() cannot interfere.
Use CardLayout. Add the JLabel and empty JPanel. Instead of seting it visible/invisible swap the cards showing the JLabel or the JPanel when necesary.
Extending JFrame is not advisable, better extend JPanel put all your components inside and then add it to a JFrame
You need to learn how to use SwingUtilities.invokeLater(): See example how your should look like
You need to learn about Layout: Tutorial
Very dumb and easy approach in your code would be:
this.statusLabel.setForeground(bgColor); //background color
this.statusLabel.setText(" "); //some number of characters
By default for you frame you are using BorderLayout. You can try to have like:
this.add(topPanel, BorderLayout.NORTH); //Add Top Panel to North
this.add(middlePanel, BorderLayout.SOUTH); //Add Middle Panel to South
rather than at center.
Or you can create an intermediate container panel for these 2 panels, or consider other layout managers like BoxLayout, etc
I'm trying to open a window that has both an image and buttons in it. But I can't seem to figure out how to add the button. The image displays great and the menu works fine, but no matter where I add the button (into the JLabel, JPanel, or JFrame), it doesn't ever show...
Main:
public static void main(String[] args) {
GUI myGUI = new GUI();
myGUI.show();
}
GUI class: openImage is called when using the menu. The image then displays, but no button.
private JFrame myFrame;
private JPanel myPanel;
private JLabel myLabel;
public GUI()
{
myFrame = new JFrame();
initializePanel();
}
public void show()
{
myFrame.setSize(600,600);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.addMouseListener(this);
setupMenu(myFrame);
myFrame.setVisible(true);
}
private void initializePanel()
{
myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(500,500));
//myPanel.setLayout(new BorderLayout());
}
private void openImage(String fileName)
{
try {
myImage = ImageIO.read(new File(fileName));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myLabel = getJLabel();
JButton button = new JButton("ButtonClick");
button.addActionListener(this);
myFrame.setContentPane(myLabel);
myPanel.add(button);
myFrame.getContentPane().add(myPanel);
myFrame.pack();
myFrame.setSize(600,600);
}
private void setupMenu(JFrame window) {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem open = new JMenuItem("Open");
open.addActionListener(this);
file.add(open);
menubar.add(file);
window.setJMenuBar(menubar);
}
Your main issue is your setting the contentPane to be a JLabel -- don't do this! The contentPane needs to be opaque, needs to be built to be easily used as a Container and in your case, really should be a JPanel. JLabel I believe uses a null layout so it's no surprise that your code shows no button. If you want to show a background image, make have myPanel constructed from an anonymous class that extends JPanel, override the paintComponent method in this class (calling super.paintComonent first in the method), and draw the image in this method. Then you can add components to the contentPane which will now use a FlowLayout (the default for a JPanel) and it will be opaque by default.
Also, if your goal is to swap items displayed in your GUI, use a CardLayout to do the swapping for you as this layout makes swapping components a breeze.
really don't know, depends of method(s) how you are added picture to the JLabel, JPanel, or JFrame, but maybe for simle Container that contains a few, only one-two JComponents is there crazy idea, without side effects, with idea to display picture and to add there JButton:
JLabel is very similair JComponent to the JPanel, and is by default translucent and very simple implements Icon/ImageIcon, then you'll only to call myLabel.setIcon(myPicture)
to the all of JComponents you are/could be able to add another JComponent by using some of LayoutManager (Box, Flow, GridBagLayout)
You tried to set the label as the content pane and then tried to add the panel to that image which doesn't make sanse at all.
Change it so you add the label to the panel and have the panel as content pane:
Like this:
You have this line which is the problem. It doesn't make much sense:
myFrame.setContentPane(myLabel);
Try instead:
myFrame.getContentPane().add(myLabel);