Alignment issue in Java Swing screen - java

I am facing an alignment issue in Java Swing screen. I have borderLayout here. My requirement is based on different buttons click suitable query will be executed and populated in JTable. But this screen is having an alignment problem, and JTable is hiding all other components. Below is the code:
public class UI {
static JTextField inputText = new JTextField(20);
static JLabel errMsgLbl = new JLabel();
static PreparedStatement ptsmt;
static ResultSet rs;
static JButton nameButton;
static JButton accnoButton;
static JButton countryButton;
static JButton altaccButton;
static JButton showAllButton;
static JButton clearButton;
static JButton exitButton;
static JButton prevButton;
static JButton nextButton;
static JLabel searchBy;
static String[] columnNames = { "ID", "Name", "Original Name",
"Account Number", "Country", "Alternate Account No",
"Related Party Name", "Select" };
static JTable table;
static JComponent createHorizontalSeparator() {
JSeparator x = new JSeparator(SwingConstants.HORIZONTAL);
x.setForeground(Color.BLACK);
x.setPreferredSize(new Dimension(50, 3));
return x;
}
public static void main(String args[]) {
try {
DBConfig.loadEngineConfiguration();
} catch (Exception ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
final JTable table = new JTable(50, 8);
JPanel topPnl = new JPanel(new BorderLayout());
JPanel cntrPnl = new JPanel(new BorderLayout());
JPanel bottomPnl = new JPanel(new BorderLayout());
JPanel hdrPnl = new JPanel((LayoutManager) new FlowLayout(
FlowLayout.LEFT));
JPanel srchPnl = new JPanel((LayoutManager) new FlowLayout(
FlowLayout.LEADING));
JPanel topBtnPnl = new JPanel((LayoutManager) new FlowLayout(
FlowLayout.LEADING));
JPanel bottombtnPnl = new JPanel((LayoutManager) new FlowLayout(
FlowLayout.LEADING));
JPanel navbtnPnl = new JPanel((LayoutManager) new FlowLayout(
FlowLayout.TRAILING));
JPanel tblPnl = new JPanel((LayoutManager) new FlowLayout(
FlowLayout.CENTER));
hdrPnl.add(new JLabel("Welcome"));
srchPnl.add(new JLabel("Input text"));
srchPnl.add(inputText);
topPnl.add(hdrPnl, BorderLayout.NORTH);
topPnl.add(srchPnl, BorderLayout.SOUTH);
searchBy = new JLabel(DBConfig.searchBy);
nameButton = new JButton(DBConfig.nameBtn);
accnoButton = new JButton(DBConfig.accNoBtn);
countryButton = new JButton(DBConfig.countryBtn);
altaccButton = new JButton(DBConfig.altAccNoBtn);
showAllButton = new JButton(DBConfig.showBtn);
clearButton = new JButton(DBConfig.clearBtn);
exitButton = new JButton(DBConfig.exitBtn);
prevButton = new JButton(DBConfig.prevBtn);
nextButton = new JButton(DBConfig.nextBtn);
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
inputText.setText(null);
errMsgLbl.setText(null);
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container frame = exitButton.getParent();
do
frame = frame.getParent();
while (!(frame instanceof JFrame));
((JFrame) frame).dispose();
}
});
topBtnPnl.add(searchBy);
topBtnPnl.add(nameButton);
topBtnPnl.add(accnoButton);
topBtnPnl.add(countryButton);
topBtnPnl.add(altaccButton);
bottombtnPnl.add(showAllButton);
bottombtnPnl.add(clearButton);
bottombtnPnl.add(exitButton);
//cntrPnl.add(topBtnPnl, BorderLayout.NORTH);
//cntrPnl.add(bottombtnPnl, BorderLayout.SOUTH);
cntrPnl.add(topBtnPnl, BorderLayout.NORTH);
cntrPnl.add(bottombtnPnl, BorderLayout.CENTER);
cntrPnl.add(createHorizontalSeparator(), BorderLayout.SOUTH);
navbtnPnl.add(prevButton);
navbtnPnl.add(nextButton);
table.getTableHeader().setReorderingAllowed(false);
tblPnl.add(table, BorderLayout.PAGE_END);
bottomPnl.add(navbtnPnl, BorderLayout.CENTER);
bottomPnl.add(tblPnl, BorderLayout.CENTER);
//table.setTableHeader(columnNames);
frame.add(topPnl, BorderLayout.NORTH);
frame.add(cntrPnl, BorderLayout.CENTER);
frame.add(bottomPnl, BorderLayout.SOUTH);
frame.setTitle(DBConfig.appName);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setMinimumSize(new Dimension(600, 400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Any help will be much appreciated. Thanks a lot in advance.

The BorderLayout supports only one component per region and you add navbtnPnl and tblPnl to the SOUTH region of bottomPnl, and tblPnl is the last one added which replaces the previously added navbtnPnl component.
Also you should not put your JTable directly in a JPanel if you want your table header to be displayed. You should add it to a JScrollPane instead which will display the header properly.

You are using wrong layout. Use GridBagLayout. i tried it, Here is partial working example
public class UI
{
static JTextField inputText = new JTextField(20);
static JLabel errMsgLbl = new JLabel();
static PreparedStatement ptsmt;
static ResultSet rs;
static JButton nameButton;
static JButton accnoButton;
static JButton countryButton;
static JButton altaccButton;
static JButton showAllButton;
static JButton clearButton;
static JButton exitButton;
static JButton prevButton;
static JButton nextButton;
static JLabel searchBy;
static String[] columnNames = {"ID", "Name", "Original Name", "Account Number", "Country", "Alternate Account No",
"Related Party Name", "Select"};
static JTable table;
static JComponent createHorizontalSeparator()
{
JSeparator x = new JSeparator(SwingConstants.HORIZONTAL);
x.setForeground(Color.BLACK);
x.setPreferredSize(new Dimension(50, 3));
return x;
}
public static void main(String args[])
{
try
{
// DBConfig.loadEngineConfiguration();
}
catch (Exception ex)
{
ex.printStackTrace();
}
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
final JTable table = new JTable(50, 8);
JPanel topPnl = new JPanel(new BorderLayout());
JPanel cntrPnl = new JPanel(new GridLayout(4, 1, 0, 0));
JPanel bottomPnl = new JPanel(new BorderLayout());
JPanel hdrPnl = new JPanel((LayoutManager) new FlowLayout(FlowLayout.LEFT));
JPanel srchPnl = new JPanel((LayoutManager) new FlowLayout(FlowLayout.LEADING));
JPanel topBtnPnl = new JPanel((LayoutManager) new FlowLayout(FlowLayout.LEADING));
JPanel bottombtnPnl = new JPanel((LayoutManager) new FlowLayout(FlowLayout.LEADING));
JPanel navbtnPnl = new JPanel((LayoutManager) new FlowLayout(FlowLayout.TRAILING));
JPanel tblPnl = new JPanel((LayoutManager) new FlowLayout(FlowLayout.CENTER));
hdrPnl.add(new JLabel("Welcome"));
srchPnl.add(new JLabel("Input text"));
srchPnl.add(inputText);
topPnl.add(hdrPnl, BorderLayout.NORTH);
topPnl.add(srchPnl, BorderLayout.SOUTH);
searchBy = new JLabel("searchBy");
nameButton = new JButton("nameBtn");
accnoButton = new JButton("accNoBtn");
countryButton = new JButton("countryBtn");
altaccButton = new JButton("altAccNoBtn");
showAllButton = new JButton("showBtn");
clearButton = new JButton("clearBtn");
exitButton = new JButton("exitBtn");
prevButton = new JButton("prevBtn");
nextButton = new JButton("nextBtn");
clearButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
inputText.setText(null);
errMsgLbl.setText(null);
}
});
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Container frame = exitButton.getParent();
do
frame = frame.getParent();
while (!(frame instanceof JFrame));
((JFrame) frame).dispose();
}
});
topBtnPnl.add(searchBy);
topBtnPnl.add(nameButton);
topBtnPnl.add(accnoButton);
topBtnPnl.add(countryButton);
topBtnPnl.add(altaccButton);
bottombtnPnl.add(showAllButton);
bottombtnPnl.add(clearButton);
bottombtnPnl.add(exitButton);
cntrPnl.add(topBtnPnl);
cntrPnl.add(bottombtnPnl);
cntrPnl.add(createHorizontalSeparator(), BorderLayout.SOUTH);
navbtnPnl.add(prevButton);
navbtnPnl.add(nextButton);
table.getTableHeader().setReorderingAllowed(false);
cntrPnl.add(table, BorderLayout.PAGE_END);
bottomPnl.add(navbtnPnl, BorderLayout.CENTER);
bottomPnl.add(tblPnl, BorderLayout.CENTER);
// table.setTableHeader(columnNames);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
// c.weighty = 10;
c.gridx = 0;
c.gridy = 0;
frame.add(topPnl, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; // make this component tall
c.weightx = 0.2;
c.weighty = 80;
c.weightx = 0.0;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
frame.add(cntrPnl, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0;
c.gridx = 0;
c.gridy = 2;
frame.add(bottomPnl, c);
frame.setTitle("appName");
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setMinimumSize(new Dimension(600, 400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

Related

Swing for apache telnet example

I'm using this java console example https://commons.apache.org/proper/commons-net/examples/telnet/WeatherTelnet.java for working with telnet server. I need frame with input text field for commands(jTextField) and area with commands and server's responce (JTextArea). I has Swing UI, but cant integrate WeatherTelnet.java with it.
IOUtil.readWrite(telnet.getInputStream(), telnet.getOutputStream(), System.in, System.out);
I think I should redirect System.out to JTextArea and jTextField to System.in. Could you help me with it, please.
Swing UI
public class ClientLauncher {
String appName = "Simple Telnet Client";
JFrame frame = new JFrame(appName);
JTextField textField;
JTextArea textArea;
JFrame preFrame;
public void display() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel southPanel = new JPanel();
southPanel.setLayout(new GridBagLayout());
textField = new JTextField(30);
textField.requestFocusInWindow();
textField.addActionListener(new TextFieldListener());
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(new Font("Serif", Font.PLAIN, 15));
textArea.setLineWrap(true);
//MessageConsole mc = new MessageConsole(textComponent);
mainPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
GridBagConstraints left = new GridBagConstraints();
left.anchor = GridBagConstraints.LINE_START;
left.fill = GridBagConstraints.HORIZONTAL;
left.weightx = 512.0D;
left.weighty = 1.0D;
GridBagConstraints right = new GridBagConstraints();
right.insets = new Insets(0, 10, 0, 0);
right.anchor = GridBagConstraints.LINE_END;
right.fill = GridBagConstraints.NONE;
right.weightx = 1.0D;
right.weighty = 1.0D;
southPanel.add(textField, left);
mainPanel.add(BorderLayout.SOUTH, southPanel);
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(470, 300);
frame.setVisible(true);
}
class TextFieldListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (textField.getText().length() > 1) {
textArea.append(textField.getText() + "\n");
textField.setText("");
textField.requestFocusInWindow();
}
}
}
public static void main(String[] args) {
ClientLauncher clientView = new ClientLauncher();
clientView.display();
}
}

Java swing timer not working in Jpanel

i am trying to build a JFrame with a swing Timer in a border layout that contains 2 JPanels, both having Timer that suppose to work together, but only one of them work. The timer in the toolbar panel doesnt work.
public class trygame extends JFrame implements ActionListener {
private JPanel _toolbar = new JPanel();
private Play game;
private Timer _timer;
private int _count = 0;
public trygame(Level lvl) {
super("Elemental Brick Breaker");
_timer = new Timer(1000,this);
_timer.start();
File jarPath=new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
String levelsPath=jarPath.getParentFile().getAbsolutePath();
String path = levelsPath + "\\src\\pics\\gameIcon.png";
ImageIcon icon = new ImageIcon(path);
this.setIconImage(icon.getImage());
setLayout(new BorderLayout());
JButton returnButton = new JButton("Return");
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5,5,5,5);
Dimension d = new Dimension(150,50);
returnButton.setPreferredSize(d);
returnButton.setMinimumSize(d);
_toolbar.add(returnButton,c);
_toolbar.setBackground(Color.black);
add(_toolbar, BorderLayout.SOUTH);
game = new Play(lvl.getBoard());
add(game, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(615,750);
setVisible(true);
setResizable(false);
game.setFocusable(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == _timer) {
_count++;
JLabel jlabel = new JLabel(" Timer: " + Integer.toString(_count));
int Destroyed = game.getDestroyed();
JLabel jlabel2 = new JLabel(" Destroyed: " + Integer.toString(Destroyed));
jlabel.setFont(new Font("Verdana",1,20));
jlabel2.setFont(new Font("Verdana",1,20));
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(5,5,5,5);
Dimension d = new Dimension(150,50);
jlabel.setPreferredSize(d);
jlabel2.setMinimumSize(d);
_toolbar.add(jlabel,c);
_toolbar.add(jlabel2,c);
_toolbar.setBorder(new LineBorder(Color.BLACK));
}
}
}

How to change frame on button event Java

I am making a simple project. It has login window like this
When the user click on button log in - it should "repaint" the window(it should seem to be happened in the same window) and then the window looks like this.
The problem is - I can't "repaint" the window - the only thing I can - it's create a new frame, so there actually are 2 frames totally.
How to make the whole thing in one same frame.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPane(Container pane)
{
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
pane.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
pane.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
JPanel panel = new JPanel();
JLabel label = new JLabel("Your login:");
panel.add(label);
JTextField textField = new JTextField(15);
panel.add(textField);
JButton loginButton = new JButton("log in");
panel.add(loginButton);
JButton exitButton = new JButton("exit");
panel.add(exitButton);
frame.add(panel, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
frame = null;
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
}
Use CardLayout.
This layout allows developers to switch between panels. It works by creating a "deck" panel that'll contain all of panels that'll potentially be displayed:
CardLayout layout = new CardLayout();
JPanel deck = new JPanel();
deck.setLayout(layout);
JPanel firstCard = new JPanel();
JPanel secondCard = new JPanel();
deck.add(firstCard, "first");
deck.add(secondCard, "second");
When you click on a button, that button's ActionListener should call show(Container, String), next(Container) or previous(Container) on the CardLayout to switch which panel is being displayed:
public void actionPerformed(ActionEvent e) {
layout.show(deck, "second");
}
One of the solutions
You can create two panels (one for each view) and add the required components to them. First, you add first panel to the frame (using frame.add(panel1)). If you want to show the second panel in the same window, you can delete first panel (using frame.remove(panel1)) and add the second panel (using frame.add(panel2)). At the end you've to call frame.pack().
This's your code with above solution:
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPanel2()
{
panel2.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
panel2.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
panel2.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
panel1 = new JPanel();
JLabel label = new JLabel("Your login:");
panel1.add(label);
JTextField textField = new JTextField(15);
panel1.add(textField);
JButton loginButton = new JButton("log in");
panel1.add(loginButton);
JButton exitButton = new JButton("exit");
panel1.add(exitButton);
frame.add(panel1, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
panel2 = new JPanel();
addComponentsToPanel2();
frame.remove(panel1);
frame.add(panel2);
//frame.repaint();
frame.pack();
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
private JPanel panel1;
private JPanel panel2;
}

GridBagLayout isn't formatting correctly

I'm trying to get the config panel to take up the top of the screen, and then have the input and output panels side-by-side. I'm also trying to get the text areas to be 70 characters wide each and 30 rows tall. However, right now, the config panel isn't showing up at all, and the text areas are only 35 characters wide and 2 rows tall. I've followed all the examples and tutorials I've found. What am I doing wrong?
public class BorderWrapper {
public static void main(String[] args) {
//Create frame
JFrame frame = new JFrame("Border Wrapper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create main panel
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
//Display frame
Dimension minSize = new Dimension(650, 375);
frame.setPreferredSize(minSize);
frame.setMinimumSize(minSize);
frame.pack();
frame.setVisible(true);
}
}
public class MainPanel extends JPanel {
private static final Font INPUT_FONT = new Font("Monospaced", Font.PLAIN, 12);
private JTextArea inputArea, outputArea;
private JTextField titleField, topBorderField, sideBorderField;
public MainPanel() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Set up config panel
JPanel configPanel = new JPanel();
configPanel.setLayout(new BoxLayout(configPanel, BoxLayout.X_AXIS));
configPanel.setMaximumSize(new Dimension(400, 200));
titleField = new JTextField(25);
titleField.setFont(INPUT_FONT);
topBorderField = new JTextField(1);
topBorderField.setFont(INPUT_FONT);
sideBorderField = new JTextField(4);
sideBorderField.setFont(INPUT_FONT);
configPanel.add(new JLabel("Title:"));
configPanel.add(titleField);
configPanel.add(new JLabel("Top border:"));
configPanel.add(topBorderField);
configPanel.add(new JLabel("Side border:"));
configPanel.add(sideBorderField);
c.gridwidth = 2;
c.gridx = 0;
c.gridy = 0;
add(configPanel, c);
//Set up Input panel
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
inputArea = new JTextArea("Type or paste your stuff here . . .");
inputArea.setFont(INPUT_FONT);
inputArea.setLineWrap(true);
inputArea.setWrapStyleWord(true);
inputArea.setColumns(75);
JScrollPane inputPane = new JScrollPane(inputArea);
inputPane.setMinimumSize(new Dimension(250, 400));
JLabel inputLabel = new JLabel("Text Box");
inputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
inputPanel.add(inputLabel);
inputPanel.add(inputPane);
inputPanel.setMinimumSize(new Dimension(250, 400));
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
add(inputPanel, c);
//Set up Output panel
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
outputArea = new JTextArea();
outputArea.setFont(INPUT_FONT);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setColumns(75);
JScrollPane outputPane = new JScrollPane(outputArea);
outputPane.setMinimumSize(new Dimension(250, 400));
JLabel outputLabel = new JLabel("Wrapped Output");
outputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
outputPanel.add(outputLabel);
outputPanel.add(outputPane);
outputPanel.setMinimumSize(new Dimension(250, 400));
c.gridwidth = 1;
c.gridx = 1;
c.gridy = 1;
add(outputPanel, c);
}
}
Originally, I was going to try to use a BorderLayout, since it seemed that made the most sense for the layout I was trying to make, but that did an even worse job when I set them to BorderLayout.WEST and BorderLayout.EAST.
Have modified your program to use BorderLayout in the MainPanel and few other minor changes to get the desired look and feel.Check if this helps.
public class BorderWrapper {
public static void main(String[] args) {
// Create frame
JFrame frame = new JFrame("Border Wrapper");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create main panel
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel);
// Display frame
Dimension minSize = new Dimension(650, 375);
frame.setPreferredSize(minSize);
frame.setMinimumSize(minSize);
frame.pack();
frame.setVisible(true);
}
}
class MainPanel extends JPanel {
private static final Font INPUT_FONT = new Font("Monospaced", Font.PLAIN, 12);
private JTextArea inputArea, outputArea;
private JTextField titleField, topBorderField, sideBorderField;
public MainPanel() {
setLayout(new BorderLayout());
// Set up config panel
JPanel configPanel = new JPanel();
configPanel.setLayout(new BoxLayout(configPanel, BoxLayout.X_AXIS));
configPanel.setMaximumSize(new Dimension(400, 200));
titleField = new JTextField(25);
titleField.setFont(INPUT_FONT);
topBorderField = new JTextField(1);
topBorderField.setFont(INPUT_FONT);
sideBorderField = new JTextField(4);
sideBorderField.setFont(INPUT_FONT);
configPanel.add(new JLabel("Title:"));
configPanel.add(titleField);
configPanel.add(new JLabel("Top border:"));
configPanel.add(topBorderField);
configPanel.add(new JLabel("Side border:"));
configPanel.add(sideBorderField);
add(configPanel, BorderLayout.NORTH);
// Set up Input panel
JPanel lowerPanel = new JPanel(new GridLayout(1, 1));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.Y_AXIS));
inputArea = new JTextArea("Type or paste your stuff here . . .");
inputArea.setFont(INPUT_FONT);
inputArea.setLineWrap(true);
inputArea.setWrapStyleWord(true);
inputArea.setColumns(75);
JScrollPane inputPane = new JScrollPane(inputArea);
JLabel inputLabel = new JLabel("Text Box");
inputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
inputPanel.add(inputLabel);
inputPanel.add(inputPane);
lowerPanel.add(inputPanel);
// Set up Output panel
JPanel outputPanel = new JPanel();
outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS));
outputArea = new JTextArea();
outputArea.setFont(INPUT_FONT);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setColumns(75);
JScrollPane outputPane = new JScrollPane(outputArea);
JLabel outputLabel = new JLabel("Wrapped Output");
outputLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
outputPanel.add(outputLabel);
outputPanel.add(outputPane);
lowerPanel.add(outputPanel);
add(lowerPanel, BorderLayout.CENTER);
}
}
I felt it convenient to use BorderLayout for this format.Anyways, you can still make few changes to the code you posted using GridBagConstraints to get the desired look.Make the below changes one by one and you will observe the differences.
1.You were aligning the MainPanel to the NORTH by using BorderLayout.But in your case the entire set of components is placed in MainPanel,so better place it in center.So instead of NORTH use below :(after this change,you will see the complete input and output panels)
MainPanel panel = new MainPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
2.You have set the dimension of the Parent frame to Dimension(height=375)
minSize = new Dimension(650, 375);
You components(configPanel=200,outputPanel=400) combined height is more than 375.Increase the height of the Parent, to about 600.
3.Instead of BoxLayout try using GridLayout for configPanel.
configPanel.setLayout(new GridLayout(1,6,5,0));
Making the above 3 changes to your existing code will get the expected output.Hope this clarifies.

Unable to set the size of my buttons in GridLayout

I am trying to build a sample application using GridLayout in Java. But I am unable to re-size my buttons. Please help me in doing it.
There are four grid layouts in the code.
I have used the setSize(width, height) function and also the setPreferredSize function. But I am not able to set the size of the buttons.
Here is the code
import java.awt.*;
import javax.swing.*;
public class Details2 {
static JButton btn1,btn2;
public static void main(String[] a) {
JFrame myFrame = new JFrame("Medical History Form");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(700,700);
Container myPane = myFrame.getContentPane();
myPane.setLayout(new GridLayout(2,1));
myPane.add(getFieldPanel());
myPane.add(getButtonPanel());
myPane.setPreferredSize(new Dimension(100,100));
myFrame.setVisible(true);
}
private static JPanel getFieldPanel() {
JPanel p = new JPanel(new GridLayout(4,2));
p.setBorder(BorderFactory.createTitledBorder("Details"));
p.add(new JLabel("Please check in the here"));
p.add(new JCheckBox("Nothing till now",false));
p.add(getPanel());
return p;
}
private static JPanel getButtonPanel() {
GridLayout g =new GridLayout(1,2);
JPanel p = new JPanel(g);
btn1 = new JButton("Submit");
btn2 = new JButton("Reset");
p.add(btn1).setPreferredSize(new Dimension(100,100));
p.add(btn2).setPreferredSize(new Dimension(100,100));
p.setPreferredSize(new Dimension(100,100));
return p;
}
private static JPanel getPanel() {
JPanel p = new JPanel(new GridLayout(5,2));
p.add(new JCheckBox("A",false));
p.add(new JCheckBox("B",false));
p.add(new JCheckBox("C",false));
p.add(new JCheckBox("D",false));
p.add(new JCheckBox("E",false));
p.add(new JCheckBox("F",false));
p.add(new JCheckBox("G",false));
p.add(new JCheckBox("E",false));
p.add(new JCheckBox("H",false));
p.add(new JCheckBox("I",false));
return p;
}
}
I believe setting GridLayout(2,2) will override size changes made to the panels. To be more precise, use GridBagConStraints; you can refer following code to understand it.
private JTextField field1 = new JTextField();
private JButton addBtn = new JButton("Save: ");
public void addComponents(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Components
c.gridwidth = 1;
c.weightx = .01;
c.weighty = .2;
c.gridx = 0;
c.gridy = 1;
pane.add(field1, c);
c.gridwidth = 1;
c.weightx = .01;
c.weighty = .2;
c.gridx = 0;
c.gridy = 1;
pane.add(addBtn, c);
}
public MainView() {
//Create and set up the window.
JFrame frame = new JFrame("NAME");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponents(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(400, 125);
frame.setLocation(400, 300);
}
if you want to control the size of your components then don't use a layout. do something like this:
private static JPanel getButtonPanel() {
JPanel p = new JPanel();
p.setLayout(null);
btn1 = new JButton("Submit");
btn2 = new JButton("Reset");
btn1.setBounds(x, y, width, height);
btn2.setBounds(x, y, width, height);
p.add(btn1);
p.add(btn2);
return p;

Categories

Resources