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.
Related
I have an application where I use two JPanels. One of them is a PaintPanel. The second panel,the jtextfield and the jtextarea work fine but they look too cramped against the right side. I tried changing the sizes with setSize() but it didn't work.
The code for the paintpanel
public void center() {
jpCenter = new PaintPanel();
jpCenter.addMouseListener(this);
jpCenter.setSize(100, 100);
jpCenter.setBackground(Color.white);
add(jpCenter, BorderLayout.CENTER);
}
The code for the panel of the chatbox
public void east() {
// CREATE EAST Panel
gl = new GridLayout(4, 1);
jpEast = new JPanel();
jpEast.setSize(200, 200);
jpEast.setLayout(gl);
jpEast.setBackground(Color.white);
label = new JLabel("Number of shapes: ");
jpEast.add(label);
// ADD TEXT FIELD
jtf = new JTextField();
jtf.setText("");
jtf.setSize(200, 200);
jpEast.add(jtf);
// ADD BUTTON
jbSend = new JButton("Send");
jbSend.setEnabled(false);
jbSend.setSize(20, 60);
jpEast.add(jbSend);
jbSend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
send(jtf.getText());
jtf.setText("");
}
});
// ADD TEXT AREA
jta = new JTextArea("");
jta.setSize(100, 100);
jpEast.add(jta);
// ADD EAST panel
add(jpEast, BorderLayout.EAST);
}
Avoid setting the size of components since it can make them not work well on all platforms, and with JTextArea in particular, it will not allow it to expand correctly if held within a JScrollPane (which is where a JTextArea belongs). Note also that most layout managers don't even respect a component's size but rather its preferred size.
Instead, set the row and column properties of your JTextAreas (done most easily via the JTextArea(int row, int column) constructor), the column property of your JTextField, the font sizes of other components (if need be). Then allow your container (JPanel) layout managers and component's own preferred sizes size all appropriately when you call pack() on your top-level window (often a JFrame), after adding all components but before setting it visible.
For more specific help, consider posting an image of the GUI you're getting vs. the one you're trying to achieve.
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 new to Java and am trying to run this code. What could be error in the following code—my JTextField, txtfld, is shown just as a line instead of as a full text box?
public class calculator
{
public static void main(String s[])
{
JFrame j=new JFrame();
j.setSize(400,600);
JPanel p1=new JPanel();
JPanel p2=new JPanel();
p1.setSize(400, 100);
p2.setSize(400, 500);
p1.setLocation(0, 0);
p2.setLocation(0, 100);
p2.setLayout(new GridLayout(4,4));
j.add(p1);
j.add(p2);
JTextField txtfld=new JTextField();
txtfld.setSize(390, 92);
txtfld.setLocation(5, 2);
//txtfld.setVisible(true);
p1.add(txtfld);
j.setVisible(true);
}
}
JTextField txtfld=new JTextField();
You need to give a hint to the layout manager what the size should be.
So you should use something like:
JTextField txtfld=new JTextField(10);
Now the preferred size will be such that 10 "W" characters can be displayed in the text field before scrolling is required.
You should also pack() the frame before making it visible:
j.pack();
j.setVisible();
This will allow the frame to display all the components at their preferred sizes.
Also, get rid of all the setSize() and setLocation() statements. It is the job of the layout manager to set the size and location. Those values will be recalculated by the layout manager.
j.add(p1);
j.add(p2);
The default layout manager for a frame is a BorderLayout. So the above code will cause p2 to replace p1 on the frame.
Basically your entire code is wrong.
Start by reading the section from the Swing tutorial on How to Use Layout Managers for more information and working examples to get you started. Maybe start with the BorderLayout example, since this is the default layout of the frame you need to understand how it works first.
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);
}
I am trying to display 2 panels that I have created in separate files one at the top and one at the bottom of my GUI with a button group between them. However, the window is only displaying one panel or the button group at a time. The panels and button group are displaying properly but only the last one added to the frame is being displayed at any given execution.
Here is the current code without any layouts...
package UserGUI;
import javax.swing.*;
import java.awt.*;
public class RealFrame extends JFrame {
JButton Close = new JButton("Close");
JButton Proceed = new JButton("Proceed");
AuthorPanel header = new AuthorPanel();
FreeSpacePanel disk = new FreeSpacePanel();
public RealFrame() {
super();
ButtonGroup Ops = new ButtonGroup();
Ops.add(Close);
Ops.add(Proceed);
JPanel OPS = new JPanel();
OPS.add(Close);
OPS.add(Proceed);
add(disk);
add(OPS);
add(header);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
}
}
JFrame uses a BorderLayout by default, so when you do...
add(disk);
add(OPS);
add(header);
You're adding each component to the same location (the CENTRE position), but the BorderLayout will only layout the last one added.
Instead, you should use something more like...
add(disk, BorderLayout.NORTH);
add(OPS);
add(header, BorderLayout.SOUTH);
See How to Use Borders for more details
add(disk);
add(OPS);
add(header);
The default layout manager of the content pane of the JFrame is a BorderLayout. If you don't specify a constraint then the component is added to the BorderLayout.CENTER. Only one component can be added to the CENTER so the only the last component is displayed.
Try:
add(disk, BorderLayout.NORTH);
add(OPS, BorderLayout.CENTER);
add(header, BorderLayout.SOUTH);
to see the difference.
Or try another layout manager on the frame. See How to Use Layout Manager for more information.