I'm trying to create an application where a list of numbers are listed on the WEST region of BorderLayout and corresponding panels in the CENTER. The problem is that
I need the WEST region to be wider. Right now, it contains JList in a JPanel which resizes it to its default size. Preferred size? Not sure!
I need to have an icon or alphabet character 'x' towards the right end of 1 or 2. So, that when I close it, I can close the corresponding panel on the CENTER.
CODE:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.Color;
public class Sample1 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sample1 frame = new Sample1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sample1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
panel.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
contentPane.add(panel, BorderLayout.WEST);
Vector<String> str = new Vector<>();
str.add("1");
str.add("2");
final JList list = new JList();
list.setListData(str);
panel.add(list);
final JPanel panel_1 = new JPanel();
panel_1.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
contentPane.add(panel_1, BorderLayout.CENTER);
panel_1.setLayout(new CardLayout(0, 0));
JPanel panel_2 = new JPanel();
panel_1.add(panel_2, "1");
JLabel lblNewLabel = new JLabel("First");
panel_2.add(lblNewLabel);
JPanel panel_3 = new JPanel();
panel_1.add(panel_3, "2");
JLabel lblNewLabel_1 = new JLabel("Second");
panel_3.add(lblNewLabel_1);
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e){
CardLayout layout = (CardLayout) panel_1.getLayout();
layout.show(panel_1, list.getSelectedValue().toString());
}
});
}
}
Maybe use a JTable with two columns. The second column can contain a close button. See Table Button Column for an example of this approach.
Otherwise you would need to add a panel to the WEST. The panel would contain the JList and some other component beside the JList to act as the close button. The problem with this approach is getting the components to line up and for the button to know which panel to close.
Have you tried using a GridLayout or BoxLayout also try setting up your GUI with a separate methods.
Setup GUI Code:
private void setupGUI() {
JPanel westP = setupWestPane();
getContentPane().add(westPa, BorderLayout.WEST);
}
Setup West Pane Code:
private JPanel setupWestPane() {
JPanel westP = setupWestPanel();
JPanel p = new JPanel(new GridLayout(1, 2, 20, 0));
p.setOpaque(false);
p.add(westP);
return p;
}
Setup West Panel Code :
private JPanel setupPlayerPanel() {
list1 = new JList();
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// If you want to add a listener to the listbox
// list1.addListSelectionListener(this);
JScrollPane jsp = new JScrollPane(playerList);
JPanel p = new JPanel(new BorderLayout());
p.setOpaque(false);
p.add(new JLabel("List"), BorderLayout.NORTH);
p.add(jsp, BorderLayout.CENTER);
return p;
}
The code above is just an example.
Related
I am having some issues with my Swing GUI.
It currently looks like this:
But I would like to move a couple things around.
Firstly I want the buttons underneath the keyboard
I want to add a text field on top of the keyboard with the submit button on the right hand side.
How can I accomplish this? I've tried to create a GridLayout and slot things by row,column coordinate but it doesn't seem to work.
private class Display extends JPanel {
Display() {
setPreferredSize(new Dimension(620, 420));
setBackground(new Color(250, 230, 180));
setFont(new Font("Serif", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.RED);
g.drawString(message, 30, 40);
g.drawString("00:00", 30, 410);
}
}
}
private void createWindow() {
setJMenuBar(menuBarCreator());
// The ActionListener that will respond to button clicks.
ButtonHandler buttonHandler = new ButtonHandler();
// Create the subpanels and add them to the main panel.
display = new Display();
setLayout(new BorderLayout(3, 3));
add(display, BorderLayout.CENTER);
JPanel bottom = new JPanel();
bottom.setLayout(new GridLayout(1,1));
add(bottom, BorderLayout.NORTH);
// Add keyboard
JPanel keyboard = new JPanel();
JPanel keyboardHolder = new JPanel();
keyboard.setLayout(new GridLayout(2, 13));
keyboardHolder.setLayout(new GridLayout(1, 2));
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
JButton button = new JButton(String.valueOf(alphabet));
button.addActionListener(buttonHandler);
keyboard.add(button);
alphabetButtons.add(button);
}
keyboardHolder.add(keyboard, 0,0);
add(keyboardHolder, BorderLayout.SOUTH);
// Create three buttons, register the ActionListener to respond to clicks on the
// buttons, and add them to the bottom panel.
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(buttonHandler);
keyboard.add(submitButton);
JButton startButton = new JButton(GuiText.START.toString());
startButton.addActionListener(buttonHandler);
bottom.add(startButton);
JButton nextButton = new JButton(GuiText.NEXT.toString());
nextButton.addActionListener(buttonHandler);
bottom.add(nextButton);
JButton skipButton = new JButton(GuiText.SKIP.toString());
skipButton.addActionListener(buttonHandler);
bottom.add(skipButton);
JButton quit = new JButton(GuiText.QUIT.toString());
quit.addActionListener(buttonHandler);
bottom.add(quit);
setBackground(new Color(100, 0, 0));
nextButton.setEnabled(false);
skipButton.setEnabled(false);
}
Below is a concrete example of what camickr wrote in his comment to the original question. Note that this is not the only possibility. There are many layout managers. I recommend visiting Laying Out Components Within a Container
The purpose of the code is only to show you how to achieve your desired layout.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class GuesGame implements Runnable {
private JFrame frame;
public void run() {
showGui();
}
private JPanel createBottomPanel() {
JPanel bottomPanel = new JPanel(new GridLayout(3, 1));
bottomPanel.add(createSubmitPanel());
bottomPanel.add(createKeyboardPanel());
bottomPanel.add(createButtonsPanel());
return bottomPanel;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
JButton startButton = new JButton("Start");
buttonsPanel.add(startButton);
JButton nextButton = new JButton("Next");
buttonsPanel.add(nextButton);
JButton skipButton = new JButton("Skip");
buttonsPanel.add(skipButton);
JButton quitButton = new JButton("Quit");
buttonsPanel.add(quitButton);
return buttonsPanel;
}
private JPanel createKeyboardPanel() {
JPanel keyboardPanel = new JPanel(new GridLayout(2, 13));
for (char c = 'a'; c <= 'z'; c++) {
JButton button = new JButton(String.valueOf(c));
keyboardPanel.add(button);
}
return keyboardPanel;
}
private JPanel createSubmitPanel() {
JPanel submitPanel = new JPanel();
JTextField txtFld = new JTextField(20);
submitPanel.add(txtFld);
JButton submitButton = new JButton("Submit");
submitPanel.add(submitButton);
return submitPanel;
}
private void showGui() {
frame = new JFrame("Guess Game");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(new Display(), BorderLayout.CENTER);
frame.add(createBottomPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new GuesGame());
}
}
class Display extends JPanel {
private String message;
Display() {
message = "Starting game";
setPreferredSize(new Dimension(620, 420));
setBackground(new Color(250, 230, 180));
setFont(new Font("Serif", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.RED);
g.drawString(message, 30, 40);
g.drawString("00:00", 30, 410);
}
}
}
You want three "rows" below the Display panel as follows
Text field and "submit" button.
Keyboard
Other buttons.
Hence the "bottom" panel contains three panels laid out one above the other.
The first panel is the text field and "submit" panel.
Underneath that is the "keyboard".
And underneath the keyboard are the other buttons.
Note that the default layout manager for JPanel is java.awt.FlowLayout and this layout manager is suitable for the panel containing the "submit" button and also suitable for the panel containing the other buttons.
Here is a screen capture of the running app.
I have a JDialog that looks like this:
JDialog myDialog = new JDialog();
myDialog.setLocationRelativeTo(parent);
// parent is a JPanel.
// I want the Dialog to appear in the middle of the parent JPanel.
myDialog.setModal(true);
myDialog.setLayout(new FlowLayout());
myDialog.add(new JLabel("my text", SwingConstants.CENTER));
myDialog.add(new JButton("button 1"));
myDialog.add(new JButton("button 2"));
myDialog.pack();
myDialog.setVisible(true);
The result is a dialog where the JLabel and the JButtons appear next to each other.
1) What is the most convenient way make a "line break" after the JLabel, so that the JButtons appear below the JLabel, without using setSize()? I want the size to be automatically determined so the the components fit exactly, as is done by pack().
2) When I do set a custom size, the dialog appears where I want it: the middles of parent and myDialog match. However, if I use pack() instead, the top left corner of myDialog is at the middle of the parent. What is the best way to make the middles match instead?
Nest JPanels, each using its own layout manager
Call setLocationRelativeTo(parent) after calling pack(). You need to position the window after it has been rendered.
For example:
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class SimpleGuiPanel extends JPanel {
private static final String TITLE = "This is my Dialog Title";
public SimpleGuiPanel() {
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 16f));
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
buttonPanel.add(new JButton("Button 1"));
buttonPanel.add(new JButton("Button 2"));
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(5, 5));
add(titleLabel, BorderLayout.PAGE_START);
add(buttonPanel, BorderLayout.CENTER);
}
private static void createAndShowGui() {
JPanel mainFramePanel = new JPanel();
mainFramePanel.setPreferredSize(new Dimension(500, 400));
final JFrame mainFrame = new JFrame("Main Frame");
mainFrame.add(mainFramePanel);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SimpleGuiPanel simpleGuiPanel = new SimpleGuiPanel();
final JDialog myDialog = new JDialog(mainFrame, "Dialog", ModalityType.APPLICATION_MODAL);
myDialog.getContentPane().add(simpleGuiPanel);
myDialog.pack();
mainFramePanel.add(new JButton(new AbstractAction("Show Dialog") {
#Override
public void actionPerformed(ActionEvent e) {
myDialog.setLocationRelativeTo(mainFrame);
myDialog.setVisible(true);
}
}));
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
I'll try to explain the problem as best i can.
Basically what I have is a system that takes in customer data (Customer is an object) and then adds it to an array. I have that working no problems. What I'm trying to get working is that I also have an option that should enable the user to edit a customers details. The way I'm trying to implement this is; in a separate GUI, I have a comboBox which will be populated with all of the customers first names that are currently in the arrayList. This also works.
Here is my problem - what I want to happen is that when one of the customers first names is chosen from the comboBox, it should find that object, and then fill out the JTextFields with its respective data, e.g. that customers first name should pop into the first name textField and his second name into the second name TextField etc..
I cant figure out this problem so any help is appreciated!
This is only one of a few classes, the rest of which work.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.MaskFormatter;
import javax.swing.JLabel;
import java.awt.SystemColor;
import java.text.ParseException;
import java.util.ArrayList;
import java.awt.Font;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.UIManager;
import java.awt.GridLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
public class editCustomers extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
ArrayList<Customers> customerList;
private MaskFormatter mask = null;
/**
* Create the frame.
*/
public editCustomers(ArrayList<Customers> aList) {
customerList = aList;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 700, 600);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(6, 0, 0, 0));
JPanel panel_12 = new JPanel();
panel.add(panel_12);
panel_12.setLayout(new BorderLayout(0, 0));
JLabel lblSelectACustomer = new JLabel("Select a Customer to Edit");
panel_12.add(lblSelectACustomer, BorderLayout.WEST);
JComboBox comboBox = new JComboBox();
//comboBox.setModel(new DefaultComboBoxModel());
for (Customers temp : customerList) {
comboBox.addItem(temp.getfName());
}
panel_12.add(comboBox, BorderLayout.EAST);
JPanel panel_3 = new JPanel();
panel.add(panel_3);
panel_3.setLayout(new BorderLayout(0, 0));
JLabel lbl1 = new JLabel("Edit Customers First Name");
lbl1.setVerticalAlignment(SwingConstants.TOP);
Dimension d = lbl1.getPreferredSize();
lbl1.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_3.add(lbl1, BorderLayout.WEST);
JPanel panel_8 = new JPanel();
panel_3.add(panel_8, BorderLayout.CENTER);
textField = new JTextField();
panel_8.add(textField);
textField.setColumns(30);
JPanel panel_4 = new JPanel();
panel.add(panel_4);
panel_4.setLayout(new BorderLayout(0, 0));
JLabel lbl2 = new JLabel("Edit Customers Second Name");
lbl2.setVerticalAlignment(SwingConstants.TOP);
lbl2.getPreferredSize();
lbl2.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_4.add(lbl2, BorderLayout.WEST);
JPanel panel_9 = new JPanel();
panel_4.add(panel_9, BorderLayout.CENTER);
textField_1 = new JTextField();
panel_9.add(textField_1);
textField_1.setColumns(30);
JPanel panel_5 = new JPanel();
panel.add(panel_5);
panel_5.setLayout(new BorderLayout(0, 0));
JLabel lbl3 = new JLabel("Edit Customers Address");
lbl3.setVerticalAlignment(SwingConstants.TOP);
lbl3.getPreferredSize();
lbl3.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_5.add(lbl3, BorderLayout.WEST);
JPanel panel_10 = new JPanel();
panel_5.add(panel_10, BorderLayout.CENTER);
textField_2 = new JTextField();
panel_10.add(textField_2);
textField_2.setColumns(30);
JPanel panel_6 = new JPanel();
panel.add(panel_6);
panel_6.setLayout(new BorderLayout(0, 0));
JLabel lbl4 = new JLabel("Edit Customers Date of Birth");
lbl4.setVerticalAlignment(SwingConstants.TOP);
lbl4.getPreferredSize();
lbl4.setPreferredSize(new Dimension(d.width + 50, d.height));
panel_6.add(lbl4, BorderLayout.WEST);
JPanel panel_11 = new JPanel();
panel_6.add(panel_11, BorderLayout.CENTER);
textField_3 = new JTextField();
try {
mask = new MaskFormatter("##/##/####");
mask.setPlaceholderCharacter(' ');
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField textField_3 = new JFormattedTextField(mask);
textField_3.setText("dd/mm/yyyy");
panel_11.add(textField_3);
textField_3.setColumns(30);
JPanel panel_2 = new JPanel();
panel.add(panel_2);
panel_2.setLayout(new BorderLayout(0, 0));
JPanel panel_7 = new JPanel();
panel_2.add(panel_7, BorderLayout.CENTER);
JButton btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel_7.add(btnConfirm);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
panel_7.add(btnCancel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(SystemColor.activeCaption);
contentPane.add(panel_1, BorderLayout.NORTH);
JLabel lblEditACurrent = new JLabel("Edit a Current Customer");
lblEditACurrent.setForeground(Color.BLACK);
lblEditACurrent.setFont(new Font("Arial", Font.PLAIN, 19));
lblEditACurrent.setBackground(UIManager.getColor("InternalFrame.activeTitleBackground"));
panel_1.add(lblEditACurrent);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
editCustomers frame = new editCustomers(new ArrayList<Customers>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
You can try something like this ....
Change line 63 - 67 as following. Put the customers into the combobox instead of just names.
JComboBox<Customer> comboBox = new JComboBox<>();
//comboBox.setModel(new DefaultComboBoxModel());
for (Customers temp : customerList) {
comboBox.addItem(temp);
}
Then implement an ActionListener for the combobox as following.
comboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Customer customer = comboBox.getSelectedItem();
// Use the above customer object's fields to populate your text fields
}
});
What would be the best way for me to move the buttons so they are under each other instead of beside each other (see image below)?
The code for this class is as follows. The Main method is in a different class.
package guiplay;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainGUI extends JFrame {
private JButton openReportSelection = new JButton("Open Report Viewer");
private JButton closeButton = new JButton("Close Program");
private JButton getCloseButton(){
return closeButton;
}
private JButton getOpenReportSelection(){
return openReportSelection;
}
public MainGUI(){
mainInterface();
}
private void mainInterface(){
setTitle("Program Information Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(openReportSelection);
openReportSelection.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JFrame reports = new JFrame();
new ReportGUI();
}
});
centerPanel.add(closeButton);
getCloseButton().addActionListener(new Listener());
add(centerPanel, BorderLayout.CENTER);
setSize(700,200);
setVisible(true);
}
}
You can use a BoxLayout as it aligns all elements either horizontally or vertically. Simply set BoxLayout's axis to BoxLayout.Y_AXIS.
Example:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
public class BoxLayoutExample extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BoxLayoutExample frame = new BoxLayoutExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public BoxLayoutExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 180, 150);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JButton btnOpenReportViewer = new JButton("Open Report Viewer");
contentPane.add(btnOpenReportViewer);
JButton btnCloseProgram = new JButton("Close Program");
contentPane.add(btnCloseProgram);
}
}
If you want to control the size so that they are similar to each other, you can use a grid layout by setting the JFrame's content pane to a GridLayout:
contentPane.setLayout(new GridLayout(0, 1, 0, 0)); // the value of 1 here means 1 column
Don't put the JButtons in a container that uses FlowLayout but rather one that uses another layout that allows stacking of components. A GridLayout comes to mind if the buttons are to be the same size, or if they need to be different sizes, a BoxLayout.
Check out the Layout Manager Tutorial.
You could try using a BoxLayout instead of a FlowLayout. In that case, you could have:
JPanel centerPanel = new JPanel(new BoxLayout());
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS)); // Y_AXIS will cause the components to be added vertically
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
centerPanel.setMaximumSize(new Dimension(100, 60)); // Set the maximum horizontal and vertical distances used, as BoxLayouts expand to fill the provided area
Or as Hovercraft said, you could use a GridLayout, in which case you would specify it as follows:
JPanel centerPanel = new JPanel(new GridLayout(1,0); // The "0" parameter specifies as many rows as needed, but only one column
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
centerPanel.setMaximumSize(new Dimension(100, 60)); // GridLayouts will also expand to fill the entire area, so you'll probably want some size parameters.
You could also see this link for more on BoxLayouts, or this link for more on GridLayouts.
The following code produces the above image. As you can see, the same color pink shows up differently for the JFrame than for the JButton. What fix can I make so they are exactly the same color?
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class Testing extends JFrame {
public Testing() {
super("hi");
setBackground(Color.PINK);
JPanel panel = new JPanel();
JButton jb = new JButton();
jb.setText("Here I am");
Border line = new LineBorder(Color.PINK);
Border margin = new EmptyBorder(5, 15, 5, 15);
Border compound = new CompoundBorder(line, margin);
jb.setOpaque(true);
jb.setBorder(compound);
jb.setBackground(Color.PINK);
panel.add(jb);
add(panel);
setVisible(true);
}
public static void main(String[] args){
Testing t = new Testing();
}
}
set backcolor for your panel instead of frame. problem solved.
public Testing() {
super("hi");
setBackground(Color.PINK);
JPanel panel = new JPanel();
JButton jb = new JButton();
jb.setText("Here I am");
Border line = new LineBorder(Color.PINK);
Border margin = new EmptyBorder(5, 15, 5, 15);
Border compound = new CompoundBorder(line, margin);
jb.setOpaque(true);
jb.setBorder(compound);
jb.setBackground(Color.PINK);
panel.setBackground(Color.PINK);
panel.add(jb);
add(panel);
setVisible(true);
}
The colors are the same but the code was setting the wrong thing pink. Vis.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class ColorTest extends JFrame {
public ColorTest() {
super("hi");
//setBackground(Color.PINK);
JPanel panel = new JPanel();
panel.setBackground(Color.PINK);
JButton jb = new JButton();
jb.setText("Here I am");
Border line = new LineBorder(Color.RED, 5);
Border margin = new EmptyBorder(5, 15, 5, 15);
Border compound = new CompoundBorder(line, margin);
jb.setOpaque(true);
jb.setBorder(compound);
jb.setBackground(Color.PINK);
panel.add(jb);
add(panel);
pack();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
ColorTest t = new ColorTest();
}
}
Also
Don't extend frame, just use an instance of one.
Swing GUIs should be started & updated on the EDT.