I'm working on a log in server & my JTextFields aren't transparent when I set Opaque to false.
My code:
//username
JTextField jUsername = new JTextField(10);
jUsername.setBounds(520, 284, 190, 25);
jUsername.setOpaque(false);
jUsername.setBorder(null);
getContentPane().add(jUsername);
//password
JTextField jPassword = new JTextField(15);
jPassword.setBounds(520, 374, 190, 25);
jPassword.setOpaque(false);
jPassword.setBorder(null);
//jPassword.setBackground(new Color(Color.TRANSLUCENT));
getContentPane().add(jPassword);
An Image what is still happening:
Anyone ever seen this before or know how to fix it? I've looked around but no one had the same problem as I do, & the fixes for theirs didn't work for mine. ( I Know I'm not using JPasswordField for password, that's temporary )
Basically, the UI delegate of the text field paints not only the text but also the field area (within the border) regardless of the opaque setting.
What you can do, is set the background color to a transparent value, something like new Color(0, 0, 0, 0) for example, which is fully transparent.
For example...
JTextField jUsername = new JTextField(10);
jUsername.setBounds(520, 284, 190, 25);
jUsername.setBackground(new Color(0, 0, 0, 0));
jUsername.setOpaque(false);
jUsername.setBorder(null);
getContentPane().add(jUsername);
//password
JTextField jPassword = new JTextField(15);
jPassword.setBounds(520, 374, 190, 25);
jPassword.setBackground(new Color(0, 0, 0, 0));
jPassword.setOpaque(false);
jPassword.setBorder(null);
//jPassword.setBackground(new Color(Color.TRANSLUCENT));
getContentPane().add(jPassword);
You can affect the transparency of a color by changing the last parameter, for example new Color(255, 255, 255, 128) would white, 50% transparent...
You may also wish to change the caret color, take a look at JTextComponent#setCaretColor for more details
no idea what you tried, for better help sooner post an SSCCE, short. runnable, compilable with setBackground instead of Image
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class LabelImageText extends JPanel {
private static final long serialVersionUID = 1L;
public LabelImageText() {
JTextField jUsername = new JTextField(10);
jUsername.setText("MyText");
jUsername.setOpaque(false);
//jUsername.setBorder(null);
add(jUsername);
JTextField jPassword = new JTextField(15);
jPassword.setText("MyText");
jPassword.setOpaque(false);
//jPassword.setBorder(null);
add(jPassword);
setBackground(Color.RED);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("set Opaque");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new LabelImageText());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowUI();
}
});
}
}
I tried with another option and it worked for me.
You can modify the property Background of the textfield. Select the option custom code in the Selection Box and paste new Color(0, 0, 0, 0)in the txtField.setBackground property.
Then just change the border property to No border. and finally uncheck the opaque checkbox.
Here a capture of my netbeans interface
Related
So i am trying to make a Menu for a game i am working on.
I want to put an image as background at my menuPanel but i cant figure out how to let the image rescale every time i am raising the window. I have made a JLabel and i have imported an image from my main method and when i launch the game i can see that the image is correctly imported but i want to fill up all menuPanel and also stretch as i am raising the window to full screen or decreasing to the Minimum size of my frame.
How can i do that?
As you can see at the screenshot i want the text to be on top of the image and the image as a background and full screen.
public class Window extends Canvas{
private static final long serialVersionUID = 6331412385749386309L;
private static final int WIDTH = 1024, HEIGHT = WIDTH / 16 * 9;
private JFrame frame;
private JPanel mainPanel;
private JPanel menuPanel;
private JPanel buttonsPanel;
private JPanel playPanel;
private JPanel optionsPanel;
private JButton playBtn;
private JButton optionsBtn;
private JButton quitBtn;
private int currWidth = WIDTH, currHeight = HEIGHT;
public Window(String title, Game game) {
frame = new JFrame(title);
frame.setSize(1024, 576);
frame.setMinimumSize(new Dimension(WIDTH, HEIGHT));
frame.requestFocus();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
menu();
game.start();
}
private void menu() {
frame.getContentPane().setLayout(new BorderLayout(0, 0));
mainPanel = new JPanel();
mainPanel.setBackground(new Color(255, 255, 255));
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(new CardLayout(0, 0));
// menuPanel config
menuPanel = new JPanel();
menuPanel.setForeground(new Color(0, 0, 0));
menuPanel.setBackground(new Color(0, 0, 0));
mainPanel.add(menuPanel, "menuPanel");
buttonsPanel = new JPanel();
buttonsPanel.setBorder(null);
buttonsPanel.setBackground(new Color(0, 0, 0));
// playBtn config
playBtn = new JButton("Play");
playBtn.setForeground(new Color(255, 255, 255));
playBtn.setFont(new Font("Segoe Script", Font.BOLD, 40));
playBtn.setOpaque(false);
playBtn.setContentAreaFilled(false);
playBtn.setBorderPainted(false);
playBtn.setFocusPainted(false);
// optionsBtn config
optionsBtn = new JButton("Options");
optionsBtn.setForeground(new Color(255, 255, 255));
optionsBtn.setFont(new Font("Segoe Script", Font.BOLD, 35));
optionsBtn.setOpaque(false);
optionsBtn.setContentAreaFilled(false);
optionsBtn.setBorderPainted(false);
optionsBtn.setFocusPainted(false);
//quitBtn config
quitBtn = new JButton("Quit");
quitBtn.setForeground(new Color(255, 255, 255));
quitBtn.setFont(new Font("Segoe Script", Font.BOLD, 35));
quitBtn.setOpaque(false);
quitBtn.setContentAreaFilled(false);
quitBtn.setBorderPainted(false);
quitBtn.setFocusPainted(false);
GroupLayout gl_buttonsPanel = new GroupLayout(buttonsPanel);
gl_buttonsPanel.setHorizontalGroup(
gl_buttonsPanel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_buttonsPanel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_buttonsPanel.createParallelGroup(Alignment.LEADING)
.addComponent(quitBtn, GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
.addComponent(playBtn, GroupLayout.DEFAULT_SIZE, 175, Short.MAX_VALUE)
.addComponent(optionsBtn, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
gl_buttonsPanel.setVerticalGroup(
gl_buttonsPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_buttonsPanel.createSequentialGroup()
.addContainerGap()
.addComponent(playBtn)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(optionsBtn, GroupLayout.PREFERRED_SIZE, 74, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(quitBtn, GroupLayout.PREFERRED_SIZE, 71, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
buttonsPanel.setLayout(gl_buttonsPanel);
//
JLabel menuImageLabel = new JLabel(new ImageIcon(Game.menu_image.getScaledInstance(700, 400, Image.SCALE_FAST)));
//
GroupLayout gl_menuPanel = new GroupLayout(menuPanel);
gl_menuPanel.setHorizontalGroup(
gl_menuPanel.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_menuPanel.createSequentialGroup()
.addComponent(menuImageLabel, GroupLayout.PREFERRED_SIZE, 762, GroupLayout.PREFERRED_SIZE)
.addGap(0)
.addComponent(buttonsPanel, GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE))
);
gl_menuPanel.setVerticalGroup(
gl_menuPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_menuPanel.createSequentialGroup()
.addGap(161)
.addComponent(buttonsPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(124))
.addComponent(menuImageLabel, GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
);
menuPanel.setLayout(gl_menuPanel);
// playPanel config
playPanel = new JPanel();
playPanel.setBackground(new Color(0, 0, 255));
mainPanel.add(playPanel, "playPanel");
// optionsPanel config
optionsPanel = new JPanel();
optionsPanel.setBackground(new Color(255, 0, 0));
mainPanel.add(optionsPanel, "optionsPanel");
frame.setVisible(true);
setActions();
}
private void setActions() {
// playBtn action
playBtn.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
playBtn.setForeground(new Color(200, 210, 10));
}
public void mouseExited(MouseEvent e) {
playBtn.setForeground(new Color(255, 255, 255));
}
public void mouseClicked(MouseEvent e) {
menuPanel.setVisible(false);
playPanel.setVisible(true);
optionsPanel.setVisible(false);
}
});
// optionsBtn action
optionsBtn.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
optionsBtn.setForeground(new Color(200, 210, 10));
}
public void mouseExited(MouseEvent e) {
optionsBtn.setForeground(new Color(255, 255, 255));
}
public void mouseClicked(MouseEvent e) {
menuPanel.setVisible(false);
playPanel.setVisible(false);
optionsPanel.setVisible(true);
}
});
// quitBtn action
quitBtn.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
quitBtn.setForeground(new Color(200, 210, 10));
}
public void mouseExited(MouseEvent e) {
quitBtn.setForeground(new Color(255, 255, 255));
}
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
}
public void tick() {
mainPanel.getSize(new Dimension(currWidth, currHeight));
System.out.println(currWidth + ", " + currHeight);
}
public void render() {
}
}
Swing is based on parent/child relationships.
So if you want the button displayed on the background the structure of your code needs to be:
- frame
- background component
- buttons panel
The easiest way to do this is to use a JLabel with your image as the background. Then you add the buttons panel to the label. The only issue is that by default a JLabel doesn't use a layout manager so you need to see the layout manager to achieve your desired effect.
I would suggest using a GridBagLayout, then the buttons will be centered on the panel. The basic code would be:
JPanel buttons = new JPanel();
buttons.add(...);
JLabel background = new JLabel(...);
background.setLayout( new GridBagLayout() );
background.add(buttons, new GridBagConstraints());
The label will be displayed at the size of the background image.
If you want the background image to scale as the frame size changes, then you have a couple of options:
Use the Stretch Icon. It will automatically scale the image to the space available.
Replace the JLabel with a JPanel and paint the image yourself. Check out the Background Panel which can be configured to automatically scale an image.
Edit:
i tried reading the code and its really confusing.
Well, the intent was not for you to read the code. The intent was for you to use the code.
When you program you learn how to use classes and the methods of the class. When you use the ImageIcon class did you read the code first or just learn how to use its contructor?
Now I agree, the two classes don't have a published API but you really only need to understand the constructors and methods of the classes in order to use them.
If you read the Stretch Icon blog it states:
StretchIcon is a drop-in replacement for ImageIcon, which it extends, except that ImageIcon’s no-arg constructor isn’t supported.
So that means that if you would normally use:
JLabel background = new JLabel( new ImageIcon("background.jpg") );
you would use the following for the StretchIcon:
JLabel background = new JLabel( new StretchIcon("background.jpg") );
Similarly for the BackgroundPanel, if you read the blog it states that it is:
an extension of JPanel that provides some custom painting support for the drawing of images
It then goes on to say that the default is to paint the image "scaled" which is what you want. So all you need to figure out is which constuctor to use to create the panel.
For a regular panel you would use:
JPanel background = new JPanel();
For the BackgroundPanel the simplest constructor to use would be the first constructor of the class which simply takes an Image as a parameter:
JPanel background = new BackgroundPanel(image);
Now you have a panel and you simply add your 3 buttons to the panel.
I did not write the StretchIcon class so I don't know the details of the code, and I don't care about the details as long as the class does what I expect it to do.
I did write the BackgroundPanel class so if you has specific questions then I can probably help you. But I don't have time to guess which part of the code you find confusing.
Edit 2:
I have 3 buttons and i want them to be at the cemter and stretch too so they stay at the center of the image
This is about learning how to use layout managers. I never use an IDE to generate my code. I want full control over the code. This allows your code to be cleaner an more easily maintained.
This allows you to choose the appropriate layout manager for the job and allows you to easily nest panels with different layout mangers. In this case you want to use the GridBagLayout which by default will center horizontally and vertically any component added to it.
By default the BackgroundPanel uses a BorderLayout. But you can easily change it to use the GridBagLayout. Then I would use a second panel with a GridLayout for the buttons.
So the code would be something like:
JPanel buttonPanel = new JPanel( new GridLayout(0, 1, 10, 0) );
buttonPanel.add(playBtn);
...
backgroundPanel.add(buttonPanel, new GridBagConstraints());
Now as the frame size is changed the buttons will automatically re-center.
Read the section from the Swing tutorial on Layout Managers for more information and examples.
Keep a link to the Swing tutorial handy. It contains information and example of most Swing basics.
You could use the method paintComponent(Graphics g) and drawImage() from JPanel to draw your Image.
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class AutoScale extends JFrame{
private Image image;
public AutoScale() {
setTitle("AutoScale");
setResizable(true);
setSize(400,400);
try {
image = ImageIO.read(new File("path to your file"));
}catch(IOException e) {
System.out.println("Image not found");
}
JPanel panelImg = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 30, 30, getWidth()/2, getHeight()/2, null);
}
};
add(panelImg);
}
public static void main(String[] args) {
AutoScale frame = new AutoScale();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
In this example, I create the Panel and paintComponent(). Inside that method, I invoke drawImage() with 6 parameters:
The Image
x Coordinate
y Coordinate
The width of the Frame divided by 2(you can play with the size of your image by adding, substracting or dividing the result of
getWidth())
The height of the Frame divided by 2(same as the width)
The imageObserver, which generally is set to null.
The paintComponent() method gets invoke automatically whenever the size of the Panel changes, so there's no need to use a WindowListener as I suggested earlier.
Note: I use a try-catch block because if it can't find the file, it will throw an Exception.
Hope this was helpful!
JTextField textbox1;
textbox1 = new JTextField();
textbox1.setBounds((549+x),(61+y),295,17);
textbox1.setOpaque(false);
Main.panel.add(textbox1);
I need a Textbox on top of an image to show the image underneath but still be able to be typed in. I've tried using the textbox1.setOpaque(false) method but it didn't change anything and didn't throw and error. Sorry if i didn't format the code properly I tried but I just don't use this site very often.
set only the background of the text box to transparent
setBackground(new Color(0,0,0,0));
Use
setOpaque(false);
Only when your text field has child components inside the textfield you want to make visible but not the textfield itself to avoid artifacts
The following example has a text field over a red circle.
import javax.swing.*;
import java.awt.*;
public class JunkStop{
public static void main(String[] args){
JFrame frame = new JFrame("wakka");
JPanel layout = new JPanel(null);
JPanel background = new JPanel(){
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(100, 100, 200, 200);
}
};
background.setOpaque(false);
JTextField field = new JTextField("testing");
field.setBackground( new Color(0, 0, 0, 0) );
layout.add(field);
layout.add(background);
field.setSize(new Dimension(200, 20));
field.setBounds(100, 150, 200, 20);
background.setBounds(0, 0, 400, 400);
frame.setContentPane(layout);
frame.setVisible(true);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I apologise now if my terminology or turns of phrase aren't right, I'm new to swing. Also, apologise for the clunky and intelligent way I've tried to get this to work.
I am trying to create a single box that has a JTextArea inside it, and next this this area (still in the same box), has some buttons. However, all I've managed to do is make a box with the buttons in, and a separate box with a text area.
I have looked at many examples where people are trying to do similar things and I thought I managed to understand and implement it, but I haven't yet succeeded. If someone could point me at the part(s) of the code I'm misunderstanding I would be very grateful.
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.*;
public class GameGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JPanel panel = new JPanel();
JTextArea textArea = new JTextArea(50, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
String action;
private static GUIClient client = new GUIClient();
JButton n = new JButton("N");
JButton e = new JButton("E");
JButton s = new JButton("S");
JButton w = new JButton("W");
JButton look = new JButton("LOOK");
JButton pickup = new JButton("PICKUP");
JButton hello = new JButton("HELLO");
JButton quit = new JButton("QUIT");
public GameGUI()
{
textArea.setEditable(false);
panel.add(new JScrollPane(textArea));
this.setBounds(300, 300, 750, 500);
this.setVisible(true);
this.setResizable(false);
this.setLayout(null);
n.setBounds(225, 25, 50, 50);
e.setBounds(300, 100, 50, 50);
s.setBounds(225, 175, 50, 50);
w.setBounds(150, 100, 50, 50);
look.setBounds(50, 362, 100, 50);
pickup.setBounds(200, 362, 100, 50);
hello.setBounds(350, 362, 100, 50);
quit.setBounds(500, 362, 100, 50);
this.add(n);
this.add(e);
this.add(s);
this.add(w);
this.add(look);
this.add(pickup);
this.add(hello);
this.add(quit);
n.addActionListener(this);
e.addActionListener(this);
s.addActionListener(this);
w.addActionListener(this);
look.addActionListener(this);
pickup.addActionListener(this);
hello.addActionListener(this);
quit.addActionListener(this);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public void displayInGUI(String fromServer)
{
textArea.append(fromServer);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
public void actionPerformed(ActionEvent f)
{
if(f.getSource()==n)
{
action = "MOVE N";
client.display(action);
}
else if(f.getSource()==e)
{
action = "MOVE E";
client.display(action);
}
else if(f.getSource()==s)
{
action = "MOVE S";
client.display(action);
}
else if(f.getSource()==w)
{
action = "MOVE W";
client.display(action);
}
else if(f.getSource()==look)
{
action = "LOOK";
client.display(action);
}
else if(f.getSource()==pickup)
{
action = "PICKUP";
client.display(action);
}
else if(f.getSource()==hello)
{
action = "HELLO";
client.display(action);
}
else if(f.getSource()==quit)
{
action = "QUIT";
client.display(action);
}
}
}
I've used this class by creating an instance of it in GUIClient (I've also created an instance of GUIClient in this class, GameGUI, which seems really ugly but it was the only way I could think to notice when the buttons were pressed).
So, if I want to run the game, I set up the server, then run GUIClient, which creates the two boxes. GUIGame then notices when the buttons are pressed and sends this info to the client which sends it to the server.
Again, I'm sorry this is so convoluted. I hope my explanation helped clear things up but if not just let me know.
Many thanks,
Elise.
I added a 'main()' method (and commented out the client parts) so I could run your program. I also set the Frame's size to 800x500 so it is visible. This is what I see:
The reason the text area is not visible is you did not add it to the frame. You will need to add the panel that contains the scrollpane that contains the textarea to the frame. You will also need to position and size it. For example:
panel.setBounds(400, 25, 200, 200);
this.add(panel);
This produces the following:
I am creating a GUI in java. Currently i have an empty JFrame and am trying to add a JPanel to it. The JPanel contains buttons, text etc. However none of this is being displayed. My code is as follows:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class memoDisplayUI {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextArea jTextBox = new JTextArea();
JScrollPane scroll = new JScrollPane();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
memoDisplayUI frame = new memoDisplayUI();
frame.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public memoDisplayUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, 270, 400);
frame.setUndecorated(true); //REMOVES MENU BAR
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblMemos = new JLabel("MEMOS");
lblMemos.setForeground(new Color(100, 149, 237));
lblMemos.setFont(new Font("Moire", Font.BOLD, 30));
lblMemos.setBounds(16, 16, 234, 37);
panel.add(lblMemos);
JButton button = new JButton("");
button.setBackground(new Color(100, 149, 237));
button.setBounds(7, 350, 40, 40);
panel.add(button);
button.setIcon(new ImageIcon("back.png"));
JButton button_1 = new JButton("");
button_1.setBackground(new Color(100, 149, 237));
button_1.setBounds(113, 350, 40, 40);
panel.add(button_1);
button_1.setIcon(new ImageIcon("Edit.png"));
JButton button_2 = new JButton("");
button_2.setBackground(new Color(100, 149, 237));
button_2.setBounds(220, 350, 40, 40);
panel.add(button_2);
button_2.setIcon(new ImageIcon("memo.png"));
JButton btnExit = new JButton("");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setBorder(null);
btnExit.setIcon(new ImageIcon("Exit.jpg"));
btnExit.setBounds(216, 19, 40, 40);
panel.add(btnExit);
jTextBox = new JTextArea();
scroll.setViewportView(jTextBox); // add scroll panel
jTextBox.setTabSize(4);
jTextBox.setLineWrap(true);
jTextBox.setBackground(new Color(192, 192, 192));
jTextBox.setBounds(8, 60, 255, 286);
panel.add(jTextBox);
frame.getContentPane().add(panel);
}
}
Could someone please advise as to why this is?
Thanks very much :)
Edit
From a few tweaks to the code, it appears this is the desired layout (in a non-resizable GUI).
I think you used null to get a "place it wherever fits"? Then use a FlowLayout
frame.setLayout(new FlowLayout());
That should fix it :)
Could someone please advise as to why this is?
Using null layouts and not calling pack().
The image I edited into the question was obtained as a screenshot of the GUI after I had commented out the call to setUndecorated(true) and dragged it a little bigger. Doing so causes the JRE to validate the component structure (what pack() would do) and thereby make the components appear.
As I mentioned in a comment:
..a better question would be "How to layout this GUI?" (so long as you provide an attempt)
And that leads me to my first comment. (Now in longer form)
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
So coming back to:
(so long as you provide an attempt)
Look over those two examples to see how they work, then attempt to combine some layouts and padding to create a frame that can then be packed to reduce to the natural size.
And a tip the the JTextArea. Suggest a size in columns x rows combined with the Font size.
1: You should never call setLayout(null).
2: Try frame.validate() to layout the components with your layout.
Replace
frame.getContentPane().setLayout(null);
with
frame.getContentPane().setLayout(new BorderLayout());
Good luck.
Edit: For future reference, to decide which LayoutManager should be used in your case, you should refer to this Visual Guide to LayoutManagers.
Just remove/comment this line from the above code at line number 46.
// frame.getContentPane().setLayout(null);
It should work fine..
Maybe you shoul replace :
frame.getContentPane().add(panel);
by
frame.setContentPane(panel);
Hope it helped
Someone told me a way to paint onto a Jframe and it worked fine in the example, but now I have tabs it doesn't paint onto them.
I need the paint/drawLine to work in my Tabbed example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.io.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
public class GUI extends JTabbedPane implements ActionListener
{
static JFrame aWindow = new JFrame("Project");
JTabbedPane myTabs = new JTabbedPane();
JPanel loginMainPanel = new JPanel();
JPanel displayMainPanel = new JPanel();
JPanel editMainPanel = new JPanel();
JTextField myText1 = new JTextField("");
JTextField myText2 = new JTextField("");
JTextField myText3 = new JTextField("");
JLabel loginLabel = new JLabel("Username:");
JTextField loginField = new JTextField();
JLabel loginLabel2 = new JLabel("Password:");
JPasswordField loginPass = new JPasswordField();
JButton displayButton = new JButton("Load Data");
JButton loginButton = new JButton("Login");
JLabel editLabel = new JLabel("Write:");
JTextArea editArea = new JTextArea();
public GUI()
{
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize = theKit.getScreenSize();
aWindow.setBounds(wndSize.width/3, wndSize.height/3, 250, 250);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(1,1);
Container content = aWindow.getContentPane();
content.setLayout(grid);
createLoginPanel();
createDisplayPanel();
createEditPanel();
myTabs.addTab("Login", loginMainPanel);
myTabs.addTab("Main Menu", displayMainPanel);
myTabs.addTab("Setting", editMainPanel);
myTabs.setSelectedIndex(0);
myTabs.setEnabledAt(1,false);
myTabs.setEnabledAt(2,false);
content.add(myTabs);
aWindow.setVisible(true);
}
public void createLoginPanel()
{
loginMainPanel.setLayout(null);
loginLabel.setBounds(10, 15, 150, 20);
loginMainPanel.add(loginLabel);
loginField.setBounds(10, 35, 150, 20);
loginMainPanel.add(loginField);
loginLabel2.setBounds(10, 60, 150, 20);
loginMainPanel.add(loginLabel2);
loginPass.setBounds(10, 80, 150, 20);
loginMainPanel.add(loginPass);
loginButton.addActionListener(this);
loginButton.setBounds(50, 110, 80, 20);
loginMainPanel.add(loginButton);
}
public void createDisplayPanel()
{
displayMainPanel.setLayout(null);
displayButton.addActionListener(this);
displayButton.setBounds(50, 80, 150, 20);
displayMainPanel.add(displayButton);
myText1.setBounds(50, 170, 200, 30);
myText2.setBounds(50, 140, 200, 30);
myText3.setBounds(50, 110, 200, 30);
displayMainPanel.add(myText1);
displayMainPanel.add(myText2);
displayMainPanel.add(myText3);
}
public void createEditPanel()
{
editMainPanel.setLayout(null);
editLabel.setBounds(10, 15, 150, 20);
editMainPanel.add(editLabel);
editArea.setBounds(10, 65, 150, 50);
editMainPanel.add(editArea);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == loginButton)
{
//myTabs.setSelectedIndex(1);
}
}
public void paint(Graphics g) {
super.paint(g);
int locX = 0;
int locY = 0;
int destX = 210;
int destY = 210;
g.setColor(Color.red);
// draw a line (there is now drawPoint..)
g.drawLine(locX, locY, destX, destY);
}
public static void main(String[] args)
{
GUI tw1 = new GUI();
}
}
How can I find a solution so it will paint that line on the tab (loginMainPanel)?
If you want custom drawing on a JPanel, you should create a custom class that extends JPanel:
class CustomPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(x1, y1, x2, y2);
}
}
Then:
JPanel loginMainPanel = new JPanel();
Woudl become:
JPanel loginMainPanel = new CustomPanel();
Sorry for the blurge of bloated code
Yes, well that is why people can't solve problems, because the code is so bloated you can't see what you are doing.
If you want us to help you problem solve then you need to post a SSCCE
Someone told me a way to paint onto a Jframe
Well, that is wrong, in general you should not be overrding the paint() method, unless you have a specific reason.
Also, your whole program is wrong because you are extending JTabbedPane. You should never do this to create a GUI.
Your paint() method is never invoked because you never use that class anywhere. Look at your code. For your class variables you create a new JTabbedPane. Then in the constructor you add all these components to the frame and make the frame visible.
You need to take a look at the Swing tutorial and follow some of the example there for a better way to create a simple GUI.
I don't understand what you are trying to do by drawing a line on the tabbed pane. A tabbed pane displays different panels every time you click on a tab. Where exactly do you want the line to appear?
Also, you should learn how to use layout managers. Using a null layout will cause unnecessary problems.
Until you post a SSCCE, I can't be of much help.