Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I apply an EtchedBorder to only a specific side of the border?

Tags:

java

border

swing

I have a JPanel where I want to add an EtchedBorder.Lowered to only the left border. I know this is possible with MatteBorders, but I was wondering if there was a way to do this with an EtchedBorder?

like image 336
samwell Avatar asked Dec 12 '22 01:12

samwell


2 Answers

  • use JSeparator instead of EtchedBorder.Lowered,

  • but JSeparator is by default only line, but you are able to build funny Borders

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingUtilities;

public class NestedLayout {

    private JFrame frame = new JFrame();
    private JPanel leftPanel = new JPanel();

    public NestedLayout() {
        leftPanel.setLayout(new BorderLayout());
        leftPanel.setBorder(BorderFactory.createEmptyBorder(
                10, //top
                10, //left
                10, //bottom
                10));   //right
        leftPanel.add(new JSeparator(JSeparator.VERTICAL), BorderLayout.CENTER);
        leftPanel.setPreferredSize(new Dimension(40, 40));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(leftPanel, BorderLayout.WEST);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new NestedLayout();
            }
        });
    }
}
like image 101
mKorbel Avatar answered May 19 '23 13:05

mKorbel


You can join two panels and add an 'opposite' matted border on each to recreate the etched effect :

import javax.swing.*;
import java.awt.*;

public class MainFrame extends JFrame {

    public MainFrame() {
        setLayout(new BorderLayout());

        JPanel left = new JPanel();
        left.setPreferredSize(new Dimension(200, 400));
        left.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.GRAY));
        add(left, BorderLayout.WEST);

        JPanel center = new JPanel();
        center.setPreferredSize(new Dimension(200, 400));
        center.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.WHITE));
        add(center, BorderLayout.CENTER);

        setVisible(true);
        pack();
    }

    public static void main(String[] args) {
        new MainFrame();
    }
}

enter image description here

like image 37
Yanflea Avatar answered May 19 '23 13:05

Yanflea