Why JTextArea not showing in GUI ?
public class AddMovie extends JTextField {
static JFrame frame;
private JLabel description;
JTextArea movieDescription;
public JPanel createContentPane() throws IOException
{
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
totalGUI.setBackground(Color.WHITE);
description = new JLabel("Description ");
description.setLocation(15,285);
description.setSize(120, 25);
description.setFont(new java.awt.Font("Tahoma", 0, 12));
movieDescription=new JTextArea();
movieDescription.setLocation(15,320);
movieDescription.setSize(420, 110);
JScrollPane scrollPane = new JScrollPane(movieDescription);
totalGUI.add(description);
totalGUI.add(movieDescription);
totalGUI.add(cancel);
totalGUI.add(scrollPane);
return totalGUI;
}
static void createAndShowGUI() throws IOException
{
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("New Movie");
//Create and set up the content pane.
AddMovie demo = new AddMovie();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(515, 520);
frame.setLocation(480,120);
frame.setVisible(true);
}
public void setVisible(boolean b) {
// TODO Auto-generated method stub
}
}
As suggested here and here, a null layout invites trouble. Because your display centers on the description, use the JTextArea constructor that lets you specify a size in rows and columns. When you pack() the enclosing Window, it will be resized to fit the text area. I've added some ad hoc text to illustrate the effect. I've also updated the code to allow the text area to grow when resizing the frame.
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
* #see https://stackoverflow.com/a/38282886/230513
*/
public class Test {
private JPanel createPanel() {
JPanel panel = new JPanel(new GridLayout());
//panel.setBorder(BorderFactory.createTitledBorder("Description"));
JTextArea movieDescription = new JTextArea(10, 20);
panel.add(new JScrollPane(movieDescription));
movieDescription.setLineWrap(true);
movieDescription.setWrapStyleWord(true);
movieDescription.setText(movieDescription.toString());
return panel;
}
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(createPanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}
totalGUI.setLayout(null);
There's the 1st problem you should solve: Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Besides many other problems, it typically destroys the ability of scroll-panes to do the job they were designed for.
General tips:
There is no attribute named cancel.
Don't override methods like setVisible(boolean) then leave them empty! That is achieving nothing more than breaking functionality that works just fine as it is!
The movieDescription is added to both the totalGUI & the scroll pane. It should only be added to the scroll pane.
A white text area added to a white BG will be invisible except for the caret.
The Tahoma font will only be available in some OS'
Rather than use a JLabel for the description, you might also add the text area to a panel and set the Description text to a TitledBorder used on a panel that the text area is placed in.
Nothing in the two wethods that declare throws IOException could actually cause one.
In the createAndShowGUI method you are creating again a AddMovie object..
so if you modifiy the coda as following, it will work...
Example:
public class AddMovie extends JTextField {
private static final long serialVersionUID = 6180900736631578119L;
private JFrame frame;
private JLabel description;
private JTextArea movieDescription;
public JPanel createContentPane() {
JPanel totalGUI = new JPanel();
totalGUI.setBackground(Color.WHITE);
description = new JLabel("Description ");
description.setLocation(15, 285);
description.setSize(120, 25);
description.setFont(new java.awt.Font("Tahoma", 0, 12));
movieDescription = new JTextArea();
movieDescription.setLocation(15, 320);
movieDescription.setSize(420, 110);
JScrollPane scrollPane = new JScrollPane(movieDescription);
totalGUI.add(description);
totalGUI.add(movieDescription);
totalGUI.add(scrollPane);
return totalGUI;
}
public void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("New Movie");
frame.setContentPane(createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(515, 520);
frame.setLocation(480, 120);
frame.setVisible(true);
}
public static void main(String[] args) {
AddMovie am = new AddMovie();
am.createAndShowGUI();
}
}
Related
I am programming a Swing based UI Component in Java 8, that basically displays multiple JTextPanes in a vertically scrollable Field and has a Toolbar for basic style manipulation (Font, Font Size, Bold, etc.)
For this I am using a JPanel, which also implements Scrollable inside a JScrollPane, that contains multiple JTextPanes using a vertical BoxLayout.
When I start this, it looks fine and all TextPanes are high enough to fit one line of text and scale when more is typed. The Problem occurs, when I change the font size. When the font size changes, the JTextPane should automatically resize to fit the new text, but when I use a button to change it, the size only changes when I click it twice.
Here are some screenshots to explain what I mean:
This is after the example starts, and I add some text to the top JTextPane. There are 2 TextPanes here.
This is after the first click to the button, which sets the font size to 30pt. The text is larger, but the JTextPane does not resize to fit it
And this is after I click the button again. The JTextPane now scaled correctly
I already tried to call invalidate, revalidate and repaint manually on the JTextPane and its parents, but that had no effect.
The JTextPane also resizes when another Attribute is changed (e.g. bold) or the FontSize is change to another value. But it seems to always be one change behind.
So when the FontSize is changed to 20, then to 30, it will resize to fit 20pt font when the FontSize is set to 30pt.
Does anybody have an Idea what could cause the problem and how I can fix it?
Here is the code of the minimal example:
public class TestEditorPanes {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(getPanel());
frame.setSize(720, 480);
frame.setVisible(true);
}
private static JPanel getPanel() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel editorPanel = new ScrollablePanel();
editorPanel.setLayout(new BoxLayout(editorPanel, BoxLayout.Y_AXIS));
JTextPane textPane1 = new JTextPane();
JTextPane textPane2 = new JTextPane();
editorPanel.add(textPane1);
editorPanel.add(textPane2);
mainPanel.add(new JScrollPane(editorPanel), BorderLayout.CENTER);
// Button sets Font size to 30
JButton btnFontSize = new JButton("FontSize");
btnFontSize.addActionListener(e -> {
MutableAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setFontSize(attrs, 30);
textPane1.setCharacterAttributes(attrs, false);
});
mainPanel.add(btnFontSize, BorderLayout.NORTH);
return mainPanel;
}
private static class ScrollablePanel extends JPanel implements Scrollable {
#Override
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
#Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 30;
}
#Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 30;
}
#Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
#Override
public boolean getScrollableTracksViewportHeight() {
return false;
}
}
}
I modified your code to create this GUI.
The main change I made was in your ActionListener. By using the StyledDocument setCharacterAttributes method, I didn't have to select the text first. It appears that setting the JTextPane font size caused the JTextPane to resize properly.
JButton btnLargeFont = new JButton("Large Font");
btnLargeFont.addActionListener(e -> {
StyleConstants.setFontSize(attributes, 30);
StyledDocument doc = textPane1.getStyledDocument();
doc.setCharacterAttributes(0, doc.getLength(), attributes, true);
textPane1.setFont(textPane1.getFont().deriveFont((float) 30));
});
Here's the complete runnable code I used.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class TestEditorPanes implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new TestEditorPanes());
}
private JFrame frame;
private MutableAttributeSet attributes;
public TestEditorPanes() {
this.attributes = new SimpleAttributeSet();
}
#Override
public void run() {
frame = new JFrame("Editor Panes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel getPanel() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel editorPanel = new JPanel();
editorPanel.setLayout(new BorderLayout());
editorPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JTextPane textPane1 = new JTextPane();
textPane1.setPreferredSize(new Dimension(400, 150));
StyleConstants.setFontSize(attributes, 14);
textPane1.setCharacterAttributes(attributes, true);
JTextPane textPane2 = new JTextPane();
textPane2.setPreferredSize(new Dimension(400, 150));
editorPanel.add(new JScrollPane(textPane1), BorderLayout.NORTH);
editorPanel.add(new JScrollPane(textPane2), BorderLayout.SOUTH);
mainPanel.add(new JScrollPane(editorPanel), BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 10, 10));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// Button sets Font size to 14
JButton btnNormalFont = new JButton("Normal Font");
btnNormalFont.addActionListener(e -> {
StyleConstants.setFontSize(attributes, 14);
StyledDocument doc = textPane1.getStyledDocument();
doc.setCharacterAttributes(0, doc.getLength(), attributes, true);
textPane1.setFont(textPane1.getFont().deriveFont((float) 14));
});
buttonPanel.add(btnNormalFont, BorderLayout.NORTH);
// Button sets Font size to 30
JButton btnLargeFont = new JButton("Large Font");
btnLargeFont.addActionListener(e -> {
StyleConstants.setFontSize(attributes, 30);
StyledDocument doc = textPane1.getStyledDocument();
doc.setCharacterAttributes(0, doc.getLength(), attributes, true);
textPane1.setFont(textPane1.getFont().deriveFont((float) 30));
});
buttonPanel.add(btnLargeFont, BorderLayout.SOUTH);
mainPanel.add(buttonPanel, BorderLayout.NORTH);
return mainPanel;
}
}
I have found a solution that works for what I want it to.
When I tried debugging the problem, I noticed, that the Swing View, that renders the Component does not update its preferred size after changing character attributes for some reason.
Manually calling updateUI() on the JTextPane after changing the FontSize forces the UI to reload and compute a new size for the component.
This is the working version of the ActionListener for my minimal example:
btnFontSize.addActionListener(e -> {
MutableAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setFontSize(attrs, 30);
textPane1.setCharacterAttributes(attrs, true);
//Call updateUI to force recalculation of size
textPane1.updateUI();
});
Gilbert Le Blancs answer would also work, if I didn't need the JTextPanes to be directly below each other and seems to be the cleaner solution for me (notice he calls setPreferredSize() manually, so the UI does not have to calculate the size).
If someone knows the reason for this behavior or a better solution, please let me know.
I've been trying to setup a JFrame with text but I'm having trouble. I can create the JFrame, but I can't get a background color or text to work with it.
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class FundManager {
JFrame window;
JPanel panel;
JLabel text;
public void createWindow()
{
//Create the window
window = new JFrame();
window.setVisible(true);
window.setSize(960, 540);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
//Create the panel
panel = new JPanel();
panel.setBackground(Color.RED);
//Create the label
text = new JLabel("test");
}
public static void main(String args[]) {
FundManager.createWindow();
}
}
My createWindow() method is not running and I get the error:
cannot make a static reference to to the non-static method.
However, when I make it static the whole program breaks.
The issue here is that you need an instance of FundManager before you can call the method createWindow(). Try the code below instead.
new FundManager().createWindow();
First of all, you cannot make a call to FundManager.createWindow(), because createWindow() is not a static method. You need an instance of FundManager.
Furthermore, you are not adding the panel nor the text field to the frame. You are only declaring them. This is a quick example of how you could locate the elements inside the frame:
JFrame window;
JPanel panel;
JLabel text;
public void createWindow() {
// Create the window
window = new JFrame();
window.setVisible(true);
window.setSize(960, 540);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
// Create the panel
panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 500));
panel.setBackground(Color.RED);
// Create the label
text = new JLabel("test");
text.setPreferredSize(new Dimension(200, 30));
text.setLocation(100, 100);
panel.add(text);
window.getContentPane().add(panel);
window.pack();
}
And run this with:
new FundManager().createWindow();
The assignment is simple, all we need to do is have the code create a window with a red panel with a single button and label. Here is the code thus far as well as the tester class.
I got the label to display on the window, but its in a weird place. I cant get the button to display at all as well getting the background to display as red.
This is where I'm having trouble with the most:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyCustomFrame extends JFrame
{
public MyCustomFrame()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createComponents()
{
JPanel panel=new createPanel();
button=new JButton("Push Me");
label=new JLabel("This is a label");
add(button);
add(label);
}
private JButton button;
private JLabel label;
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 800;
public void createPanel()
{
JPanel panel=new JPanel();
panel.setBackground(Color.RED);
//button=new JButton("Push Me");
//label=new JLabel("This is a label");
}
public void createFrame()
{
JFrame frame=new JFrame();
add(frame);
frame.setVisible(true);
}
}
And this is the tester class:
import javax.swing.JFrame;
public class MyCustomFrameViewer
{
public static void main(String[] args)
{
MyCustomFrame frame = new MyCustomFrame();
frame.setTitle("My first frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You create the JPanel, panel, but add nothing to it, and then never add the panel to your JFrame. You should add your components to the JPanel, panel, and then add the panel object to your JFrame.
Note that a JPanel uses FlowLayout by default, and so it will more easily accept multiple other components without special add methods. The JFrame's contentPane uses BorderLayout which is slightly more complicated to use.
Add the panel to the frame instead of the label and button, and add the label and button to the panel...
private void createComponents()
{
JPanel panel=new createPanel();
add(panel);
button=new JButton("Push Me");
label=new JLabel("This is a label");
panel.add(button);
panel.add(label);
}
You may also want to take a look at Initial Threads and make sure you are creating your UI from within the context of the Event Dispatching Thread
Some side notes...
This scares me...
public void createFrame()
{
JFrame frame=new JFrame();
add(frame);
frame.setVisible(true);
}
You're trying to add a frame to a frame, which is an illegal operation in Swing, but thankfully, you're not actually calling it from what I can see.
Instead of using setSize(FRAME_WIDTH, FRAME_HEIGHT);, you may wish to use pack instead.
See also the tips in comments in this example:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
// Don't extend frame, just use an instance
//public class MyCustomFrame extends JFrame {
public class MyCustomFrame {
private JFrame frame;
private JButton button;
private JLabel label;
private JPanel panel;
// better to override the preferred size of the component of interest
final int GAME_WIDTH = 300;
final int GAME_HEIGHT = 100;
public MyCustomFrame() {
createComponents();
// better to override the preferred size of the component of interest
//setSize(GAME_WIDTH, GAME_HEIGHT);
}
private void createComponents() {
// compilation error! createPanel() does not return anything..
//JPanel panel = new createPanel();
createPanel();
// create the frame!
createFrame();
}
private void createPanel() {
// creates a local instance
//JPanel panel = new JPanel();
panel = new JPanel() {
/* override the preferred size of the component of interest */
#Override
public Dimension getPreferredSize() {
return new Dimension(GAME_WIDTH, GAME_HEIGHT);
}
};
panel.setBackground(Color.RED);
button = new JButton("Push Me");
label = new JLabel("This is a label");
panel.add(button);
panel.add(label);
}
private void createFrame() {
// create a local instance of a JFrame that goes out of scope at end
// of method..
//JFrame frame = new JFrame();
frame = new JFrame("My first frame");
// add the panel to the frame!
frame.add(panel);
// better to use DISPOSE_ON_CLOSE
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// a good way to position a GUI
frame.setLocationByPlatform(true);
// this was trying to add a JFrame to another JFrame
//add(frame);
frame.pack();
}
public final JFrame getFrame() {
return frame;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
MyCustomFrame myFrame = new MyCustomFrame();
JFrame frame = myFrame.getFrame();
frame.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
I am new to Java and mostly CardLayout. I want to simply switch "windows" represented by JPanels. I read somewhere that job for CardLayout. But my problem is, when add chatPanel to mainPanel (this is the CardLayout one), it shifts the content of connectPanel several pixels to the top, away from its centered position. Is I skip in my code createChatPanel(), its where it should be.
I have this code:
package App;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import Validators.*;
public class GUI {
private JFrame mainFrame = null;
private JPanel mainPanel = null;
private CardLayout cl = new CardLayout();
public GUI(){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (UnsupportedLookAndFeelException e) {
}
catch (ClassNotFoundException e) {
}
catch (InstantiationException e) {
}
catch (IllegalAccessException e) {
}
mainFrame = new JFrame("MainChat");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(640,480);
mainFrame.setLocationRelativeTo(null);
mainFrame.setResizable(false);
mainFrame.setLayout(new GridBagLayout());
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu("Soubor");
JMenu menuHelp = new JMenu("Nápověda");
menuBar.add(menuFile);
menuBar.add(menuHelp);
menuFile.add(new JMenuItem("Nové Připojení"));
menuFile.add(new JSeparator());
menuFile.add(new JMenuItem("Konec"));
menuHelp.add(new JMenuItem("O programu"));
mainFrame.setJMenuBar(menuBar);
createMainPanel();
createConnectPanel();
createChatPanel();
mainFrame.setVisible(true);
}
public void createMainPanel() {
mainPanel = new JPanel(cl);
mainFrame.add(mainPanel);
}
public void createConnectPanel() {
JPanel connectPanel = new JPanel();
mainPanel.add(connectPanel,"connectPanel");
JTextField ip = new JTextField();
ip.setDocument(new JTextFieldLimit(15));
ip.setColumns(11);
JLabel iplabel = new JLabel("IP:");
connectPanel.add(iplabel);
connectPanel.add(ip);
JButton connect = new JButton("Connect");
connect.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(mainPanel,"chatPanel");
}
});
connectPanel.add(connect);
}
public void createChatPanel(){
JPanel chatPanel = new JPanel();
mainPanel.add(chatPanel,"chatPanel");
JTextArea chatbox = new JTextArea();
chatbox.setPreferredSize(new Dimension(200,200));
chatPanel.add(chatbox);
}
}
Please, what I messed up? Thanks.
Since you are adding two JPanels to your main JPanel,
these two panels both need to fit within the main panel.
If one of the inner panels is much larger than the other one,
the main panel will adjust to fit the larger one.
E.g. commenting this line:
chatbox.setPreferredSize(new Dimension(200,200));
would cause your text field to stay put. This is because the
chatbox would not cause the container to resize.
Also note that the main panel is not initially the same size as your
main frame, since you have not set the size of the main panel.
If you would set the size of the connectPanel to the same size
as your main frame, the connectPanel would not
be automatically resized when adding the chatPanel (as a
consequence of the mainPanel being resized)
So what you could do is add the middle line in:
JPanel connectPanel = new JPanel();
connectPanel.setSize(640, 480);
mainPanel.add(connectPanel, "connectPanel");
, which probably would solve your problem.
Although this would work, I definitely recommend using
MIG Layout for
all your GUI designing. It will save you plenty of time if
you take an hour to learn it. It will also save you from
having to set sizes manually (and thereby saving you from
having to rewrite half your GUI code with every design change).
If you want a JPanel centered in another, place your connectPanel in another JPanel that acts as a dumb container, and have this container use GridBagLayout. Then if you add the connectPanel to the container without any GridBagConstraints, it will be added to the default position for GridBagLayout which is centered. You can then add this container JPanel to your mainPanel using the same constant that you would have used for your connectPanel.
I would tend to let the layouts determine the size of components and avoid using setSize and even setPreferredSize, and would definitely call pack() on my JFrame prior to setting it visible. You definitely don't want to set the size or preferredSize of your JTextField, but rather set its columns and rows and place it in a JScrollPane, and then add that JScrollPane to the view.
Edit:
Here's an example that shows placement of something like your connect panel at the top, middle and bottom of a small gui. Just press the "Next" button to see what I mean:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI2 extends JPanel {
public static final String CONNECT_NORTH = "connect north";
public static final String CONNECT_CENTER = "connect center";
private static final String CONNECT_SOUTH = "connect south";
private static final String CHAT_PANEL = "chat panel";
private CardLayout cardlayout = new CardLayout();
public GUI2() {
setLayout(cardlayout);
add(createConnectPanel(BorderLayout.NORTH), CONNECT_NORTH);
add(createConnectPanel(BorderLayout.CENTER), CONNECT_CENTER);
add(createConnectPanel(BorderLayout.SOUTH), CONNECT_SOUTH);
add(createChatPanel(), CHAT_PANEL);
}
public void nextPanel() {
cardlayout.next(this);
}
private JPanel createConnectPanel(String borderlayoutLocation) {
JPanel innerPanel = new JPanel();
innerPanel.add(new JLabel("IP:"));
innerPanel.add(Box.createHorizontalStrut(5));
innerPanel.add(new JTextField(11));
innerPanel.add(Box.createHorizontalStrut(5));
innerPanel.add(new JButton(new AbstractAction("Next") {
#Override
public void actionPerformed(ActionEvent arg0) {
GUI2.this.nextPanel();
}
}));
JPanel innerPanel2 = new JPanel(new GridBagLayout());
innerPanel2.add(innerPanel);
JPanel connectPanel = new JPanel(new BorderLayout());
connectPanel.add(innerPanel2, borderlayoutLocation);
return connectPanel;
}
private JPanel createChatPanel() {
JPanel chatPanel = new JPanel(new BorderLayout(5, 5));
chatPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
chatPanel.add(new JScrollPane(new JTextArea(15, 30)), BorderLayout.CENTER);
chatPanel.add(new JTextField(), BorderLayout.SOUTH);
return chatPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGui();
}
});
}
private static void createGui() {
JFrame frame = new JFrame("App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GUI2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Right, I have a JTabbedPane that has a JPanel that contains a JLabel and a JTextField.
my code
JTabbed Pane declaration :
this.tabPane = new JTabbedPane();
this.tabPane.setSize(750, 50);
this.tabPane.setLocation(10, 10);
tabPane.setSize(750,450);
tabPane.add("ControlPanel",controlPanel);
textfield declaration :
this.channelTxtFld = new JTextField("");
this.channelTxtFld.setFont(this.indentedFont);
this.channelTxtFld.setSize(200, 30);
this.channelTxtFld.setLocation(200, 10);
JLabel :
this.channelLabel = new JLabel("Channel name : ");
this.channelLabel.setSize(150, 30);
this.channelLabel.setLocation(10,10);
private void createPanels() {
controlPanel = new JPanel();
controlPanel.setSize(650,500);
}
private void fillPanels() {
controlPanel.add(channelLabel);
controlPanel.add(channelTxtFld);
}
So what my plan is, was to have a tabbed pane that has a JPanel where I have some Labels, textfields and buttons on fixed positions, but after doing this this is my result:
http://i.stack.imgur.com/vXa68.png
What I wanted was that I had the JLabel and next to it a full grown JTextfield on the left side not in the middle.
Anyone any idea what my mistake is ?
thank you :)
What kind of Layout Manager are you using for your controlPanel, you probably want BorderLayout, putting the Label in the West, and the TextField in the center.
BTW, setting the size and position of various components doesn't make sense unless you are using a Null Layout, which isn't a good idea. So i'd remove all that stuff and let the Layout Manager do it for you.
Use a LayoutManager and consider also the methods setPreferredSize, setMinimumSize, setMaximumSize to adjust components bounds according on which is your desired effect.
Assuming the default JPanel layout, FlowLayout, give the JTextField a non-zero number of columns, and give the JLabel a JLabel.LEFT constraint.
Addendum:
a full grown JTextField
Something like this?
import java.awt.*;
import javax.swing.*;
/**
* #see http://stackoverflow.com/questions/5773874
*/
public class JTabbedText {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
private final JTabbedPane jtp = new JTabbedPane();
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtp.setPreferredSize(new Dimension(400, 200));
jtp.addTab("Control", new MyPanel("Channel"));
f.add(jtp, BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
private static class MyPanel extends JPanel {
private final JLabel label = new JLabel("", JLabel.LEFT);
private final JTextField text = new JTextField();
public MyPanel(String name) {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
label.setText(name);
label.setAlignmentY(JLabel.TOP_ALIGNMENT);
text.setAlignmentY(JTextField.TOP_ALIGNMENT);
this.add(label);
this.add(text);
}
}
}