Java swing timer not working in Jpanel - java

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));
}
}
}

Related

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;
}

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;

Alignment issue in Java Swing screen

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);
}
}

About the layout of a GUI

I'm in the middle of working on a program. It's GUI has two main parts, the left of the JFrame and the right of the JFrame. (Currently the right half is blank because I havn't started working on it yet).
The left part doesn't look good. All the buttons and textfields are stretched. I want them to have the height of standard buttons, similiar to the ones on this site. (You know, standard windows buttons).
How do I do that?
(I wouldn't want to simply pack() the whole thing, since the right half of the window is going to have a big square JPanel, and so pack()ing would mean that the window will still be square and the buttons on the left half would still be streched up and down).
Here's a picture:
And here's the code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class GUI extends JFrame {
JButton rect,oval,tri,free,addPoint;
JLabel xLabel,yLabel;
JTextField xTextField,yTextField;
JPanel leftPanel,rightPanel,optionsPanel,pointsPanel;
public GUI(){
initUI();
}
private void initUI(){
setLayout(new GridLayout(1,2,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setSize(500,500);
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
rightPanel = new JPanel();
optionsPanel = new JPanel();
pointsPanel = new JPanel();
add(leftPanel);
add(rightPanel);
leftPanel.setLayout(new GridLayout(2,1,5,5));
leftPanel.add(optionsPanel);
optionsPanel.setLayout(new GridLayout(1,4,2,2));
optionsPanel.add(rect);
optionsPanel.add(oval);
optionsPanel.add(tri);
optionsPanel.add(free);
leftPanel.add(pointsPanel);
pointsPanel.setLayout(new GridLayout(1,5,2,2));
pointsPanel.add(xLabel);
pointsPanel.add(xTextField);
pointsPanel.add(yLabel);
pointsPanel.add(yTextField);
pointsPanel.add(addPoint);
setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Try this
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class GUI extends JFrame {
JButton rect,oval,tri,free,addPoint;
JLabel xLabel,yLabel;
JTextField xTextField,yTextField;
JPanel leftPanel,rightPanel,optionsPanel,pointsPanel;
public GUI(){
initUI();
}
private void initUI(){
setLayout(new GridLayout(1,2,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setSize(500,500);
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
JPnel p=new JPanel();
p.add(rect);
p.add(oval);
p.add(tri);
p.add(free);
p.add(addPoint);
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
rightPanel = new JPanel();
optionsPanel = new JPanel();
pointsPanel = new JPanel();
add(leftPanel);
add(rightPanel);
leftPanel.setLayout(new GridLayout(2,1,5,5));
leftPanel.add(optionsPanel);
optionsPanel.setLayout(new GridLayout(1,4,2,2));
optionsPanel.add(p);
//optionsPanel.add(oval);
//optionsPanel.add(tri);
//optionsPanel.add(free);
leftPanel.add(pointsPanel);
pointsPanel.setLayout(new GridLayout(1,5,2,2));
pointsPanel.add(xLabel);
pointsPanel.add(xTextField);
pointsPanel.add(yLabel);
pointsPanel.add(yTextField);
pointsPanel.add(addPoint);
setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Like this for JLabels and JTextFields
Please go through following link for more information about Grid layout
How to Use GridLayout
Also try with different layouts in java swing
A Visual Guide to Layout Managers
Please try FlowLayout it is suitable for your requirement.
Just change setLayout(new FlowLayout());
Output :
You have that effect, because you use GridLayout, which resize component to whole cell(vertically/horizontally). You need to use another LayoutManager, or combinations of layouts.
For example I've changed your code with GridBagLayout:
private void initUI(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setLayout(new GridBagLayout());
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
leftPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
rightPanel = new JPanel();
rightPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
optionsPanel = new JPanel(new GridBagLayout());
pointsPanel = new JPanel(new GridBagLayout());
GridBagConstraints cMain = new GridBagConstraints();
cMain.insets = new Insets(5, 5, 5, 5);
cMain.gridx = 0;
cMain.gridy = 0;
cMain.anchor = GridBagConstraints.NORTHWEST;
add(leftPanel,cMain);
cMain.fill = GridBagConstraints.BOTH;
cMain.gridx++;
cMain.weighty = 1;
cMain.weightx = 1;
add(rightPanel,cMain);
leftPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
leftPanel.add(optionsPanel,c);
c.gridy++;
leftPanel.add(pointsPanel,c);
c.gridy = 0;
optionsPanel.add(rect,c);
c.gridx++;
optionsPanel.add(oval,c);
c.gridx++;
optionsPanel.add(tri,c);
c.gridx++;
optionsPanel.add(free,c);
c.gridx = 0;
c.gridy = 1;
pointsPanel.add(xLabel,c);
c.gridx++;
pointsPanel.add(xTextField,c);
c.gridx++;
pointsPanel.add(yLabel,c);
c.gridx++;
pointsPanel.add(yTextField,c);
c.gridx++;
pointsPanel.add(addPoint,c);
setSize(500,500);
setVisible(true);
}

Fixed size of buttons

There is a JPanel with buttons and textField. TextField filters unnecessary buttons by name. But after delete the size of rest buttons is changing.
The height of buttons must not change after filtering in the textField. How to achieve this?
public class TestViewer {
public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {
public void run() {
JDialog dialog = new TestDialog();
dialog.setLocationRelativeTo(null);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setTitle("Type text and press Enter");
dialog.setSize(300, 700);
dialog.setVisible(true);
dialog.setLocationRelativeTo(null);
dialog.setModal(true);
}
});
}
}
class TestDialog extends JDialog {
public TestDialog() {
getContentPane().add(new JPan
el(), BorderLayout.CENTER);
getContentPane().add(createBtnPanel(), BorderLayout.CENTER);
}
private JPanel createBtnPanel() {
int n = 100;
Final String ArrButtonNames[] = new String[n];
for (int h = 0; h < ArrButtonNames.length; h++) {
if ((h%2)==0){
ArrButtonNames[h]="Filter"+h;
}
else{
ArrButtonNames[h]="Button"+h;
}
}
final JButton ArrButton[] = new JButton[n];
final JPanel btnPanel = new JPanel(new GridLayout(0, ArrButtonNames.length, 1,1));
btnPanel.setLayout(new GridLayout(0, 1));
final JTextField textField = new JTextField();
textField.setColumns(23);
btnPanel.add(textField);
for (int i = 0; i < ArrButtonNames.length; i++) {
String btnString = ArrButtonNames[i];
JButton button = new JButton(btnString);
Dimension d = button.getPreferredSize();
d.setSize(d.getWidth(), d.getHeight()*1);
button.setPreferredSize(d);
button.setSize(d);
button.setMinimumSize(d);
button.setMaximumSize(d);
btnPanel.add(button);
ArrButton[i] = button;
}
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int k = 0; k < ArrButtonNames.length; k++) {
if(ArrButtonNames[k].indexOf(textField.getText())==-1) {
btnPanel.remove(ArrButton[k]);
btnPanel.revalidate();
btnPanel.repaint();
}
}
}
});
JPanel MainPanel = new JPanel();
MainPanel.setLayout(new BorderLayout());
MainPanel.add(btnPanel, BorderLayout.NORTH);
final JScrollPane scrollPane = new JScrollPane(btnPanel);
MainPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
return MainPanel;
}
}
You have that effect, because you use GridLayout, which resize components to fill whole cell.
For your purposes I recommend you to use GridBagLayout, that can do what you want.
Try to use next code for filling your btnPanel instead of yours:
final JButton ArrButton[] = new JButton[n];
final JPanel btnPanel = new JPanel();
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridx=0;
c.gridy=0;
btnPanel.setLayout(new GridBagLayout());
final JTextField textField = new JTextField();
btnPanel.add(textField,c);
for (int i = 0; i < ArrButtonNames.length; i++) {
String btnString = ArrButtonNames[i];
JButton button = new JButton(btnString);
c.gridy ++;
btnPanel.add(button,c);
ArrButton[i] = button;
}
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.gridy ++;
btnPanel.add(new JLabel(""),c);
And it looks like:
ALso use pack() method instead of setSize(...), and don't use setPreferedSize(...) and others size methods read about that here.

Categories

Resources