I have a horizontal split pane that contains a vertical split pane. When the window shows up i want the vertical split pane in the top of the horizontal split pane to be split in the middle. I want the horizontal divider to be in the middle.
I have that working, however, i also want to the horizontal split pane to change its size when the window is maximized. (It currently does not.)
I also have a button box below the horizontal pane and would like it to always be visible when the window is resized. Currently when the window launches i can see everything in the horizontal split. I am unable to see the buttons, because they do not fit in the preferred size of the window (800, 600). But i would like everything to show up in the window automatically and stay Glue'd to the border of the window when it is resized...
How can i do this?
Thanks!
Below is the code i am currently using. I call the create methods in a controller. createView is called first then the rest in sequential order.
public void createView() {
dialog = new JFrame();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
dialog.setAlwaysOnTop(true);
dialog.setBounds(0, 0, 800, 600);
dialog.setMinimumSize(new Dimension(800, 600));
dialog.setPreferredSize(new Dimension(800, 600));
dialog.setResizable(true);
dialog.setTitle("MJLA Class Control Panel");
contentPanel = new JPanel();
// contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
classQuizSRTSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
contentPanel.add(classQuizSRTSplit, BorderLayout.NORTH);
classQuizSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
classQuizSRTSplit.setTopComponent(classQuizSplit);
// classQuizHBox = Box.createHorizontalBox();
// contentPanel.add(classQuizHBox);
sRTHBox = Box.createHorizontalBox();
contentPanel.add(sRTHBox);
buttonBox = Box.createHorizontalBox();
contentPanel.add(buttonBox, BorderLayout.SOUTH);
refreshButton = new JButton("Refresh");
buttonBox.add(refreshButton);
doneButton = new JButton("Done");
buttonBox.add(doneButton);
this.validateView();
}
public void createClassTablePanel() {
this.classTablePanel = new JPanel();
this.classTablePanel.setBorder(BorderFactory.createLineBorder(Color.black, 3));
this.classTablePanel.setPreferredSize(new Dimension(300, 300));
this.classTablePanel.setLayout(new BorderLayout());
// this.classQuizHBox.add(classTablePanel);
this.classQuizSplit.setLeftComponent(classTablePanel);
classTableModel = cPModel.getClassTableModel();
classTable = new JTable(this.classTableModel);
classTable.getSelectionModel().addListSelectionListener(this);
JScrollPane scrollPane = new JScrollPane(classTable);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
classTablePanel.add(scrollPane, BorderLayout.CENTER);
this.validateView();
}
public void createQuizTablePanel() {
this.quizTablePanel = new JPanel();
this.quizTablePanel.setBorder(BorderFactory.createLineBorder(Color.black, 3));
this.quizTablePanel.setPreferredSize(new Dimension(300, 300));
this.quizTablePanel.setLayout(new BorderLayout());
// this.classQuizHBox.add(quizTablePanel);
this.classQuizSplit.setRightComponent(quizTablePanel);
quizTableModel = cPModel.getQuizTableModel();
this.quizSorter = new TableRowSorter<DefaultTableModel>(quizTableModel);
quizTable = new JTable(this.quizTableModel);
quizTable.getSelectionModel().addListSelectionListener(this);
quizTable.setRowSorter(quizSorter);
JScrollPane scrollPane = new JScrollPane(quizTable);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
quizTablePanel.add(scrollPane, BorderLayout.CENTER);
Box buttonHBox = Box.createHorizontalBox();
quizTablePanel.add(buttonHBox, BorderLayout.SOUTH);
addQuizButton = new JButton("Add Quiz");
buttonHBox.add(addQuizButton);
removeQuizButton = new JButton("Remove Quiz");
buttonHBox.add(removeQuizButton);
editQuizButton = new JButton("Edit Quiz");
buttonHBox.add(editQuizButton);
this.validateView();
}
public void createStudentRecordTablePanel() {
this.studentRecordTablePanel = new JPanel();
this.studentRecordTablePanel.setBorder(BorderFactory.createLineBorder(Color.black, 3));
this.studentRecordTablePanel.setLayout(new BorderLayout());
// this.sRTHBox.add(studentRecordTablePanel);
this.classQuizSRTSplit.setBottomComponent(studentRecordTablePanel);
this.studentRecordTableModel = cPModel.getStudentRecordTableModel();
this.sRTSorter = new TableRowSorter<DefaultTableModel>(studentRecordTableModel);
sRTTable = new JTable(this.studentRecordTableModel);
sRTTable.setRowSorter(sRTSorter);
JScrollPane scrollPane = new JScrollPane(sRTTable);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
studentRecordTablePanel.add(scrollPane, BorderLayout.CENTER);
Box buttonHBox = Box.createHorizontalBox();
studentRecordTablePanel.add(buttonHBox, BorderLayout.SOUTH);
editGradeButton = new JButton("Edit Grade");
buttonHBox.add(editGradeButton);
generateReportButton = new JButton("Generate Report");
buttonHBox.add(generateReportButton);
this.validateView();
}
Another issue.
That fixed one of the problems #TrashGod. However, how can i make the horizontal split pane resize its component to fit the new size of the window, instead of their being that big gap between the done and refresh button and the bottom of the horizontal split pane?
I was thinking that i would have to listen for an event for when the window size changes and then call the pack() method when that happens, is that the only way or would that even work? (Just tested this, it did not work... just puts everything back to preferred sizes. duh)
Initial look.
After window maximized.
You might look at setResizeWeight(); a value of 0.5 should distribute the space evenly.
The pack() method "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents." BorderLayout.NORTH and BorderLayout.SOUTH seem like suitable layouts for staying with the divider.
For additional help, please provide an sscce that exhibits the problem.
Related
I want to be able to scroll down a dynamically generated list of movies. I tried adding a Scrollpane.
I have a navigation bar at the page start and in the center a jpanel with all the movies.
You can recreate this example by using this code:
private static JFrame frame;
public static void main(String[] args) throws HeadlessException {
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setBackground(new Color(32, 32, 32));
JPanel navigationPanel = createNavigationBar();
frame.add(navigationPanel, BorderLayout.PAGE_START);
JPanel moviePanel = createMoviePanel();
frame.add(moviePanel, BorderLayout.CENTER);
frame.setPreferredSize(new Dimension(1920, 1080));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Example App");
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
// MoviePanel Class
public static JPanel createMoviePanel() {
JPanel parentMoviePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 25));
JPanel contentPanel = new JPanel(new GridLayout(0, 1));
JPanel moviePanel = new JPanel(new GridLayout(0, 9, 8, 5));
JScrollPane scrollPane = new JScrollPane(moviePanel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));
scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0));
parentMoviePanel.setBackground(new Color(32, 32, 32));
contentPanel.setBackground(new Color(32, 32, 32));
moviePanel.setBackground(new Color(32, 32, 32));
final File root = new File("");
for (int i = 0; i < 70; i++) {
// Get the image and scale it down
BufferedImage movieCover=new BufferedImage(150,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d=(Graphics2D)movieCover.getGraphics();
g2d.setColor(Color.GRAY);
g2d.fillRect(0,0,movieCover.getWidth(),movieCover.getHeight());
// Create button and change settings
JButton movieButton = new JButton("Movie " + i, new ImageIcon(movieCover));
movieButton.setMargin(new Insets(0, 0, 0, 0));
movieButton.setPreferredSize(new Dimension(180, 250));
movieButton.setForeground(Color.WHITE);
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
movieButton.setHorizontalTextPosition(JButton.CENTER);
movieButton.setVerticalTextPosition(JButton.BOTTOM);
moviePanel.add(movieButton);
scrollPane.revalidate();
}
contentPanel.add(moviePanel);
contentPanel.add(scrollPane);
parentMoviePanel.add(contentPanel);
return parentMoviePanel;
}
// Navbar Class
public static JPanel createNavigationBar() {
JPanel navBar = new JPanel();
navBar.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20));
navBar.setBackground(new Color(25, 25, 25));
JButton homeButton = new JButton("Home");
homeButton.setContentAreaFilled(false);
homeButton.setBorderPainted(false);
homeButton.setFocusPainted(false);
JButton movieButton = new JButton("Movies");
movieButton.setContentAreaFilled(false);
movieButton.setBorderPainted(false);
movieButton.setFocusPainted(false);
// Add all the buttons to the navbar
navBar.add(homeButton);
navBar.add(movieButton);
return navBar;
}
What I'm trying to do is to scroll down this list of movies, using my mouse wheel without seeing any kind of scrollbar. It should look exactly how it looks now, but I want to be able to scroll down and see all the movies.
I don't know why it isn't working that's why I'm asking here in hope someone can explain to me what I'm doing wrong.
Your usage of a scroll pane is incorrect.
A Swing component can only have a single parent. The following code is creating the scroll pane with a child component. However you then remove the moviePanel from the scroll pane when you add it to the content pane.
So the scroll pane has no child component and will never work.
JScrollPane scrollPane = new JScrollPane(moviePanel);
...
contentPanel.add(moviePanel);
contentPanel.add(scrollPane);
However, even that won't solve your problem because you are now using a FlowLayout on your top level panel so all the child components will always be displayed at their preferred size so there is no need for scroll bars.
Get rid of all the scroll pane logic in your createMoviePanel() method.
Instead you probably want to add the scroll pane to the content pane:
//frame.add(moviePanel, BorderLayout.CENTER);
frame.add(new JScrollPane(moviePanel), BorderLayout.CENTER);
Now the scroll pane will dynamically resize as the frame size changes. Scrollbars will then appear as required.
I'm not able to set the height of a JComboBox, I searched in the web but didn't found the right answer.
As you can see from the image below the combo box fills nearly all the panel height and I'd like it to have a smaller height.
I tried setting size with getPreferredSize() method but it didn't work, it worked only for other components like the button.
My code
private JComponent firstPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JLabel spesaAnnuaSingola = new JLabel();
spesaAnnuaSingola.setText("Spesa Annua Singola");
panel.add(spesaAnnuaSingola, BorderLayout.NORTH);
JComboBox<String> listaSpese = new JComboBox<String>();
panel.add(listaSpese, BorderLayout.CENTER);
JTextField speseAnnuaSingolaTF = new JTextField();
speseAnnuaSingolaTF.setText("");
speseAnnuaSingolaTF.setEditable(false);
panel.add(speseAnnuaSingolaTF, BorderLayout.LINE_START);
JButton button = new JButton("CALCOLA")
{
public Dimension getPreferredSize()
{
return new Dimension(150,50);
};
};
JPanel leftflowpanel = new JPanel( new FlowLayout(FlowLayout.LEFT) );
leftflowpanel.add(speseAnnuaSingolaTF);
panel.add(leftflowpanel, BorderLayout.SOUTH);
JPanel rightflowpanel = new JPanel( new FlowLayout(FlowLayout.RIGHT) );
rightflowpanel.add(button);
panel.add(rightflowpanel, BorderLayout.SOUTH);
return panel;
}
And then:
public StatsPanel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
GridBagConstraints c = new GridBagConstraints();
// I will need a grid layout
this.setLayout(new GridLayout(1, 1, 30, 30));
JPanel panelLeft = new JPanel(new BorderLayout());
panelLeft.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 50));
panelLeft.add(firstPanel(), BorderLayout.NORTH);
c.fill = GridBagConstraints.VERTICAL;
c.gridx = 0;
c.gridy = 0;
this.add(panelLeft);
}
JComboBox<String> listaSpese = new JComboBox<String>();
panel.add(listaSpese, BorderLayout.CENTER);
You add your combo box to the CENTER of the BorderLayout, which gets all the extra space of the frame. Don't add the combo box to the CENTER.
Instead you will need to nest panels. So create a panel for the NORTH of the BorderLayout. Then this panel will contain both your label and your combo box. Maybe use a vertical BoxLayout for this panel. Then both the label and the combo box will be displayed at their preferred heights.
Read the section from the Swing on Layout Manager for more information. The point is you can nest multiple panels each using a different layout to achieve your desired layout.
I'm currently trying to get along with Layouts, considering that I never really understood them and only did nullLayout instead, absolutely positioning all elements then.
However, I currently have a suitable small project, where I am trying to learn it, which is some small chat service.
Here is a picture right now:
And here is a picture, of how I imagine it to be finished (Please note that this is just some concept, but it should give you the right idea. I'm not a graphic artist):
Here is my current code:
public class Gui {
JFrame frame;
JTextArea textfield;
JTextField enterMessage;
public Gui(){
frame = new JFrame();
frame.setSize(600, 400);
textfield = new JTextArea();
textfield.setText("Textfield");
textfield.setSize(400, 300);
JPanel messagePanel = new JPanel();
JTextField chatMessage = new JTextField();
chatMessage.setText("Send me");
JButton send = new JButton();
send.setText("Send");
messagePanel.add(chatMessage, BorderLayout.WEST);
messagePanel.add(send, BorderLayout.EAST);
frame.add(textfield, BorderLayout.WEST);
frame.add(messagePanel, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
My idea, together with the understanding of BorderLayouts so far was to put the Textfield, where the chat dialog ends up in later on, right inside the frame, on the WEST-side.
The button to send and the field to enter some text will be inside a panel, with an own borderlayout, while the button has some smaller part on the right and the rest of the width is being filled with the textfield.
The whole panel then ends on the SOUTH-side of the frame.
However, right now I have the problem, that the elements keep shrinking to the least possible size.
I tried to fix this with setSize(); , but that does not have an impact at all, it is just being completely ignored.
Any help to point me into the right direction?
Initially, you've got one simple problem:
// should be new JPanel(new BorderLayout())
JPanel messagePanel = new JPanel();
Then, after that, generally BorderLayout likes to stretch the component in BorderLayout.CENTER. So you want to put your textfield and chatMessage in the center.
public Gui(){
frame = new JFrame();
frame.setSize(600, 400);
textfield = new JTextArea();
textfield.setText("Textfield");
// textfield.setSize(400, 300);
JPanel messagePanel = new JPanel(new BorderLayout());
JTextField chatMessage = new JTextField("Send me");
JButton send = new JButton("Send");
messagePanel.add(chatMessage, BorderLayout.CENTER);
messagePanel.add(send, BorderLayout.EAST);
frame.add(textfield, BorderLayout.CENTER);
frame.add(messagePanel, BorderLayout.SOUTH);
frame.setVisible(true);
}
Once you do that, you should get something like this:
But, as a few words of advice:
Don't rely on setSize of a JFrame. Instead, you should use setPreferredSize on a single component which the entire UI should size itself around. (Probably the main text area.) The size of a JFrame includes, for example, the title bar.
You should consider wrapping your JTextArea in a scroll pane. You can then instead setPreferredSize on the viewport.
After you have a component with a preferred size, call pack() on the JFrame before calling setVisible(true). This will size it automatically.
Something like:
frame = new JFrame();
// frame.setSize(600, 400);
...
JScrollPane pane = new JScrollPane(
textfield,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// specifying initial size for the
// visible portion of the scroll pane
pane.getViewport().setPreferredSize(new Dimension(320, 200));
frame.add(pane, BorderLayout.CENTER);
frame.add(messagePanel, BorderLayout.SOUTH);
// entire UI sizes around the scroll pane view
frame.pack();
frame.setVisible(true);
Try BoxLayout insted BorderLayout in messagePanel:
messagePanel.setLayout(new BoxLayout(messagePanel,BoxLayout.LINE_AXIS));
messagePanel.add(chatMessage);
messagePanel.add(send);
And for textField:
frame.add(textfield, BorderLayout.CENTER);
Try setting preferred size dimensions of the elements.
textfield.setText("Textfield");
textfield.setPreferredSize(new Dimension(600, 300));
//some other code
JTextField chatMessage = new JTextField();
chatMessage.setPreferredSize(new Dimension(500, 25));
//some other code
As pointed out by Sridhar, BorderLayout does not always respect the dimensions of sub-panels. To fix this, you should initialize your sub-panels (in this case textfield and messagePanel) using setPreferedSize() instead of setSize().
change your constructor to
public Gui() {
frame = new JFrame();
frame.setSize(600, 400);
textfield = new JTextArea();
textfield.setText("Textfield");
textfield.setSize(400, 300);
// set border layout to JPanel
JPanel messagePanel = new JPanel(new BorderLayout());
JTextField chatMessage = new JTextField();
chatMessage.setText("Send me");
JButton send = new JButton();
send.setText("Send");
// add JTextField to CENTER and button to EAST
messagePanel.add(chatMessage, BorderLayout.CENTER);
messagePanel.add(send, BorderLayout.EAST);
// add textArea to CENTER of JFrame
frame.add(textfield, BorderLayout.CENTER);
frame.add(messagePanel, BorderLayout.SOUTH);
frame.setVisible(true);
}
and it will work..
I want to create a JInternalFrame with some components in it.
My aim is to design a bash console in Java.
My frame is made of 4 components:
JTextArea included into a JScrollPane
JLabel with the text "Cmd:"
JTextField
JButton with the text "Send"
And I have the following code:
Box box = Box.createHorizontalBox();
box.add(Box.createVerticalStrut(5));
box.add(this.cmd_label);
box.add(Box.createVerticalStrut(5));
box.add(this.cmd_input);
box.add(Box.createVerticalStrut(5));
box.add(this.submit);
box.add(Box.createVerticalStrut(5));
Box mainBox = Box.createVerticalBox();
mainBox.add(Box.createHorizontalStrut(5));
mainBox.add(this.result_scroll);
mainBox.add(Box.createHorizontalStrut(5));
mainBox.add(box);
mainBox.add(Box.createHorizontalStrut(5));
add(mainBox);
So when the frame has not been maximized, I have a correct look:
But when I maximize it, all components are incorrectly located:
So, here is my question: How can I set a weight to the components to fix their location every time, or, how can I fix it?
Thanks.
I think this would be better done with a BorderLayout. In a BorderLayout, the component specified as the center component will expand to fill as much space as possible, and the other components will remain at their preferred sizes.
int hgap = 5;
int vgap = 5;
internalFrame.getContentPane().setLayout(new BorderLayout(hgap, vgap));
internalFrame.getContentPane().add(this.result_scroll, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.add(this.cmd_label);
bottomPanel.add(this.cmd_input);
bottomPanel.add(this.submit);
internalFrame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
Here try this code, is this behaviour exceptable :
import java.awt.*;
import javax.swing.*;
public class LayoutExample
{
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("LAYOUT EXAMPLE");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout(5, 5));
centerPanel.setBorder(
BorderFactory.createEmptyBorder(2, 2, 2, 2));
JTextArea tarea = new JTextArea(10, 10);
tarea.setBackground(Color.DARK_GRAY.darker());
tarea.setForeground(Color.WHITE);
tarea.setCaretColor(Color.WHITE);
tarea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(tarea);
centerPanel.add(scrollPane, BorderLayout.CENTER);
JPanel footerPanel = new JPanel();
footerPanel.setLayout(new BorderLayout(5, 5));
footerPanel.setBorder(
BorderFactory.createEmptyBorder(2, 2, 2, 2));
JLabel cmdLabel = new JLabel("Cmd : ");
JTextField tfield = new JTextField(10);
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(
BorderFactory.createEmptyBorder(2, 2, 2, 2));
JButton sendButton = new JButton("SEND");
footerPanel.add(cmdLabel, BorderLayout.LINE_START);
footerPanel.add(tfield, BorderLayout.CENTER);
buttonPanel.add(sendButton);
footerPanel.add(buttonPanel, BorderLayout.LINE_END);
frame.getContentPane().add(centerPanel, BorderLayout.CENTER);
frame.getContentPane().add(footerPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new LayoutExample().createAndDisplayGUI();
}
});
}
}
OUTPUT :
Base problem here is what I consider a bug in JTextField's max layout hint: it's unbounded in both horizontal and vertical dimension. The latter is pure nonsense for a component designed for showing a single line of text. To fix, subclass and let it return its pref for the height, like:
JTextField cmdInput = new JTextField() {
#Override
public Dimension getMaximumSize() {
Dimension max = super.getMaximumSize();
max.height = getPreferredSize().height;
return max;
}
};
As BoxLayout respects maxSize, the excess height now will be given to the top box only.
On the long run, consider switching to a third party manager which allows fine-tuning in a all-in-one-panel approach. Yeah, here comes my current favourite: MigLayout. Compare the following lines to all the nesting and border tricks above and have fun :-)
MigLayout layout = new MigLayout("wrap 3, debug",
"[][grow, fill][]", // 3 columns, middle column filled and allows growing
"[grow, fill][]"); // two rows, first filled and allows growing
JComponent content = new JPanel(layout);
// the scrollPane in the first row spanning all columns
// and growing in both directions
content.add(new JScrollPane(new JTextArea(20, 20)), "span, grow");
// auto-wrapped to first column in second row
content.add(new JLabel("Cmd:"));
content.add(new JTextField());
content.add(new JButton("Submit"));
Problem:
My program layout is fine, as below before I add JToolbar to BorderLayout.PAGE_START
Here's a screenshot before JToolbar is added:
Here's how it looked like after adding JToolbar:
May I know what did I do wrong?
Here's the code I used:
//Create the text pane and configure it.
textPane = new JTextPane();
-snipped code-
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(300, 300));
//Create the text area for the status log and configure it.
changeLog = new JTextArea(5, 30);
changeLog.setEditable(false);
JScrollPane scrollPaneForLog = new JScrollPane(changeLog);
//Create a split pane for the change log and the text area.
JSplitPane splitPane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
scrollPane, scrollPaneForLog);
splitPane.setOneTouchExpandable(true);
//Create the status area.
JPanel statusPane = new JPanel(new GridLayout(1, 1));
CaretListenerLabel caretListenerLabel =
new CaretListenerLabel("Caret Status");
statusPane.add(caretListenerLabel);
//Create the toolbar
JToolBar toolBar = new JToolBar();
-snipped code-
//Add the components.
getContentPane().add(toolBar, BorderLayout.PAGE_START);
getContentPane().add(splitPane, BorderLayout.CENTER);
getContentPane().add(statusPane, BorderLayout.PAGE_END);
//Set up the menu bar.
actions = createActionTable(textPane);
JMenu editMenu = createEditMenu();
JMenu styleMenu = createStyleMenu();
JMenuBar mb = new JMenuBar();
mb.add(editMenu);
mb.add(styleMenu);
setJMenuBar(mb);
Please help, I'm new to GUI Building, and I don't feel like using Netbeans to drag and drop the UI for me... Thank you in advance.
Instead of using setSize() on the JFrame, set the preferred size of your center component as you do now and invoke pack(), which "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents." Expanding on #Bragaadeesh's example,
public static void main(String[] args) {
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.build();
frame.pack();
frame.setVisible(true);
}
Then, change to scrollPane.setPreferredSize(new Dimension(500, 300)) or JTextArea changeLog = new JTextArea(10, 30) to see the difference.
I don't know what is the issue. I tried to run it on my system by fixing the compilation issues. Here is the code and screenshot.
import java.awt.*;
import javax.swing.*;
public class TestFrame extends JFrame{
public static void main(String[] args) {
TestFrame frame = new TestFrame();
frame.build();
frame.setVisible(true);
}
public void build(){
setSize(600,600);
//Create the text pane and configure it.
JTextPane textPane = new JTextPane();
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(300, 300));
//Create the text area for the status log and configure it.
JTextArea changeLog = new JTextArea(5, 30);
changeLog.setEditable(false);
JScrollPane scrollPaneForLog = new JScrollPane(changeLog);
//Create a split pane for the change log and the text area.
JSplitPane splitPane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
scrollPane, scrollPaneForLog);
splitPane.setOneTouchExpandable(true);
//Create the status area.
JPanel statusPane = new JPanel(new GridLayout(1, 1));
JLabel caretListenerLabel =
new JLabel("Caret Status");
statusPane.add(caretListenerLabel);
//Create the toolbar
JToolBar toolBar = new JToolBar();
toolBar.add(new JButton("Btn1"));
toolBar.add(new JButton("Btn2"));
toolBar.add(new JButton("Btn3"));
toolBar.add(new JButton("Btn4"));
//Add the components.
getContentPane().add(toolBar, BorderLayout.PAGE_START);
getContentPane().add(splitPane, BorderLayout.CENTER);
getContentPane().add(statusPane, BorderLayout.PAGE_END);
//Set up the menu bar.
JMenu editMenu = new JMenu("test");
JMenu styleMenu = new JMenu("test");
JMenuBar mb = new JMenuBar();
mb.add(editMenu);
mb.add(styleMenu);
setJMenuBar(mb);
}
}
EDIT: I understand why now.
I used Paint to give me a rough estimation of the pixels, and previously I did not know that the height from the start of the top frame title bar is counted! So that adds up to ~= 504. I get it now.
So next time when I have to set the height roughly, I think I'll use Paint.
Hmmm weird. I have to change from:
//Display the window.
frame.setSize(640, 480);
to
//Display the window.
frame.setSize(640, 504);
Then only it works.
Can somebody teach me how to estimate or set the width/height for the components? Because initially I wanted it to be 640,480 but apparently now it needs 640,504.